Compare commits

..

20 Commits

Author SHA1 Message Date
Ahmed Bouhuolia
3f2ab6e8f0 feat(webapp): add socket to vite server proxy 2026-01-08 22:43:42 +02:00
Ahmed Bouhuolia
f0fae7d148 Merge pull request #894 from bigcapitalhq/fix-refund-credit-notes
fix(server): refund credit note gl entries
2026-01-08 00:29:47 +02:00
Ahmed Bouhuolia
e063597a80 fix(server): refund credit note gl entries 2026-01-08 00:27:43 +02:00
Ahmed Bouhuolia
9b3f6b22d1 Merge pull request #893 from bigcapitalhq/bugs-bashing-3
fix: bugs bashing
2026-01-04 01:27:19 +02:00
Ahmed Bouhuolia
0475ce136a fix: bugs bashing
- Added English translations for customer types in `customer.json`.
- Updated `Model.ts` to improve deletion logic by filtering dependent relations.
- Introduced `BillPaymentBillSyncSubscriber` to handle bill payment events.
- Enhanced `CreateBillPaymentService` and `EditBillPaymentService` to fetch entries after insertion/updating.
- Updated `SaleInvoiceCostGLEntries` to include item entry details in GL entries.
- Refactored various components in the webapp for consistency in naming conventions.
2026-01-04 01:24:10 +02:00
Ahmed Bouhuolia
987ad992a4 Merge pull request #892 from bigcapitalhq/darkmode-ui-bugs
fix: darkmode ui bugs
2026-01-03 18:26:21 +02:00
Ahmed Bouhuolia
ee92c2815b fix: darkmode ui bugs 2026-01-03 18:24:33 +02:00
Ahmed Bouhuolia
5767f1f603 Merge pull request #890 from bigcapitalhq/named-imports-hocs
fix: account transactions don't show up
2026-01-01 22:16:02 +02:00
Ahmed Bouhuolia
885d8014c2 fix: account transactions don't show up 2026-01-01 22:13:47 +02:00
Ahmed Bouhuolia
3ffab896ed Merge pull request #889 from bigcapitalhq/revert-888-named-imports-hocs
Revert "fix: account transactions don't show up"
2026-01-01 22:13:31 +02:00
Ahmed Bouhuolia
92a5086f1f Revert "fix: account transactions don't show up" 2026-01-01 22:13:08 +02:00
Ahmed Bouhuolia
1bf9038ddc Merge pull request #888 from bigcapitalhq/named-imports-hocs
fix: account transactions don't show up
2026-01-01 22:11:56 +02:00
Ahmed Bouhuolia
2736b76ced fix: account transactions don't show up 2026-01-01 22:09:51 +02:00
Ahmed Bouhuolia
9e921b074f Merge pull request #887 from bigcapitalhq/named-imports-hocs
refactor: HOCs named imports
2026-01-01 22:00:58 +02:00
Ahmed Bouhuolia
0f377e19f3 refactor: HOCs named imports 2026-01-01 21:58:42 +02:00
Ahmed Bouhuolia
5d872798ff Merge pull request #886 from bigcapitalhq/fix-credit-note-print
fix: credit note printing
2026-01-01 17:21:36 +02:00
Ahmed Bouhuolia
0ef78a19fe fix: credit note printing 2026-01-01 17:19:06 +02:00
Ahmed Bouhuolia
70b0a4833c Merge pull request #885 from bigcapitalhq/refund-credit-notes
fix: refund credit notes
2026-01-01 17:05:36 +02:00
Ahmed Bouhuolia
ead4fc9b97 fix: refund credit notes 2026-01-01 17:03:48 +02:00
Ahmed Bouhuolia
a91a7c612f Merge pull request #882 from bigcapitalhq/bugs-bashing2
Bug fixes, refactoring, and improvements
2025-12-31 01:01:08 +02:00
63 changed files with 1082 additions and 487 deletions

View File

@@ -0,0 +1,5 @@
{
"type.business": "Business",
"type.individual": "Individual"
}

View File

@@ -48,14 +48,30 @@ export class PaginationQueryBuilder<
// No relations defined // No relations defined
return this.delete(); return this.delete();
} }
// Only check HasManyRelation and ManyToManyRelation relations, as BelongsToOneRelation are just
// foreign key references and shouldn't prevent deletion. Only dependent records should block deletion.
const dependentRelationNames = relationNames.filter((name) => {
const relation = relationMappings[name];
return relation && (
relation.relation === Model.HasManyRelation ||
relation.relation === Model.ManyToManyRelation
);
});
if (dependentRelationNames.length === 0) {
// No dependent relations defined, safe to delete
return this.delete();
}
const recordQuery = this.clone(); const recordQuery = this.clone();
relationNames.forEach((relationName: string) => { dependentRelationNames.forEach((relationName: string) => {
recordQuery.withGraphFetched(relationName); recordQuery.withGraphFetched(relationName);
}); });
const record = await recordQuery; const record = await recordQuery;
const hasRelations = relationNames.some((name) => { const hasRelations = dependentRelationNames.some((name) => {
const val = record[name]; const val = record[name];
return Array.isArray(val) ? val.length > 0 : val != null; return Array.isArray(val) ? val.length > 0 : val != null;
}); });

View File

@@ -14,6 +14,7 @@ import { BranchesSettingsService } from '../Branches/BranchesSettings';
import { BillPaymentsController } from './BillPayments.controller'; import { BillPaymentsController } from './BillPayments.controller';
import { BillPaymentGLEntries } from './commands/BillPaymentGLEntries'; import { BillPaymentGLEntries } from './commands/BillPaymentGLEntries';
import { BillPaymentGLEntriesSubscriber } from './subscribers/BillPaymentGLEntriesSubscriber'; import { BillPaymentGLEntriesSubscriber } from './subscribers/BillPaymentGLEntriesSubscriber';
import { BillPaymentBillSyncSubscriber } from './subscribers/BillPaymentBillSyncSubscriber';
import { LedgerModule } from '../Ledger/Ledger.module'; import { LedgerModule } from '../Ledger/Ledger.module';
import { AccountsModule } from '../Accounts/Accounts.module'; import { AccountsModule } from '../Accounts/Accounts.module';
import { BillPaymentsExportable } from './queries/BillPaymentsExportable'; import { BillPaymentsExportable } from './queries/BillPaymentsExportable';
@@ -39,6 +40,7 @@ import { BillPaymentsPages } from './commands/BillPaymentsPages.service';
TenancyContext, TenancyContext,
BillPaymentGLEntries, BillPaymentGLEntries,
BillPaymentGLEntriesSubscriber, BillPaymentGLEntriesSubscriber,
BillPaymentBillSyncSubscriber,
BillPaymentsExportable, BillPaymentsExportable,
BillPaymentsImportable, BillPaymentsImportable,
GetBillPaymentsService, GetBillPaymentsService,
@@ -52,4 +54,4 @@ import { BillPaymentsPages } from './commands/BillPaymentsPages.service';
], ],
controllers: [BillPaymentsController], controllers: [BillPaymentsController],
}) })
export class BillPaymentsModule {} export class BillPaymentsModule { }

View File

@@ -38,7 +38,7 @@ export class CreateBillPaymentService {
@Inject(BillPayment.name) @Inject(BillPayment.name)
private readonly billPaymentModel: TenantModelProxy<typeof BillPayment>, private readonly billPaymentModel: TenantModelProxy<typeof BillPayment>,
) {} ) { }
/** /**
* Creates a new bill payment transcations and store it to the storage * Creates a new bill payment transcations and store it to the storage
@@ -103,11 +103,19 @@ export class CreateBillPaymentService {
} as IBillPaymentCreatingPayload); } as IBillPaymentCreatingPayload);
// Writes the bill payment graph to the storage. // Writes the bill payment graph to the storage.
const billPayment = await this.billPaymentModel() const insertedBillPayment = await this.billPaymentModel()
.query(trx) .query(trx)
.insertGraphAndFetch({ .insertGraphAndFetch({
...billPaymentObj, ...billPaymentObj,
}); });
// Fetch the bill payment with entries to ensure they're loaded for the subscriber.
const billPayment = await this.billPaymentModel()
.query(trx)
.withGraphFetched('entries')
.findById(insertedBillPayment.id)
.throwIfNotFound();
// Triggers `onBillPaymentCreated` event. // Triggers `onBillPaymentCreated` event.
await this.eventPublisher.emitAsync(events.billPayment.onCreated, { await this.eventPublisher.emitAsync(events.billPayment.onCreated, {
billPayment, billPayment,

View File

@@ -29,7 +29,7 @@ export class EditBillPayment {
@Inject(Vendor.name) @Inject(Vendor.name)
private readonly vendorModel: TenantModelProxy<typeof Vendor>, private readonly vendorModel: TenantModelProxy<typeof Vendor>,
) {} ) { }
/** /**
* Edits the details of the given bill payment. * Edits the details of the given bill payment.
@@ -116,12 +116,20 @@ export class EditBillPayment {
} as IBillPaymentEditingPayload); } as IBillPaymentEditingPayload);
// Edits the bill payment transaction graph on the storage. // Edits the bill payment transaction graph on the storage.
const billPayment = await this.billPaymentModel() await this.billPaymentModel()
.query(trx) .query(trx)
.upsertGraphAndFetch({ .upsertGraph({
id: billPaymentId, id: billPaymentId,
...billPaymentObj, ...billPaymentObj,
}); });
// Fetch the bill payment with entries to ensure they're loaded for the subscriber.
const billPayment = await this.billPaymentModel()
.query(trx)
.withGraphFetched('entries')
.findById(billPaymentId)
.throwIfNotFound();
// Triggers `onBillPaymentEdited` event. // Triggers `onBillPaymentEdited` event.
await this.eventPublisher.emitAsync(events.billPayment.onEdited, { await this.eventPublisher.emitAsync(events.billPayment.onEdited, {
billPaymentId, billPaymentId,

View File

@@ -16,8 +16,6 @@ export class BillPaymentsExportable extends Exportable {
/** /**
* Retrieves the accounts data to exportable sheet. * Retrieves the accounts data to exportable sheet.
* @param {number} tenantId
* @returns
*/ */
public async exportable(query: any) { public async exportable(query: any) {
const filterQuery = (builder) => { const filterQuery = (builder) => {

View File

@@ -0,0 +1,80 @@
import {
IBillPaymentEventCreatedPayload,
IBillPaymentEventDeletedPayload,
IBillPaymentEventEditedPayload,
} from '../types/BillPayments.types';
import { BillPaymentBillSync } from '../commands/BillPaymentBillSync.service';
import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { events } from '@/common/events/events';
@Injectable()
export class BillPaymentBillSyncSubscriber {
/**
* @param {BillPaymentBillSync} billPaymentBillSync - Bill payment bill sync service.
*/
constructor(private readonly billPaymentBillSync: BillPaymentBillSync) { }
/**
* Handle bill increment/decrement payment amount
* once created, edited or deleted.
*/
@OnEvent(events.billPayment.onCreated)
async handleBillIncrementPaymentOnceCreated({
billPayment,
trx,
}: IBillPaymentEventCreatedPayload) {
// Ensure entries are available - they should be included in insertGraphAndFetch
const entries = billPayment.entries || [];
await this.billPaymentBillSync.saveChangeBillsPaymentAmount(
entries.map((entry) => ({
billId: entry.billId,
paymentAmount: entry.paymentAmount,
})),
null,
trx,
);
}
/**
* Handle bill increment/decrement payment amount once edited.
*/
@OnEvent(events.billPayment.onEdited)
async handleBillIncrementPaymentOnceEdited({
billPayment,
oldBillPayment,
trx,
}: IBillPaymentEventEditedPayload) {
const entries = billPayment.entries || [];
const oldEntries = oldBillPayment?.entries || null;
await this.billPaymentBillSync.saveChangeBillsPaymentAmount(
entries.map((entry) => ({
billId: entry.billId,
paymentAmount: entry.paymentAmount,
})),
oldEntries,
trx,
);
}
/**
* Handle revert bills payment amount once bill payment deleted.
*/
@OnEvent(events.billPayment.onDeleted)
async handleBillDecrementPaymentAmount({
oldBillPayment,
trx,
}: IBillPaymentEventDeletedPayload) {
const oldEntries = oldBillPayment.entries || [];
await this.billPaymentBillSync.saveChangeBillsPaymentAmount(
oldEntries.map((entry) => ({
billId: entry.billId,
paymentAmount: 0,
})),
oldEntries,
trx,
);
}
}

View File

@@ -7,9 +7,13 @@ import { CreditNotesRefundsApplication } from './CreditNotesRefundsApplication.s
import { CreditNoteRefundsController } from './CreditNoteRefunds.controller'; import { CreditNoteRefundsController } from './CreditNoteRefunds.controller';
import { CreditNotesModule } from '../CreditNotes/CreditNotes.module'; import { CreditNotesModule } from '../CreditNotes/CreditNotes.module';
import { GetCreditNoteRefundsService } from './queries/GetCreditNoteRefunds.service'; import { GetCreditNoteRefundsService } from './queries/GetCreditNoteRefunds.service';
import { RefundCreditNoteGLEntries } from './commands/RefundCreditNoteGLEntries';
import { RefundCreditNoteGLEntriesSubscriber } from '../CreditNotes/subscribers/RefundCreditNoteGLEntriesSubscriber';
import { LedgerModule } from '../Ledger/Ledger.module';
import { AccountsModule } from '../Accounts/Accounts.module';
@Module({ @Module({
imports: [forwardRef(() => CreditNotesModule)], imports: [forwardRef(() => CreditNotesModule), LedgerModule, AccountsModule],
providers: [ providers: [
CreateRefundCreditNoteService, CreateRefundCreditNoteService,
DeleteRefundCreditNoteService, DeleteRefundCreditNoteService,
@@ -17,8 +21,10 @@ import { GetCreditNoteRefundsService } from './queries/GetCreditNoteRefunds.serv
RefundSyncCreditNoteBalanceService, RefundSyncCreditNoteBalanceService,
CreditNotesRefundsApplication, CreditNotesRefundsApplication,
GetCreditNoteRefundsService, GetCreditNoteRefundsService,
RefundCreditNoteGLEntries,
RefundCreditNoteGLEntriesSubscriber,
], ],
exports: [RefundSyncCreditNoteBalanceService], exports: [RefundSyncCreditNoteBalanceService],
controllers: [CreditNoteRefundsController], controllers: [CreditNoteRefundsController],
}) })
export class CreditNoteRefundsModule {} export class CreditNoteRefundsModule { }

View File

@@ -1,5 +1,6 @@
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsOptional, IsPositive, IsString } from 'class-validator'; import { ToNumber, IsOptional } from '@/common/decorators/Validators';
import { IsDateString, IsNotEmpty, IsPositive, IsString } from 'class-validator';
import { IsDate } from 'class-validator'; import { IsDate } from 'class-validator';
import { IsNumber } from 'class-validator'; import { IsNumber } from 'class-validator';
@@ -10,8 +11,13 @@ export class CreditNoteRefundDto {
description: 'The id of the from account', description: 'The id of the from account',
example: 1, example: 1,
}) })
@ApiProperty({
description: 'The id of the from account',
example: 1,
})
fromAccountId: number; fromAccountId: number;
@ToNumber()
@IsNumber() @IsNumber()
@IsPositive() @IsPositive()
@IsNotEmpty() @IsNotEmpty()
@@ -21,6 +27,7 @@ export class CreditNoteRefundDto {
}) })
amount: number; amount: number;
@ToNumber()
@IsNumber() @IsNumber()
@IsOptional() @IsOptional()
@IsPositive() @IsPositive()
@@ -30,23 +37,23 @@ export class CreditNoteRefundDto {
}) })
exchangeRate?: number; exchangeRate?: number;
@IsOptional()
@IsString() @IsString()
@IsNotEmpty()
@ApiProperty({ @ApiProperty({
description: 'The reference number of the credit note refund', description: 'The reference number of the credit note refund',
example: '123456', example: '123456',
}) })
referenceNo: string; referenceNo: string;
@IsOptional()
@IsString() @IsString()
@IsNotEmpty()
@ApiProperty({ @ApiProperty({
description: 'The description of the credit note refund', description: 'The description of the credit note refund',
example: 'Credit note refund', example: 'Credit note refund',
}) })
description: string; description: string;
@IsDate() @IsDateString()
@IsNotEmpty() @IsNotEmpty()
@ApiProperty({ @ApiProperty({
description: 'The date of the credit note refund', description: 'The date of the credit note refund',
@@ -54,6 +61,7 @@ export class CreditNoteRefundDto {
}) })
date: Date; date: Date;
@ToNumber()
@IsNumber() @IsNumber()
@IsOptional() @IsOptional()
@ApiProperty({ @ApiProperty({

View File

@@ -1,10 +1,10 @@
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { renderCreditNotePaperTemplateHtml } from '@bigcapital/pdf-templates';
import { GetCreditNoteService } from './GetCreditNote.service'; import { GetCreditNoteService } from './GetCreditNote.service';
import { CreditNoteBrandingTemplate } from './CreditNoteBrandingTemplate.service'; import { CreditNoteBrandingTemplate } from './CreditNoteBrandingTemplate.service';
import { transformCreditNoteToPdfTemplate } from '../utils'; import { transformCreditNoteToPdfTemplate } from '../utils';
import { CreditNote } from '../models/CreditNote'; import { CreditNote } from '../models/CreditNote';
import { ChromiumlyTenancy } from '@/modules/ChromiumlyTenancy/ChromiumlyTenancy.service'; import { ChromiumlyTenancy } from '@/modules/ChromiumlyTenancy/ChromiumlyTenancy.service';
import { TemplateInjectable } from '@/modules/TemplateInjectable/TemplateInjectable.service';
import { EventEmitter2 } from '@nestjs/event-emitter'; import { EventEmitter2 } from '@nestjs/event-emitter';
import { PdfTemplateModel } from '@/modules/PdfTemplate/models/PdfTemplate'; import { PdfTemplateModel } from '@/modules/PdfTemplate/models/PdfTemplate';
import { CreditNotePdfTemplateAttributes } from '../types/CreditNotes.types'; import { CreditNotePdfTemplateAttributes } from '../types/CreditNotes.types';
@@ -15,7 +15,6 @@ import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
export class GetCreditNotePdf { export class GetCreditNotePdf {
/** /**
* @param {ChromiumlyTenancy} chromiumlyTenancy - Chromiumly tenancy service. * @param {ChromiumlyTenancy} chromiumlyTenancy - Chromiumly tenancy service.
* @param {TemplateInjectable} templateInjectable - Template injectable service.
* @param {GetCreditNote} getCreditNoteService - Get credit note service. * @param {GetCreditNote} getCreditNoteService - Get credit note service.
* @param {CreditNoteBrandingTemplate} creditNoteBrandingTemplate - Credit note branding template service. * @param {CreditNoteBrandingTemplate} creditNoteBrandingTemplate - Credit note branding template service.
* @param {EventEmitter2} eventPublisher - Event publisher service. * @param {EventEmitter2} eventPublisher - Event publisher service.
@@ -24,7 +23,6 @@ export class GetCreditNotePdf {
*/ */
constructor( constructor(
private readonly chromiumlyTenancy: ChromiumlyTenancy, private readonly chromiumlyTenancy: ChromiumlyTenancy,
private readonly templateInjectable: TemplateInjectable,
private readonly getCreditNoteService: GetCreditNoteService, private readonly getCreditNoteService: GetCreditNoteService,
private readonly creditNoteBrandingTemplate: CreditNoteBrandingTemplate, private readonly creditNoteBrandingTemplate: CreditNoteBrandingTemplate,
private readonly eventPublisher: EventEmitter2, private readonly eventPublisher: EventEmitter2,
@@ -36,23 +34,40 @@ export class GetCreditNotePdf {
private readonly pdfTemplateModel: TenantModelProxy< private readonly pdfTemplateModel: TenantModelProxy<
typeof PdfTemplateModel typeof PdfTemplateModel
>, >,
) {} ) { }
/** /**
* Retrieves sale invoice pdf content. * Retrieves credit note html content.
* @param {number} creditNoteId - Credit note id.
* @returns {Promise<string>}
*/
public async getCreditNoteHtml(creditNoteId: number): Promise<string> {
const brandingAttributes =
await this.getCreditNoteBrandingAttributes(creditNoteId);
// Map attributes to match the React component props
// The branding template returns companyLogoUri, but type may have companyLogo
const props = {
...brandingAttributes,
companyLogoUri:
(brandingAttributes as any).companyLogoUri ||
(brandingAttributes as any).companyLogo ||
'',
};
return renderCreditNotePaperTemplateHtml(props);
}
/**
* Retrieves credit note pdf content.
* @param {number} creditNoteId - Credit note id. * @param {number} creditNoteId - Credit note id.
* @returns {Promise<[Buffer, string]>} * @returns {Promise<[Buffer, string]>}
*/ */
public async getCreditNotePdf( public async getCreditNotePdf(
creditNoteId: number, creditNoteId: number,
): Promise<[Buffer, string]> { ): Promise<[Buffer, string]> {
const brandingAttributes =
await this.getCreditNoteBrandingAttributes(creditNoteId);
const htmlContent = await this.templateInjectable.render(
'modules/credit-note-standard',
brandingAttributes,
);
const filename = await this.getCreditNoteFilename(creditNoteId); const filename = await this.getCreditNoteFilename(creditNoteId);
const htmlContent = await this.getCreditNoteHtml(creditNoteId);
const document = const document =
await this.chromiumlyTenancy.convertHtmlContent(htmlContent); await this.chromiumlyTenancy.convertHtmlContent(htmlContent);

View File

@@ -10,6 +10,7 @@ import {
import { FinancialSheet } from '../../common/FinancialSheet'; import { FinancialSheet } from '../../common/FinancialSheet';
import { JournalSheetRepository } from './JournalSheetRepository'; import { JournalSheetRepository } from './JournalSheetRepository';
import { ILedgerEntry } from '@/modules/Ledger/types/Ledger.types'; import { ILedgerEntry } from '@/modules/Ledger/types/Ledger.types';
import { getTransactionTypeLabel } from '@/modules/BankingTransactions/utils';
export class JournalSheet extends FinancialSheet { export class JournalSheet extends FinancialSheet {
readonly query: IJournalReportQuery; readonly query: IJournalReportQuery;
@@ -97,10 +98,13 @@ export class JournalSheet extends FinancialSheet {
transactionType: groupEntry.transactionType, transactionType: groupEntry.transactionType,
referenceId: groupEntry.transactionId, referenceId: groupEntry.transactionId,
referenceTypeFormatted: this.i18n.t(groupEntry.transactionType), referenceTypeFormatted: this.i18n.t(
getTransactionTypeLabel(
groupEntry.transactionType,
groupEntry.transactionSubType,
),
),
entries: this.entriesMapper(entriesGroup), entries: this.entriesMapper(entriesGroup),
currencyCode: this.baseCurrency, currencyCode: this.baseCurrency,
credit: totalCredit, credit: totalCredit,

View File

@@ -6,6 +6,7 @@ import { SaleInvoice } from '@/modules/SaleInvoices/models/SaleInvoice';
import { SaleReceipt } from '@/modules/SaleReceipts/models/SaleReceipt'; import { SaleReceipt } from '@/modules/SaleReceipts/models/SaleReceipt';
import { Item } from '@/modules/Items/models/Item'; import { Item } from '@/modules/Items/models/Item';
import { BaseModel } from '@/models/Model'; import { BaseModel } from '@/models/Model';
import { ItemEntry } from '@/modules/TransactionItemEntry/models/ItemEntry';
export class InventoryCostLotTracker extends BaseModel { export class InventoryCostLotTracker extends BaseModel {
date: Date; date: Date;
@@ -27,6 +28,7 @@ export class InventoryCostLotTracker extends BaseModel {
warehouseId: number; warehouseId: number;
item?: Item; item?: Item;
itemEntry?: ItemEntry;
invoice?: SaleInvoice; invoice?: SaleInvoice;
receipt?: SaleReceipt; receipt?: SaleReceipt;

View File

@@ -20,7 +20,7 @@ export class InventoryCostSubscriber {
private readonly itemsQuantitySync: InventoryItemsQuantitySyncService, private readonly itemsQuantitySync: InventoryItemsQuantitySyncService,
private readonly inventoryService: InventoryComputeCostService, private readonly inventoryService: InventoryComputeCostService,
private readonly importAls: ImportAls, private readonly importAls: ImportAls,
) {} ) { }
/** /**
* Sync inventory items quantity once inventory transactions created. * Sync inventory items quantity once inventory transactions created.
@@ -60,7 +60,7 @@ export class InventoryCostSubscriber {
* Marks items cost compute running state. * Marks items cost compute running state.
*/ */
@OnEvent(events.inventory.onInventoryTransactionsCreated) @OnEvent(events.inventory.onInventoryTransactionsCreated)
async markGlobalSettingsComputeItems({}) { async markGlobalSettingsComputeItems({ }) {
await this.inventoryService.markItemsCostComputeRunning(true); await this.inventoryService.markItemsCostComputeRunning(true);
} }
@@ -68,7 +68,7 @@ export class InventoryCostSubscriber {
* Marks items cost compute as completed. * Marks items cost compute as completed.
*/ */
@OnEvent(events.inventory.onInventoryCostEntriesWritten) @OnEvent(events.inventory.onInventoryCostEntriesWritten)
async markGlobalSettingsComputeItemsCompeted({}) { async markGlobalSettingsComputeItemsCompeted({ }) {
await this.inventoryService.markItemsCostComputeRunning(false); await this.inventoryService.markItemsCostComputeRunning(false);
} }
@@ -80,15 +80,13 @@ export class InventoryCostSubscriber {
itemId, itemId,
startingDate, startingDate,
}: IComputeItemCostJobCompletedPayload) { }: IComputeItemCostJobCompletedPayload) {
// const dependsComputeJobs = await this.agenda.jobs({ // Convert startingDate to Date if it's a string
// name: 'compute-item-cost', const startingDateObj = startingDate instanceof Date
// nextRunAt: { $ne: null }, ? startingDate
// 'data.tenantId': tenantId, : new Date(startingDate);
// });
// // There is no scheduled compute jobs waiting. // Write GL entries for inventory cost lots after cost computation completes
// if (dependsComputeJobs.length === 0) { await this.saleInvoicesCost.writeCostLotsGLEntries(startingDateObj);
// await this.saleInvoicesCost.scheduleWriteJournalEntries(startingDate);
// }
} }
/** /**

View File

@@ -38,7 +38,8 @@ export class SaleInvoiceCostGLEntries {
.modify('filterDateRange', startingDate) .modify('filterDateRange', startingDate)
.orderBy('date', 'ASC') .orderBy('date', 'ASC')
.withGraphFetched('invoice') .withGraphFetched('invoice')
.withGraphFetched('item'); .withGraphFetched('item')
.withGraphFetched('itemEntry');
const ledger = this.getInventoryCostLotsLedger(inventoryCostLotTrans); const ledger = this.getInventoryCostLotsLedger(inventoryCostLotTrans);
@@ -79,6 +80,9 @@ export class SaleInvoiceCostGLEntries {
transactionType: inventoryCostLot.transactionType, transactionType: inventoryCostLot.transactionType,
transactionId: inventoryCostLot.transactionId, transactionId: inventoryCostLot.transactionId,
transactionNumber: inventoryCostLot.invoice.invoiceNo,
referenceNumber: inventoryCostLot.invoice.referenceNo,
date: inventoryCostLot.date, date: inventoryCostLot.date,
indexGroup: 20, indexGroup: 20,
costable: true, costable: true,
@@ -105,6 +109,9 @@ export class SaleInvoiceCostGLEntries {
const costAccountId = const costAccountId =
inventoryCostLot.costAccountId || inventoryCostLot.item.costAccountId; inventoryCostLot.costAccountId || inventoryCostLot.item.costAccountId;
// Get description from item entry if available
const description = inventoryCostLot.itemEntry?.description || null;
// XXX Debit - Cost account. // XXX Debit - Cost account.
const costEntry = { const costEntry = {
...commonEntry, ...commonEntry,
@@ -112,6 +119,7 @@ export class SaleInvoiceCostGLEntries {
accountId: costAccountId, accountId: costAccountId,
accountNormal: AccountNormal.DEBIT, accountNormal: AccountNormal.DEBIT,
itemId: inventoryCostLot.itemId, itemId: inventoryCostLot.itemId,
note: description,
index: getIndexIncrement(), index: getIndexIncrement(),
}; };
// XXX Credit - Inventory account. // XXX Credit - Inventory account.
@@ -121,6 +129,7 @@ export class SaleInvoiceCostGLEntries {
accountId: inventoryCostLot.item.inventoryAccountId, accountId: inventoryCostLot.item.inventoryAccountId,
accountNormal: AccountNormal.DEBIT, accountNormal: AccountNormal.DEBIT,
itemId: inventoryCostLot.itemId, itemId: inventoryCostLot.itemId,
note: description,
index: getIndexIncrement(), index: getIndexIncrement(),
}; };
return [costEntry, inventoryEntry]; return [costEntry, inventoryEntry];

View File

@@ -1,15 +1,18 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { events } from '@/common/events/events';
import { IInventoryCostLotsGLEntriesWriteEvent } from '@/modules/InventoryCost/types/InventoryCost.types'; import { IInventoryCostLotsGLEntriesWriteEvent } from '@/modules/InventoryCost/types/InventoryCost.types';
import { SaleInvoiceCostGLEntries } from '../SaleInvoiceCostGLEntries'; import { SaleInvoiceCostGLEntries } from '../SaleInvoiceCostGLEntries';
@Injectable() @Injectable()
export class InvoiceCostGLEntriesSubscriber { export class InvoiceCostGLEntriesSubscriber {
constructor(private readonly invoiceCostEntries: SaleInvoiceCostGLEntries) {} constructor(private readonly invoiceCostEntries: SaleInvoiceCostGLEntries) { }
/** /**
* Writes the invoices cost GL entries once the inventory cost lots be written. * Writes the invoices cost GL entries once the inventory cost lots be written.
* @param {IInventoryCostLotsGLEntriesWriteEvent} * @param {IInventoryCostLotsGLEntriesWriteEvent}
*/ */
@OnEvent(events.inventory.onCostLotsGLEntriesWrite)
async writeInvoicesCostEntriesOnCostLotsWritten({ async writeInvoicesCostEntriesOnCostLotsWritten({
trx, trx,
startingDate, startingDate,

View File

@@ -2,19 +2,35 @@ import { Injectable } from '@nestjs/common';
import { DeleteRefundVendorCreditService } from './commands/DeleteRefundVendorCredit.service'; import { DeleteRefundVendorCreditService } from './commands/DeleteRefundVendorCredit.service';
import { RefundVendorCredit } from './models/RefundVendorCredit'; import { RefundVendorCredit } from './models/RefundVendorCredit';
import { CreateRefundVendorCredit } from './commands/CreateRefundVendorCredit.service'; import { CreateRefundVendorCredit } from './commands/CreateRefundVendorCredit.service';
import { IRefundVendorCreditDTO } from './types/VendorCreditRefund.types';
import { RefundVendorCreditDto } from './dtos/RefundVendorCredit.dto'; import { RefundVendorCreditDto } from './dtos/RefundVendorCredit.dto';
import { GetRefundVendorCreditsService } from './queries/GetRefundVendorCredits.service';
import { IRefundVendorCreditPOJO } from './types/VendorCreditRefund.types';
@Injectable() @Injectable()
export class VendorCreditsRefundApplication { export class VendorCreditsRefundApplication {
/** /**
* @param {CreateRefundVendorCredit} createRefundVendorCreditService * @param {CreateRefundVendorCredit} createRefundVendorCreditService
* @param {DeleteRefundVendorCreditService} deleteRefundVendorCreditService * @param {DeleteRefundVendorCreditService} deleteRefundVendorCreditService
* @param {GetRefundVendorCreditsService} getRefundVendorCreditsService
*/ */
constructor( constructor(
private readonly createRefundVendorCreditService: CreateRefundVendorCredit, private readonly createRefundVendorCreditService: CreateRefundVendorCredit,
private readonly deleteRefundVendorCreditService: DeleteRefundVendorCreditService, private readonly deleteRefundVendorCreditService: DeleteRefundVendorCreditService,
) {} private readonly getRefundVendorCreditsService: GetRefundVendorCreditsService,
) { }
/**
* Retrieve the vendor credit refunds graph.
* @param {number} vendorCreditId - Vendor credit id.
* @returns {Promise<IRefundVendorCreditPOJO[]>}
*/
public getVendorCreditRefunds(
vendorCreditId: number,
): Promise<IRefundVendorCreditPOJO[]> {
return this.getRefundVendorCreditsService.getVendorCreditRefunds(
vendorCreditId,
);
}
/** /**
* Creates a refund vendor credit. * Creates a refund vendor credit.

View File

@@ -1,4 +1,4 @@
import { Body, Controller, Delete, Param, Post } from '@nestjs/common'; import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common';
import { VendorCreditsRefundApplication } from './VendorCreditsRefund.application'; import { VendorCreditsRefundApplication } from './VendorCreditsRefund.application';
import { RefundVendorCredit } from './models/RefundVendorCredit'; import { RefundVendorCredit } from './models/RefundVendorCredit';
import { ApiOperation, ApiTags } from '@nestjs/swagger'; import { ApiOperation, ApiTags } from '@nestjs/swagger';
@@ -9,7 +9,22 @@ import { RefundVendorCreditDto } from './dtos/RefundVendorCredit.dto';
export class VendorCreditsRefundController { export class VendorCreditsRefundController {
constructor( constructor(
private readonly vendorCreditsRefundApplication: VendorCreditsRefundApplication, private readonly vendorCreditsRefundApplication: VendorCreditsRefundApplication,
) {} ) { }
/**
* Retrieve the vendor credit refunds graph.
* @param {number} vendorCreditId - Vendor credit id.
* @returns {Promise<IRefundVendorCreditPOJO[]>}
*/
@Get(':vendorCreditId/refund')
@ApiOperation({ summary: 'Retrieve the vendor credit refunds graph.' })
public getVendorCreditRefunds(
@Param('vendorCreditId') vendorCreditId: string,
) {
return this.vendorCreditsRefundApplication.getVendorCreditRefunds(
Number(vendorCreditId),
);
}
/** /**
* Creates a refund vendor credit. * Creates a refund vendor credit.
@@ -17,7 +32,7 @@ export class VendorCreditsRefundController {
* @param {IRefundVendorCreditDTO} refundVendorCreditDTO * @param {IRefundVendorCreditDTO} refundVendorCreditDTO
* @returns {Promise<RefundVendorCredit>} * @returns {Promise<RefundVendorCredit>}
*/ */
@Post(':vendorCreditId/refunds') @Post(':vendorCreditId/refund')
@ApiOperation({ summary: 'Create a refund for the given vendor credit.' }) @ApiOperation({ summary: 'Create a refund for the given vendor credit.' })
public async createRefundVendorCredit( public async createRefundVendorCredit(
@Param('vendorCreditId') vendorCreditId: string, @Param('vendorCreditId') vendorCreditId: string,

View File

@@ -6,15 +6,21 @@ import { VendorCreditsRefundApplication } from './VendorCreditsRefund.applicatio
import { CreateRefundVendorCredit } from './commands/CreateRefundVendorCredit.service'; import { CreateRefundVendorCredit } from './commands/CreateRefundVendorCredit.service';
import { WarehousesModule } from '../Warehouses/Warehouses.module'; import { WarehousesModule } from '../Warehouses/Warehouses.module';
import { BranchesModule } from '../Branches/Branches.module'; import { BranchesModule } from '../Branches/Branches.module';
import { RefundVendorCreditGLEntries } from './commands/RefundVendorCreditGLEntries';
import { RefundVendorCreditGLEntriesSubscriber } from './subscribers/RefundVendorCreditGLEntriesSubscriber';
import { LedgerModule } from '../Ledger/Ledger.module';
import { AccountsModule } from '../Accounts/Accounts.module';
@Module({ @Module({
imports: [WarehousesModule, BranchesModule], imports: [WarehousesModule, BranchesModule, LedgerModule, AccountsModule],
providers: [ providers: [
GetRefundVendorCreditsService, GetRefundVendorCreditsService,
DeleteRefundVendorCreditService, DeleteRefundVendorCreditService,
CreateRefundVendorCredit, CreateRefundVendorCredit,
VendorCreditsRefundApplication VendorCreditsRefundApplication,
RefundVendorCreditGLEntries,
RefundVendorCreditGLEntriesSubscriber,
], ],
controllers: [VendorCreditsRefundController], controllers: [VendorCreditsRefundController],
}) })
export class VendorCreditsRefundModule {} export class VendorCreditsRefundModule { }

View File

@@ -1,159 +1,172 @@
// import { Inject, Service } from 'typedi'; import { LedgerStorageService } from '@/modules/Ledger/LedgerStorage.service';
// import { Knex } from 'knex'; import { Inject, Injectable } from '@nestjs/common';
// import { AccountNormal, ILedgerEntry } from '@/interfaces'; import { RefundVendorCredit } from '../models/RefundVendorCredit';
// import { IRefundVendorCredit } from '@/interfaces'; import { Ledger } from '@/modules/Ledger/Ledger';
// import JournalPosterService from '@/services/Sales/JournalPosterService'; import { Knex } from 'knex';
// import LedgerRepository from '@/services/Ledger/LedgerRepository'; import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
// import HasTenancyService from '@/services/Tenancy/TenancyService'; import { Account } from '@/modules/Accounts/models/Account.model';
import { ILedgerEntry } from '@/modules/Ledger/types/Ledger.types';
import { AccountNormal } from '@/interfaces/Account';
import { AccountRepository } from '@/modules/Accounts/repositories/Account.repository';
// @Service() @Injectable()
// export default class RefundVendorCreditGLEntries { export class RefundVendorCreditGLEntries {
// @Inject() constructor(
// private journalService: JournalPosterService; private readonly ledgerStorage: LedgerStorageService,
private readonly accountRepository: AccountRepository,
// @Inject() @Inject(Account.name)
// private ledgerRepository: LedgerRepository; private readonly accountModel: TenantModelProxy<typeof Account>,
// @Inject() @Inject(RefundVendorCredit.name)
// private tenancy: HasTenancyService; private readonly refundVendorCreditModel: TenantModelProxy<
typeof RefundVendorCredit
>,
) { }
// /** /**
// * Retrieves the refund credit common GL entry. * Retrieves the refund vendor credit common GL entry.
// * @param {IRefundVendorCredit} refundCredit * @param {RefundVendorCredit} refundVendorCredit
// */ * @returns
// private getRefundCreditGLCommonEntry = ( */
// refundCredit: IRefundVendorCredit private getRefundVendorCreditCommonGLEntry = (
// ) => { refundVendorCredit: RefundVendorCredit,
// return { ) => {
// exchangeRate: refundCredit.exchangeRate, const model = refundVendorCredit as any;
// currencyCode: refundCredit.currencyCode, return {
currencyCode: refundVendorCredit.currencyCode,
exchangeRate: refundVendorCredit.exchangeRate,
// transactionType: 'RefundVendorCredit', transactionType: 'RefundVendorCredit',
// transactionId: refundCredit.id, transactionId: refundVendorCredit.id,
date: refundVendorCredit.date,
userId: refundVendorCredit.vendorCredit?.userId,
// date: refundCredit.date, referenceNumber: refundVendorCredit.referenceNo,
// userId: refundCredit.userId,
// referenceNumber: refundCredit.referenceNo,
// createdAt: refundCredit.createdAt,
// indexGroup: 10,
// credit: 0, createdAt: model.createdAt,
// debit: 0, indexGroup: 10,
// note: refundCredit.description, credit: 0,
// branchId: refundCredit.branchId, debit: 0,
// };
// };
// /** note: refundVendorCredit.description,
// * Retrieves the refund credit payable GL entry. branchId: refundVendorCredit.branchId,
// * @param {IRefundVendorCredit} refundCredit };
// * @param {number} APAccountId };
// * @returns {ILedgerEntry}
// */
// private getRefundCreditGLPayableEntry = (
// refundCredit: IRefundVendorCredit,
// APAccountId: number
// ): ILedgerEntry => {
// const commonEntry = this.getRefundCreditGLCommonEntry(refundCredit);
// return { /**
// ...commonEntry, * Retrieves the refund vendor credit payable GL entry.
// credit: refundCredit.amount, * @param {RefundVendorCredit} refundVendorCredit
// accountId: APAccountId, * @param {number} APAccountId
// contactId: refundCredit.vendorCredit.vendorId, * @returns {ILedgerEntry}
// index: 1, */
// accountNormal: AccountNormal.CREDIT, private getRefundVendorCreditGLPayableEntry = (
// }; refundVendorCredit: RefundVendorCredit,
// }; APAccountId: number,
): ILedgerEntry => {
const commonEntry = this.getRefundVendorCreditCommonGLEntry(
refundVendorCredit,
);
// /** return {
// * Retrieves the refund credit deposit GL entry. ...commonEntry,
// * @param {IRefundVendorCredit} refundCredit credit: refundVendorCredit.amount,
// * @returns {ILedgerEntry} accountId: APAccountId,
// */ contactId: refundVendorCredit.vendorCredit.vendorId,
// private getRefundCreditGLDepositEntry = ( index: 1,
// refundCredit: IRefundVendorCredit accountNormal: AccountNormal.CREDIT,
// ): ILedgerEntry => { };
// const commonEntry = this.getRefundCreditGLCommonEntry(refundCredit); };
// return { /**
// ...commonEntry, * Retrieves the refund vendor credit deposit GL entry.
// debit: refundCredit.amount, * @param {RefundVendorCredit} refundVendorCredit
// accountId: refundCredit.depositAccountId, * @returns {ILedgerEntry}
// index: 2, */
// accountNormal: AccountNormal.DEBIT, private getRefundVendorCreditGLDepositEntry = (
// }; refundVendorCredit: RefundVendorCredit,
// }; ): ILedgerEntry => {
const commonEntry = this.getRefundVendorCreditCommonGLEntry(
refundVendorCredit,
);
// /** return {
// * Retrieve refund vendor credit GL entries. ...commonEntry,
// * @param {IRefundVendorCredit} refundCredit debit: refundVendorCredit.amount,
// * @param {number} APAccountId accountId: refundVendorCredit.depositAccountId,
// * @returns {ILedgerEntry[]} index: 2,
// */ accountNormal: AccountNormal.DEBIT,
// public getRefundCreditGLEntries = ( };
// refundCredit: IRefundVendorCredit, };
// APAccountId: number
// ): ILedgerEntry[] => {
// const payableEntry = this.getRefundCreditGLPayableEntry(
// refundCredit,
// APAccountId
// );
// const depositEntry = this.getRefundCreditGLDepositEntry(refundCredit);
// return [payableEntry, depositEntry]; /**
// }; * Retrieve refund vendor credit GL entries.
* @param {RefundVendorCredit} refundVendorCredit
* @param {number} APAccountId
* @returns {ILedgerEntry[]}
*/
public getRefundVendorCreditGLEntries(
refundVendorCredit: RefundVendorCredit,
APAccountId: number,
): ILedgerEntry[] {
const payableEntry = this.getRefundVendorCreditGLPayableEntry(
refundVendorCredit,
APAccountId,
);
const depositEntry = this.getRefundVendorCreditGLDepositEntry(
refundVendorCredit,
);
// /** return [payableEntry, depositEntry];
// * Saves refund credit note GL entries. }
// * @param {number} tenantId
// * @param {IRefundVendorCredit} refundCredit -
// * @param {Knex.Transaction} trx -
// * @return {Promise<void>}
// */
// public saveRefundCreditGLEntries = async (
// tenantId: number,
// refundCreditId: number,
// trx?: Knex.Transaction
// ): Promise<void> => {
// const { Account, RefundVendorCredit } = this.tenancy.models(tenantId);
// // Retireve refund with associated vendor credit entity. /**
// const refundCredit = await RefundVendorCredit.query() * Creates refund vendor credit GL entries.
// .findById(refundCreditId) * @param {number} refundVendorCreditId
// .withGraphFetched('vendorCredit'); * @param {Knex.Transaction} trx
*/
public createRefundVendorCreditGLEntries = async (
refundVendorCreditId: number,
trx?: Knex.Transaction,
) => {
// Retrieve the refund with associated vendor credit.
const refundVendorCredit = await this.refundVendorCreditModel()
.query(trx)
.findById(refundVendorCreditId)
.withGraphFetched('vendorCredit');
// const payableAccount = await Account.query().findOne( // Retrieve the payable account (A/P) account based on the given currency.
// 'slug', const APAccount = await this.accountRepository.findOrCreateAccountsPayable(
// 'accounts-payable' refundVendorCredit.currencyCode,
// ); {},
// // Generates the GL entries of the given refund credit. trx,
// const entries = this.getRefundCreditGLEntries( );
// refundCredit,
// payableAccount.id
// );
// // Saves the ledegr to the storage.
// await this.ledgerRepository.saveLedgerEntries(tenantId, entries, trx);
// };
// /** // Retrieve refund vendor credit GL entries.
// * Reverts refund credit note GL entries. const refundGLEntries = this.getRefundVendorCreditGLEntries(
// * @param {number} tenantId refundVendorCredit,
// * @param {number} refundCreditId APAccount.id,
// * @param {Knex.Transaction} trx );
// * @return {Promise<void>} const ledger = new Ledger(refundGLEntries);
// */
// public revertRefundCreditGLEntries = async ( // Saves refund ledger entries.
// tenantId: number, await this.ledgerStorage.commit(ledger, trx);
// refundCreditId: number, };
// trx?: Knex.Transaction
// ) => { /**
// await this.journalService.revertJournalTransactions( * Reverts refund vendor credit GL entries.
// tenantId, * @param {number} refundVendorCreditId
// refundCreditId, * @param {Knex.Transaction} trx
// 'RefundVendorCredit', */
// trx public revertRefundVendorCreditGLEntries = async (
// ); refundVendorCreditId: number,
// }; trx?: Knex.Transaction,
// } ) => {
await this.ledgerStorage.deleteByReference(
refundVendorCreditId,
'RefundVendorCredit',
trx,
);
};
}

View File

@@ -1,10 +1,12 @@
import { IsOptional, ToNumber } from '@/common/decorators/Validators';
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from '@nestjs/swagger';
import { Min } from 'class-validator'; import { IsDateString, Min } from 'class-validator';
import { IsString } from 'class-validator'; import { IsString } from 'class-validator';
import { IsDate } from 'class-validator'; import { IsDate } from 'class-validator';
import { IsNotEmpty, IsNumber, IsOptional, IsPositive } from 'class-validator'; import { IsNotEmpty, IsNumber, IsPositive } from 'class-validator';
export class RefundVendorCreditDto { export class RefundVendorCreditDto {
@ToNumber()
@IsNumber() @IsNumber()
@IsNotEmpty() @IsNotEmpty()
@Min(0) @Min(0)
@@ -32,6 +34,7 @@ export class RefundVendorCreditDto {
}) })
depositAccountId: number; depositAccountId: number;
@IsOptional()
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
@ApiProperty({ @ApiProperty({
@@ -40,7 +43,7 @@ export class RefundVendorCreditDto {
}) })
description: string; description: string;
@IsDate() @IsDateString()
@IsNotEmpty() @IsNotEmpty()
@ApiProperty({ @ApiProperty({
description: 'The date of the refund', description: 'The date of the refund',

View File

@@ -0,0 +1,48 @@
import { events } from '@/common/events/events';
import { RefundVendorCreditGLEntries } from '../commands/RefundVendorCreditGLEntries';
import {
IRefundVendorCreditCreatedPayload,
IRefundVendorCreditDeletedPayload,
} from '../types/VendorCreditRefund.types';
import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
@Injectable()
export class RefundVendorCreditGLEntriesSubscriber {
constructor(
private readonly refundVendorCreditGLEntries: RefundVendorCreditGLEntries,
) { }
/**
* Writes refund vendor credit GL entries once the transaction created.
* @param {IRefundVendorCreditCreatedPayload} payload -
*/
@OnEvent(events.vendorCredit.onRefundCreated)
async writeRefundVendorCreditGLEntriesOnceCreated({
trx,
refundVendorCredit,
vendorCredit,
}: IRefundVendorCreditCreatedPayload) {
await this.refundVendorCreditGLEntries.createRefundVendorCreditGLEntries(
refundVendorCredit.id,
trx,
);
}
/**
* Reverts refund vendor credit GL entries once the transaction deleted.
* @param {IRefundVendorCreditDeletedPayload} payload -
*/
@OnEvent(events.vendorCredit.onRefundDeleted)
async revertRefundVendorCreditGLEntriesOnceDeleted({
trx,
refundCreditId,
oldRefundCredit,
}: IRefundVendorCreditDeletedPayload) {
await this.refundVendorCreditGLEntries.revertRefundVendorCreditGLEntries(
refundCreditId,
trx,
);
}
}

View File

@@ -0,0 +1,37 @@
import { Controller, Get, Param } from '@nestjs/common';
import { WarehousesApplication } from './WarehousesApplication.service';
import {
ApiOperation,
ApiParam,
ApiResponse,
ApiTags,
} from '@nestjs/swagger';
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
@Controller('items')
@ApiTags('Warehouses')
@ApiCommonHeaders()
export class WarehouseItemsController {
constructor(private warehousesApplication: WarehousesApplication) { }
@Get(':id/warehouses')
@ApiOperation({
summary: 'Retrieves the item associated warehouses.',
})
@ApiResponse({
status: 200,
description:
'The item associated warehouses have been successfully retrieved.',
})
@ApiResponse({ status: 404, description: 'The item not found.' })
@ApiParam({
name: 'id',
required: true,
type: Number,
description: 'The item id',
})
getItemWarehouses(@Param('id') itemId: string) {
return this.warehousesApplication.getItemWarehouses(Number(itemId));
}
}

View File

@@ -85,10 +85,4 @@ export class WarehousesController {
markWarehousePrimary(@Param('id') warehouseId: string) { markWarehousePrimary(@Param('id') warehouseId: string) {
return this.warehousesApplication.markWarehousePrimary(Number(warehouseId)); return this.warehousesApplication.markWarehousePrimary(Number(warehouseId));
} }
@Get('items/:itemId')
@ApiOperation({ summary: 'Get item warehouses' })
getItemWarehouses(@Param('itemId') itemId: string) {
return this.warehousesApplication.getItemWarehouses(Number(itemId));
}
} }

View File

@@ -7,6 +7,7 @@ import { CreateWarehouse } from './commands/CreateWarehouse.service';
import { EditWarehouse } from './commands/EditWarehouse.service'; import { EditWarehouse } from './commands/EditWarehouse.service';
import { DeleteWarehouseService } from './commands/DeleteWarehouse.service'; import { DeleteWarehouseService } from './commands/DeleteWarehouse.service';
import { WarehousesController } from './Warehouses.controller'; import { WarehousesController } from './Warehouses.controller';
import { WarehouseItemsController } from './WarehouseItems.controller';
import { GetWarehouse } from './queries/GetWarehouse'; import { GetWarehouse } from './queries/GetWarehouse';
import { WarehouseMarkPrimary } from './commands/WarehouseMarkPrimary.service'; import { WarehouseMarkPrimary } from './commands/WarehouseMarkPrimary.service';
import { GetWarehouses } from './queries/GetWarehouses'; import { GetWarehouses } from './queries/GetWarehouses';
@@ -47,7 +48,7 @@ const models = [RegisterTenancyModel(Warehouse)];
@Module({ @Module({
imports: [TenancyDatabaseModule, ...models], imports: [TenancyDatabaseModule, ...models],
controllers: [WarehousesController], controllers: [WarehousesController, WarehouseItemsController],
providers: [ providers: [
CreateWarehouse, CreateWarehouse,
EditWarehouse, EditWarehouse,
@@ -90,6 +91,6 @@ const models = [RegisterTenancyModel(Warehouse)];
InventoryTransactionsWarehouses, InventoryTransactionsWarehouses,
ValidateWarehouseExistance ValidateWarehouseExistance
], ],
exports: [WarehousesSettings, WarehouseTransactionDTOTransform, ...models], exports: [WarehousesSettings, WarehouseTransactionDTOTransform, WarehousesApplication, ...models],
}) })
export class WarehousesModule {} export class WarehousesModule {}

View File

@@ -1,5 +1,5 @@
// @ts-nocheck // @ts-nocheck
import React from 'react'; import React, { useMemo } from 'react';
import { Position, Checkbox, InputGroup } from '@blueprintjs/core'; import { Position, Checkbox, InputGroup } from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime'; import { DateInput } from '@blueprintjs/datetime';
import moment from 'moment'; import moment from 'moment';
@@ -7,23 +7,29 @@ import intl from 'react-intl-universal';
import { isUndefined } from 'lodash'; import { isUndefined } from 'lodash';
import { useAutofocus } from '@/hooks'; import { useAutofocus } from '@/hooks';
import { T, Choose, ListSelect } from '@/components'; import { T, Choose } from '@/components';
import { Select } from '@/components/Forms';
import { momentFormatter } from '@/utils'; import { momentFormatter } from '@/utils';
function AdvancedFilterEnumerationField({ options, value, ...rest }) { function AdvancedFilterEnumerationField({ options, value, ...rest }) {
const selectedItem = useMemo(
() => options.find((opt) => opt.key === value) || null,
[options, value],
);
return ( return (
<ListSelect <Select
items={options} items={options}
selectedItem={value} selectedItem={selectedItem}
popoverProps={{ popoverProps={{
fill: true, fill: true,
inline: true, inline: true,
minimal: true, minimal: true,
captureDismiss: true, captureDismiss: true,
}} }}
defaultText={<T id={'filter.select_option'} />} placeholder={<T id={'filter.select_option'} />}
textProp={'label'} textAccessor={'label'}
selectedItemProp={'key'} valueAccessor={'key'}
{...rest} {...rest}
/> />
); );

View File

@@ -14,4 +14,3 @@ const mapActionsToProps = (dispatch) => ({
}); });
export const withAccountsTableActions = connect(null, mapActionsToProps); export const withAccountsTableActions = connect(null, mapActionsToProps);
export const withAccountsActions = withAccountsTableActions;

View File

@@ -6,7 +6,7 @@ import { Intent, Alert } from '@blueprintjs/core';
import { queryCache } from 'react-query'; import { queryCache } from 'react-query';
import { AppToaster } from '@/components'; import { AppToaster } from '@/components';
import { withAccountsActions } from '@/containers/Accounts/withAccountsTableActions'; // import { withAccountsActions } from '@/containers/Accounts/withAccountsTableActions';
import { withAlertStoreConnect } from '@/containers/Alert/withAlertStoreConnect'; import { withAlertStoreConnect } from '@/containers/Alert/withAlertStoreConnect';
import { withAlertActions } from '@/containers/Alert/withAlertActions'; import { withAlertActions } from '@/containers/Alert/withAlertActions';
@@ -41,7 +41,7 @@ function AccountBulkInactivateAlert({
}); });
queryCache.invalidateQueries('accounts-table'); queryCache.invalidateQueries('accounts-table');
}) })
.catch((errors) => {}) .catch((errors) => { })
.finally(() => { .finally(() => {
setLoading(false); setLoading(false);
closeAlert(name); closeAlert(name);
@@ -68,5 +68,5 @@ function AccountBulkInactivateAlert({
export default compose( export default compose(
withAlertStoreConnect(), withAlertStoreConnect(),
withAlertActions, withAlertActions,
withAccountsActions, // withAccountsActions,
)(AccountBulkInactivateAlert); )(AccountBulkInactivateAlert);

View File

@@ -8,7 +8,7 @@ import ReferenceNumberForm from '@/containers/JournalNumber/ReferenceNumberForm'
import { withDialogActions } from '@/containers/Dialog/withDialogActions'; import { withDialogActions } from '@/containers/Dialog/withDialogActions';
import { withSettingsActions } from '@/containers/Settings/withSettingsActions'; import { withSettingsActions } from '@/containers/Settings/withSettingsActions';
import { withSettings } from '@/containers/Settings/withSettings'; import { withSettings } from '@/containers/Settings/withSettings';
import { withBillActions } from '@/containers/Purchases/Bills/BillsLanding/withBillsActions'; import { withBillsActions } from '@/containers/Purchases/Bills/BillsLanding/withBillsActions';
import { compose, optionsMapToArray } from '@/utils'; import { compose, optionsMapToArray } from '@/utils';
@@ -28,7 +28,7 @@ function BillNumberDialogContent({
// #withDialogActions // #withDialogActions
closeDialog, closeDialog,
// #withBillActions // #withBillsActions
setBillNumberChanged, setBillNumberChanged,
}) { }) {
const fetchSettings = useQuery(['settings'], () => requestFetchOptions({})); const fetchSettings = useQuery(['settings'], () => requestFetchOptions({}));
@@ -76,5 +76,5 @@ export default compose(
nextNumber: billsettings?.next_number, nextNumber: billsettings?.next_number,
numberPrefix: billsettings?.number_prefix, numberPrefix: billsettings?.number_prefix,
})), })),
withBillActions, withBillsActions,
)(BillNumberDialogContent); )(BillNumberDialogContent);

View File

@@ -63,7 +63,6 @@ function ContactDuplicateForm({
name={'contact_type'} name={'contact_type'}
label={<T id={'contact_type'} />} label={<T id={'contact_type'} />}
labelInfo={<FieldRequiredHint />} labelInfo={<FieldRequiredHint />}
className={'form-group--select-list'}
> >
<FSelect <FSelect
name={'contact_type'} name={'contact_type'}

View File

@@ -1,9 +1,17 @@
// @ts-nocheck // @ts-nocheck
import React from 'react'; import React from 'react';
import { Field, ErrorMessage, FastField } from 'formik'; import { Field, ErrorMessage, FastField, useFormikContext } from 'formik';
import { FormGroup, InputGroup } from '@blueprintjs/core'; import { FormGroup, InputGroup } from '@blueprintjs/core';
import { inputIntent, toSafeNumber } from '@/utils'; import { inputIntent, toSafeNumber } from '@/utils';
import { Row, Col, MoneyInputGroup, FormattedMessage as T } from '@/components'; import {
Row,
Col,
MoneyInputGroup,
FormattedMessage as T,
FMoneyInputGroup,
FFormGroup,
FInputGroup,
} from '@/components';
import { useAutofocus } from '@/hooks'; import { useAutofocus } from '@/hooks';
import { decrementQuantity } from './utils'; import { decrementQuantity } from './utils';
@@ -12,27 +20,19 @@ import { decrementQuantity } from './utils';
*/ */
function DecrementAdjustmentFields() { function DecrementAdjustmentFields() {
const decrementFieldRef = useAutofocus(); const decrementFieldRef = useAutofocus();
const { values, setFieldValue } = useFormikContext();
return ( return (
<Row className={'row--decrement-fields'}> <Row className={'row--decrement-fields'}>
{/*------------ Quantity on hand -----------*/} {/*------------ Quantity on hand -----------*/}
<Col className={'col--quantity-on-hand'}> <Col className={'col--quantity-on-hand'}>
<FastField name={'quantity_on_hand'}> <FFormGroup name={'quantity_on_hand'} label={<T id={'qty_on_hand'} />}>
{({ field, meta: { error, touched } }) => ( <FInputGroup
<FormGroup name={'quantity_on_hand'}
label={<T id={'qty_on_hand'} />} disabled={true}
intent={inputIntent({ error, touched })} medium={'true'}
helperText={<ErrorMessage name="quantity_on_hand" />} />
> </FFormGroup>
<InputGroup
disabled={true}
medium={'true'}
intent={inputIntent({ error, touched })}
{...field}
/>
</FormGroup>
)}
</FastField>
</Col> </Col>
<Col className={'col--sign'}> <Col className={'col--sign'}>
@@ -41,40 +41,23 @@ function DecrementAdjustmentFields() {
{/*------------ Decrement -----------*/} {/*------------ Decrement -----------*/}
<Col className={'col--decrement'}> <Col className={'col--decrement'}>
<Field name={'quantity'}> <FFormGroup name={'quantity'} label={<T id={'decrement'} />} fill>
{({ <FMoneyInputGroup
form: { values, setFieldValue }, name={'quantity'}
field, allowDecimals={false}
meta: { error, touched }, allowNegativeValue={true}
}) => ( inputRef={(ref) => (decrementFieldRef.current = ref)}
<FormGroup onBlurValue={(value) => {
label={<T id={'decrement'} />} setFieldValue(
intent={inputIntent({ error, touched })} 'new_quantity',
helperText={<ErrorMessage name="quantity" />} decrementQuantity(
fill={true} toSafeNumber(value),
> toSafeNumber(values.quantity_on_hand),
<MoneyInputGroup ),
value={field.value} );
allowDecimals={false} }}
allowNegativeValue={true} />
inputRef={(ref) => (decrementFieldRef.current = ref)} </FFormGroup>
onChange={(value) => {
setFieldValue('quantity', value);
}}
onBlurValue={(value) => {
setFieldValue(
'new_quantity',
decrementQuantity(
toSafeNumber(value),
toSafeNumber(values.quantity_on_hand),
),
);
}}
intent={inputIntent({ error, touched })}
/>
</FormGroup>
)}
</Field>
</Col> </Col>
<Col className={'col--sign'}> <Col className={'col--sign'}>
@@ -82,38 +65,27 @@ function DecrementAdjustmentFields() {
</Col> </Col>
{/*------------ New quantity -----------*/} {/*------------ New quantity -----------*/}
<Col className={'col--quantity'}> <Col className={'col--quantity'}>
<Field name={'new_quantity'}> <FFormGroup
{({ name={'new_quantity'}
form: { values, setFieldValue }, label={<T id={'new_quantity'} />}
field, fill
meta: { error, touched }, fastField
}) => ( >
<FormGroup <FMoneyInputGroup
label={<T id={'new_quantity'} />} name={'new_quantity'}
intent={inputIntent({ error, touched })} allowDecimals={false}
helperText={<ErrorMessage name="new_quantity" />} allowNegativeValue={true}
> onBlurValue={(value) => {
<MoneyInputGroup setFieldValue(
value={field.value} 'quantity',
allowDecimals={false} decrementQuantity(
allowNegativeValue={true} toSafeNumber(value),
onChange={(value) => { toSafeNumber(values.quantity_on_hand),
setFieldValue('new_quantity', value); ),
}} );
onBlurValue={(value) => { }}
setFieldValue( />
'quantity', </FFormGroup>
decrementQuantity(
toSafeNumber(value),
toSafeNumber(values.quantity_on_hand),
),
);
}}
intent={inputIntent({ error, touched })}
/>
</FormGroup>
)}
</Field>
</Col> </Col>
</Row> </Row>
); );

View File

@@ -160,7 +160,7 @@ export default function InventoryAdjustmentFormDialogFields() {
name={'adjustment_account_id'} name={'adjustment_account_id'}
label={<T id={'adjustment_account'} />} label={<T id={'adjustment_account'} />}
labelInfo={<FieldRequiredHint />} labelInfo={<FieldRequiredHint />}
className={'form-group--adjustment-account'} fill
> >
<FAccountsSuggestField <FAccountsSuggestField
name={'adjustment_account_id'} name={'adjustment_account_id'}
@@ -168,6 +168,8 @@ export default function InventoryAdjustmentFormDialogFields() {
inputProps={{ inputProps={{
placeholder: intl.get('select_adjustment_account'), placeholder: intl.get('select_adjustment_account'),
}} }}
fill
fastField
/> />
</FFormGroup> </FFormGroup>
@@ -185,16 +187,21 @@ export default function InventoryAdjustmentFormDialogFields() {
name={'reason'} name={'reason'}
label={<T id={'adjustment_reasons'} />} label={<T id={'adjustment_reasons'} />}
labelInfo={<FieldRequiredHint />} labelInfo={<FieldRequiredHint />}
fill
fastField fastField
> >
<FTextArea name={'reason'} growVertically large fastField /> <FTextArea name={'reason'} growVertically large fastField fill />
</FFormGroup> </FFormGroup>
</div> </div>
); );
} }
export const FeatureRowDivider = styled.div` export const FeatureRowDivider = styled.div`
--x-color-background: #e9e9e9;
.bp4-dark & {
--x-color-background: rgba(255, 255, 255, 0.1);
}
height: 2px; height: 2px;
background: #e9e9e9; background: var(--x-color-background);
margin-bottom: 15px; margin-bottom: 15px;
`; `;

View File

@@ -27,10 +27,12 @@ import {
FormattedMessage as T, FormattedMessage as T,
ExchangeRateMutedField, ExchangeRateMutedField,
BranchSelect, BranchSelect,
BranchSelectButton,
FeatureCan, FeatureCan,
FInputGroup, FInputGroup,
FMoneyInputGroup, FMoneyInputGroup,
FDateInput,
FFormGroup,
FTextArea,
} from '@/components'; } from '@/components';
import { import {
inputIntent, inputIntent,
@@ -66,16 +68,13 @@ function RefundCreditNoteFormFields({
<FeatureCan feature={Features.Branches}> <FeatureCan feature={Features.Branches}>
<Row> <Row>
<Col xs={5}> <Col xs={5}>
<FormGroup <FFormGroup name={'branch_id'} label={<T id={'branch'} />}>
label={<T id={'branch'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<BranchSelect <BranchSelect
name={'branch_id'} name={'branch_id'}
branches={branches} branches={branches}
popoverProps={{ minimal: true }} popoverProps={{ minimal: true }}
/> />
</FormGroup> </FFormGroup>
</Col> </Col>
</Row> </Row>
<BranchRowDivider /> <BranchRowDivider />
@@ -84,29 +83,23 @@ function RefundCreditNoteFormFields({
<Row> <Row>
<Col xs={5}> <Col xs={5}>
{/* ------------- Refund date ------------- */} {/* ------------- Refund date ------------- */}
<FastField name={'date'}> <FFormGroup
{({ form, field: { value }, meta: { error, touched } }) => ( name={'date'}
<FFormGroup label={<T id={'refund_credit_note.dialog.refund_date'} />}
name={'date'} labelInfo={<FieldRequiredHint />}
label={<T id={'refund_credit_note.dialog.refund_date'} />} fill
labelInfo={<FieldRequiredHint />} >
fill <FDateInput
> name={'date'}
<DateInput {...momentFormatter('YYYY/MM/DD')}
{...momentFormatter('YYYY/MM/DD')} popoverProps={{ position: Position.BOTTOM, minimal: true }}
value={tansformDateValue(value)} inputProps={{
onChange={handleDateChange((formattedDate) => { leftIcon: <Icon icon={'date-range'} />,
form.setFieldValue('date', formattedDate); }}
})} />
popoverProps={{ position: Position.BOTTOM, minimal: true }} </FFormGroup>
inputProps={{
leftIcon: <Icon icon={'date-range'} />,
}}
/>
</FFormGroup>
)}
</FastField>
</Col> </Col>
<Col xs={5}> <Col xs={5}>
{/* ------------ Form account ------------ */} {/* ------------ Form account ------------ */}
<FFormGroup <FFormGroup
@@ -114,6 +107,7 @@ function RefundCreditNoteFormFields({
label={<T id={'refund_credit_note.dialog.from_account'} />} label={<T id={'refund_credit_note.dialog.from_account'} />}
labelInfo={<FieldRequiredHint />} labelInfo={<FieldRequiredHint />}
fill fill
fastField
> >
<FAccountsSuggestField <FAccountsSuggestField
name={'from_account_id'} name={'from_account_id'}
@@ -126,6 +120,7 @@ function RefundCreditNoteFormFields({
ACCOUNT_TYPE.CASH, ACCOUNT_TYPE.CASH,
ACCOUNT_TYPE.FIXED_ASSET, ACCOUNT_TYPE.FIXED_ASSET,
]} ]}
fastField
/> />
</FFormGroup> </FFormGroup>
</Col> </Col>
@@ -137,6 +132,7 @@ function RefundCreditNoteFormFields({
label={<T id={'refund_credit_note.dialog.amount'} />} label={<T id={'refund_credit_note.dialog.amount'} />}
labelInfo={<FieldRequiredHint />} labelInfo={<FieldRequiredHint />}
fill fill
fastField
> >
<ControlGroup> <ControlGroup>
<InputPrependText text={values.currency_code} /> <InputPrependText text={values.currency_code} />
@@ -144,6 +140,7 @@ function RefundCreditNoteFormFields({
name={'amount'} name={'amount'}
minimal={true} minimal={true}
inputRef={(ref) => (amountFieldRef.current = ref)} inputRef={(ref) => (amountFieldRef.current = ref)}
/> />
</ControlGroup> </ControlGroup>
</FFormGroup> </FFormGroup>
@@ -161,21 +158,19 @@ function RefundCreditNoteFormFields({
</If> </If>
{/* ------------ Reference No. ------------ */} {/* ------------ Reference No. ------------ */}
<FFormGroup name={'reference_no'} label={<T id={'reference_no'} />} fill> <FFormGroup name={'reference_no'} label={<T id={'reference_no'} />} fill fastField>
<FInputGroup name={'reference_no'} minimal fill /> <FInputGroup name={'reference_no'} minimal fill />
</FFormGroup> </FFormGroup>
{/* --------- Statement --------- */} {/* --------- Statement --------- */}
<FastField name={'description'}> <FFormGroup
{({ form, field, meta: { error, touched } }) => ( name={'description'}
<FormGroup label={<T id={'refund_credit_note.dialog.description'} />}
label={<T id={'refund_credit_note.dialog.description'} />} fill
className={'form-group--description'} fastField
> >
<TextArea growVertically={true} {...field} /> <FTextArea name={'description'} growVertically fill fastField />
</FormGroup> </FFormGroup>
)}
</FastField>
</div> </div>
); );
} }
@@ -183,7 +178,12 @@ function RefundCreditNoteFormFields({
export default compose(withCurrentOrganization())(RefundCreditNoteFormFields); export default compose(withCurrentOrganization())(RefundCreditNoteFormFields);
export const BranchRowDivider = styled.div` export const BranchRowDivider = styled.div`
--x-divider-color: #ebf1f6;
.bp4-dark & {
--x-divider-color: rgba(255, 255, 255, 0.1);
}
height: 1px; height: 1px;
background: #ebf1f6; background: var(--x-divider-color);
margin-bottom: 13px; margin-bottom: 13px;
`; `;

View File

@@ -152,8 +152,8 @@ function RefundVendorCreditFormFields({
</FFormGroup> </FFormGroup>
{/* --------- Statement --------- */} {/* --------- Statement --------- */}
<FFormGroup name={'description'} fill fastField> <FFormGroup name={'description'} label={<T id={'refund_vendor_credit.dialog.description'} />} fill fastField>
<FTextArea name={'description'} growVertically={true} fastField /> <FTextArea name={'description'} growVertically fill fastField />
</FFormGroup> </FFormGroup>
</div> </div>
); );
@@ -162,7 +162,12 @@ function RefundVendorCreditFormFields({
export default compose(withCurrentOrganization())(RefundVendorCreditFormFields); export default compose(withCurrentOrganization())(RefundVendorCreditFormFields);
export const BranchRowDivider = styled.div` export const BranchRowDivider = styled.div`
--x-divider-color: #ebf1f6;
.bp4-dark & {
--x-divider-color: rgba(255, 255, 255, 0.1);
}
height: 1px; height: 1px;
background: #ebf1f6; background: var(--x-divider-color);
margin-bottom: 13px; margin-bottom: 13px;
`; `;

View File

@@ -70,9 +70,14 @@ function AccountDrawerDataTable() {
export default compose(withDrawerActions)(AccountDrawerTable); export default compose(withDrawerActions)(AccountDrawerTable);
const TableFooter = styled.div` const TableFooter = styled.div`
--x-border-color: #d2dde2;
.bp4-dark & {
--x-border-color: var(--color-dark-gray5);
}
padding: 6px 14px; padding: 6px 14px;
display: block; display: block;
border-top: 1px solid #d2dde2; border-top: 1px solid var(--x-border-color);
border-bottom: 1px solid #d2dde2; border-bottom: 1px solid var(--x-border-color);
font-size: 12px; font-size: 12px;
`; `;

View File

@@ -9,13 +9,13 @@ import { ItemsCategoriesProvider } from './ItemsCategoriesProvider';
import ItemCategoriesTable from './ItemCategoriesTable'; import ItemCategoriesTable from './ItemCategoriesTable';
import ItemsCategoryActionsBar from './ItemsCategoryActionsBar'; import ItemsCategoryActionsBar from './ItemsCategoryActionsBar';
import { withItemsCategories } from './withItemCategories'; import { withItemCategories } from './withItemCategories';
/** /**
* Item categories list. * Item categories list.
*/ */
function ItemCategoryList({ function ItemCategoryList({
// #withItemsCategories // #withItemCategories
itemsCategoriesTableState itemsCategoriesTableState
}) { }) {
return ( return (
@@ -32,7 +32,7 @@ function ItemCategoryList({
} }
export default R.compose( export default R.compose(
withItemsCategories(({ itemsCategoriesTableState }) => ({ withItemCategories(({ itemsCategoriesTableState }) => ({
itemsCategoriesTableState, itemsCategoriesTableState,
})), })),
)(ItemCategoryList); )(ItemCategoryList);

View File

@@ -15,5 +15,3 @@ export const withItemCategories = (mapState) => {
}; };
return connect(mapStateToProps); return connect(mapStateToProps);
}; };
export const withItemsCategories = withItemCategories;

View File

@@ -63,7 +63,12 @@ export function PaymentMethodSelectField({
} }
const PaymentMethodSelectRoot = styled(Group)` const PaymentMethodSelectRoot = styled(Group)`
border: 1px solid #d3d8de; --x-color-border: #d3d8de;
.bp4-dark & {
--x-color-border: rgba(255, 255, 255, 0.2);
}
border: 1px solid var(--x-color-border);
border-radius: 3px; border-radius: 3px;
padding: 8px; padding: 8px;
gap: 0; gap: 0;
@@ -72,13 +77,23 @@ const PaymentMethodSelectRoot = styled(Group)`
`; `;
const PaymentMethodCheckbox = styled(Checkbox)` const PaymentMethodCheckbox = styled(Checkbox)`
--x-color-border: #c5cbd3;
.bp4-dark & {
--x-color-border: rgba(255, 255, 255, 0.2);
}
margin: 0; margin: 0;
&.bp4-control .bp4-control-indicator { &.bp4-control .bp4-control-indicator {
box-shadow: 0 0 0 1px #c5cbd3; box-shadow: 0 0 0 1px var(--x-color-border);
} }
`; `;
const PaymentMethodText = styled(Text)` const PaymentMethodText = styled(Text)`
color: #404854; --x-color-text: #404854;
.bp4-dark & {
--x-color-text: var(--color-light-gray4);
}
color: var(--x-color-text);
`; `;

View File

@@ -48,5 +48,5 @@ const PaymentMethodsTitle = styled('h6')`
font-size: 12px; font-size: 12px;
font-weight: 500; font-weight: 500;
margin: 0; margin: 0;
color: rgb(95, 107, 124); color: var(--color-muted-text);
`; `;

View File

@@ -45,7 +45,7 @@ import { isEmpty } from 'lodash';
* Bills actions bar. * Bills actions bar.
*/ */
function BillActionsBar({ function BillActionsBar({
// #withBillActions // #withBillsActions
setBillsTableState, setBillsTableState,
// #withBills // #withBills

View File

@@ -13,7 +13,7 @@ import {
import BillsEmptyStatus from './BillsEmptyStatus'; import BillsEmptyStatus from './BillsEmptyStatus';
import { withBills } from './withBills'; import { withBills } from './withBills';
import { withBillActions } from './withBillsActions'; import { withBillsActions } from './withBillsActions';
import { withAlertActions } from '@/containers/Alert/withAlertActions'; import { withAlertActions } from '@/containers/Alert/withAlertActions';
import { withDialogActions } from '@/containers/Dialog/withDialogActions'; import { withDialogActions } from '@/containers/Dialog/withDialogActions';
import { withDrawerActions } from '@/containers/Drawer/withDrawerActions'; import { withDrawerActions } from '@/containers/Drawer/withDrawerActions';
@@ -163,7 +163,7 @@ function BillsDataTable({
export default compose( export default compose(
withBills(({ billsTableState }) => ({ billsTableState })), withBills(({ billsTableState }) => ({ billsTableState })),
withBillActions, withBillsActions,
withAlertActions, withAlertActions,
withDrawerActions, withDrawerActions,
withDialogActions, withDialogActions,

View File

@@ -6,7 +6,7 @@ import { DashboardViewsTabs } from '@/components';
import { useBillsListContext } from './BillsListProvider'; import { useBillsListContext } from './BillsListProvider';
import { withBills } from './withBills'; import { withBills } from './withBills';
import { withBillActions } from './withBillsActions'; import { withBillsActions } from './withBillsActions';
import { compose, transfromViewsToTabs } from '@/utils'; import { compose, transfromViewsToTabs } from '@/utils';
@@ -14,7 +14,7 @@ import { compose, transfromViewsToTabs } from '@/utils';
* Bills view tabs. * Bills view tabs.
*/ */
function BillViewTabs({ function BillViewTabs({
// #withBillActions // #withBillsActions
setBillsTableState, setBillsTableState,
// #withBills // #withBills
@@ -47,7 +47,7 @@ function BillViewTabs({
} }
export default compose( export default compose(
withBillActions, withBillsActions,
withBills(({ billsTableState }) => ({ withBills(({ billsTableState }) => ({
billsCurrentView: billsTableState.viewSlug, billsCurrentView: billsTableState.viewSlug,
})), })),

View File

@@ -14,4 +14,3 @@ const mapDispatchToProps = (dispatch) => ({
}); });
export const withBillsActions = connect(null, mapDispatchToProps); export const withBillsActions = connect(null, mapDispatchToProps);
export const withBillActions = withBillsActions;

View File

@@ -70,16 +70,16 @@ function VendorCreditNoteForm({
() => ({ () => ({
...(!isEmpty(vendorCredit) ...(!isEmpty(vendorCredit)
? { ? {
...transformToEditForm(vendorCredit), ...transformToEditForm(vendorCredit),
} }
: { : {
...defaultVendorsCreditNote, ...defaultVendorsCreditNote,
...(vendorcreditAutoIncrement && { ...(vendorcreditAutoIncrement && {
vendor_credit_number: vendorCreditNumber, vendor_credit_number: vendorCreditNumber,
}),
currency_code: base_currency,
...newVendorCredit,
}), }),
currency_code: base_currency,
...newVendorCredit,
}),
}), }),
[vendorCredit, base_currency], [vendorCredit, base_currency],
); );

View File

@@ -24,6 +24,7 @@ import {
VendorsSelect, VendorsSelect,
Stack, Stack,
FDateInput, FDateInput,
FInputGroup,
} from '@/components'; } from '@/components';
import { import {
vendorsFieldShouldUpdate, vendorsFieldShouldUpdate,
@@ -74,6 +75,7 @@ function VendorCreditNoteFormHeaderFields({
}) { }) {
const theme = useTheme(); const theme = useTheme();
const fieldsClassName = getFieldsStyle(theme); const fieldsClassName = getFieldsStyle(theme);
const { values } = useFormikContext();
// Handle vendor credit number changing. // Handle vendor credit number changing.
const handleVendorCreditNumberChange = () => { const handleVendorCreditNumberChange = () => {
@@ -81,10 +83,11 @@ function VendorCreditNoteFormHeaderFields({
}; };
// Handle vendor credit no. field blur. // Handle vendor credit no. field blur.
const handleVendorCreditNoBlur = (form, field) => (event) => { const handleVendorCreditNoBlur = (event) => {
const newValue = event.target.value; const newValue = event.target.value;
const oldValue = values.vendor_credit_number;
if (field.value !== newValue && vendorcreditAutoIncrement) { if (oldValue !== newValue && vendorcreditAutoIncrement) {
openDialog('vendor-credit-form', { openDialog('vendor-credit-form', {
initialFormValues: { initialFormValues: {
manualTransactionNo: newValue, manualTransactionNo: newValue,
@@ -109,7 +112,6 @@ function VendorCreditNoteFormHeaderFields({
name={'exchange_rate'} name={'exchange_rate'}
formGroupProps={{ label: ' ', inline: true }} formGroupProps={{ label: ' ', inline: true }}
/> />
{/* ------- Vendor Credit date ------- */} {/* ------- Vendor Credit date ------- */}
<FFormGroup <FFormGroup
name={'vendor_credit_date'} name={'vendor_credit_date'}
@@ -130,7 +132,6 @@ function VendorCreditNoteFormHeaderFields({
</FFormGroup> </FFormGroup>
{/* ----------- Vendor Credit No # ----------- */} {/* ----------- Vendor Credit No # ----------- */}
<FFormGroup <FFormGroup
name={'vendor_credit_number'} name={'vendor_credit_number'}
label={<T id={'credit_note.label_credit_note'} />} label={<T id={'credit_note.label_credit_note'} />}
@@ -163,7 +164,7 @@ function VendorCreditNoteFormHeaderFields({
</FFormGroup> </FFormGroup>
{/* ----------- Reference ----------- */} {/* ----------- Reference ----------- */}
<FFormGroup label={<T id={'reference_no'} />} inline={true} fastField> <FFormGroup name={'reference_no'} label={<T id={'reference_no'} />} inline={true} fastField>
<FInputGroup name={'reference_no'} minimal={true} fastField /> <FInputGroup name={'reference_no'} minimal={true} fastField />
</FFormGroup> </FFormGroup>
</Stack> </Stack>

View File

@@ -40,10 +40,10 @@ import { compose } from '@/utils';
* Payment made actions bar. * Payment made actions bar.
*/ */
function PaymentMadeActionsBar({ function PaymentMadeActionsBar({
// #withPaymentMadesActions // #withPaymentMadeActions
setPaymentMadesTableState, setPaymentMadesTableState,
// #withPaymentMades // #withPaymentMade
paymentMadesFilterConditions, paymentMadesFilterConditions,
// #withSettings // #withSettings
@@ -133,7 +133,7 @@ function PaymentMadeActionsBar({
icon={<Icon icon={'trash-16'} iconSize={16} />} icon={<Icon icon={'trash-16'} iconSize={16} />}
text={<T id={'delete'} />} text={<T id={'delete'} />}
intent={Intent.DANGER} intent={Intent.DANGER}
// onClick={handleBulkDelete} // onClick={handleBulkDelete}
/> />
</If> </If>
<Button <Button

View File

@@ -8,7 +8,7 @@ import { PaymentMadesListProvider } from './PaymentMadesListProvider';
import PaymentMadeActionsBar from './PaymentMadeActionsBar'; import PaymentMadeActionsBar from './PaymentMadeActionsBar';
import PaymentMadesTable from './PaymentMadesTable'; import PaymentMadesTable from './PaymentMadesTable';
import { withPaymentMades } from './withPaymentMade'; import { withPaymentMade } from './withPaymentMade';
import { withPaymentMadeActions } from './withPaymentMadeActions'; import { withPaymentMadeActions } from './withPaymentMadeActions';
import { compose, transformTableStateToQuery } from '@/utils'; import { compose, transformTableStateToQuery } from '@/utils';
@@ -17,7 +17,7 @@ import { compose, transformTableStateToQuery } from '@/utils';
* Payment mades list. * Payment mades list.
*/ */
function PaymentMadeList({ function PaymentMadeList({
// #withPaymentMades // #withPaymentMade
paymentMadesTableState, paymentMadesTableState,
paymentsTableStateChanged, paymentsTableStateChanged,
@@ -47,7 +47,7 @@ function PaymentMadeList({
} }
export default compose( export default compose(
withPaymentMades(({ paymentMadesTableState, paymentsTableStateChanged }) => ({ withPaymentMade(({ paymentMadesTableState, paymentsTableStateChanged }) => ({
paymentMadesTableState, paymentMadesTableState,
paymentsTableStateChanged, paymentsTableStateChanged,
})), })),

View File

@@ -15,7 +15,7 @@ import { withPaymentMadeActions } from './withPaymentMadeActions';
* Payment made views tabs. * Payment made views tabs.
*/ */
function PaymentMadeViewTabs({ function PaymentMadeViewTabs({
// #withPaymentMadesActions // #withPaymentMadeActions
setPaymentMadesTableState, setPaymentMadesTableState,
// #withPaymentMade // #withPaymentMade

View File

@@ -18,5 +18,3 @@ export const withPaymentMade = (mapState) => {
}; };
return connect(mapStateToProps); return connect(mapStateToProps);
}; };
export const withPaymentMades = withPaymentMade;

View File

@@ -29,4 +29,4 @@ const mapDispatchToProps = (dispatch, props) => {
} }
} }
export const withRouteActions = connect(null, mapDispatchToProps) export const withRouteActions = connect(null, mapDispatchToProps);

View File

@@ -12,7 +12,6 @@ import { useIsDarkMode } from '@/hooks/useDarkMode';
const inputGroupCss = css` const inputGroupCss = css`
& .bp4-input { & .bp4-input {
max-width: 110px; max-width: 110px;
color: rgb(17, 17, 17);
padding-left: 8px; padding-left: 8px;
} }
`; `;

View File

@@ -13,7 +13,6 @@ import { useIsDarkMode } from '@/hooks/useDarkMode';
const inputGroupCss = css` const inputGroupCss = css`
& .bp4-input { & .bp4-input {
max-width: 110px; max-width: 110px;
color: rgb(17, 17, 17);
padding-left: 8px; padding-left: 8px;
} }
`; `;

View File

@@ -127,7 +127,7 @@ const PaymentOptionsText = styled(Box)`
font-size: 13px; font-size: 13px;
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
color: #5f6b7c; color: var(--color-muted-text);
`; `;
const PaymentOptionsButton = styled(Button)` const PaymentOptionsButton = styled(Button)`

View File

@@ -10,7 +10,7 @@ import { SubscriptionPlansPeriod } from '@/store/plans/plans.reducer';
import styles from './SetupSubscription.module.scss'; import styles from './SetupSubscription.module.scss';
interface SubscriptionPlansPeriodsSwitchCombinedProps interface SubscriptionPlansPeriodsSwitchCombinedProps
extends WithSubscriptionPlansActionsProps {} extends WithSubscriptionPlansActionsProps { }
function SubscriptionPlansPeriodSwitcherRoot({ function SubscriptionPlansPeriodSwitcherRoot({
// #withSubscriptionPlansActions // #withSubscriptionPlansActions

View File

@@ -11,12 +11,11 @@ import {
Menu, Menu,
MenuItem, MenuItem,
} from '@blueprintjs/core'; } from '@blueprintjs/core';
import { If, Icon, FormattedMessage as T } from '@/components'; import { If, Icon, FormattedMessage as T, Group } from '@/components';
import classNames from 'classnames'; import classNames from 'classnames';
import { useFormikContext } from 'formik'; import { useFormikContext } from 'formik';
import { CLASSES } from '@/constants/classes';
import { useWarehouseTransferFormContext } from './WarehouseTransferFormProvider'; import { useWarehouseTransferFormContext } from './WarehouseTransferFormProvider';
import { CLASSES } from '@/constants/classes';
/** /**
* Warehouse transfer floating actions bar. * Warehouse transfer floating actions bar.
@@ -77,98 +76,101 @@ export default function WarehouseTransferFloatingActions() {
return ( return (
<div className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}> <div className={classNames(CLASSES.PAGE_FORM_FLOATING_ACTIONS)}>
{/* ----------- Save Intitate & transferred ----------- */} <Group spacing={10}>
<If condition={!warehouseTransfer || !warehouseTransfer?.is_transferred}> {/* ----------- Save Intitate & transferred ----------- */}
<ButtonGroup> <If condition={!warehouseTransfer || !warehouseTransfer?.is_transferred}>
<ButtonGroup>
<Button
disabled={isSubmitting}
loading={isSubmitting}
intent={Intent.PRIMARY}
type="submit"
onClick={handleSubmitInitiateBtnClick}
style={{ minWidth: '85px' }}
text={<T id={'warehouse_transfer.save_initiate_transfer'} />}
/>
<Popover
content={
<Menu>
<MenuItem
text={
<T id={'warehouse_transfer.save_mark_as_transferred'} />
}
onClick={handleSubmitTransferredBtnClick}
/>
</Menu>
}
minimal={true}
interactionKind={PopoverInteractionKind.CLICK}
position={Position.BOTTOM_LEFT}
>
<Button
disabled={isSubmitting}
intent={Intent.PRIMARY}
rightIcon={<Icon icon="arrow-drop-up-16" iconSize={20} />}
/>
</Popover>
</ButtonGroup>
{/* ----------- Save As Draft ----------- */}
<ButtonGroup>
<Button
disabled={isSubmitting}
className={'ml1'}
onClick={handleSubmitDraftBtnClick}
text={<T id={'save_as_draft'} />}
/>
<Popover
content={
<Menu>
<MenuItem
text={<T id={'save_and_new'} />}
onClick={handleSubmitDraftAndNewBtnClick}
/>
<MenuItem
text={<T id={'save_continue_editing'} />}
onClick={handleSubmitDraftContinueEditingBtnClick}
/>
</Menu>
}
minimal={true}
interactionKind={PopoverInteractionKind.CLICK}
position={Position.BOTTOM_LEFT}
>
<Button
disabled={isSubmitting}
rightIcon={<Icon icon="arrow-drop-up-16" iconSize={20} />}
/>
</Popover>
</ButtonGroup>
</If>
<If condition={warehouseTransfer && warehouseTransfer?.is_transferred}>
<Button <Button
disabled={isSubmitting} disabled={isSubmitting}
loading={isSubmitting} loading={isSubmitting}
intent={Intent.PRIMARY} intent={Intent.PRIMARY}
type="submit" onClick={handleSubmitTransferredBtnClick}
onClick={handleSubmitInitiateBtnClick} style={{ minWidth: '100px' }}
style={{ minWidth: '85px' }} text={<T id={'save'} />}
text={<T id={'warehouse_transfer.save_initiate_transfer'} />}
/> />
<Popover </If>
content={
<Menu>
<MenuItem
text={
<T id={'warehouse_transfer.save_mark_as_transferred'} />
}
onClick={handleSubmitTransferredBtnClick}
/>
</Menu>
}
minimal={true}
interactionKind={PopoverInteractionKind.CLICK}
position={Position.BOTTOM_LEFT}
>
<Button
disabled={isSubmitting}
intent={Intent.PRIMARY}
rightIcon={<Icon icon="arrow-drop-up-16" iconSize={20} />}
/>
</Popover>
</ButtonGroup>
{/* ----------- Save As Draft ----------- */} {/* ----------- Clear & Reset----------- */}
<ButtonGroup>
<Button
disabled={isSubmitting}
className={'ml1'}
onClick={handleSubmitDraftBtnClick}
text={<T id={'save_as_draft'} />}
/>
<Popover
content={
<Menu>
<MenuItem
text={<T id={'save_and_new'} />}
onClick={handleSubmitDraftAndNewBtnClick}
/>
<MenuItem
text={<T id={'save_continue_editing'} />}
onClick={handleSubmitDraftContinueEditingBtnClick}
/>
</Menu>
}
minimal={true}
interactionKind={PopoverInteractionKind.CLICK}
position={Position.BOTTOM_LEFT}
>
<Button
disabled={isSubmitting}
rightIcon={<Icon icon="arrow-drop-up-16" iconSize={20} />}
/>
</Popover>
</ButtonGroup>
</If>
<If condition={warehouseTransfer && warehouseTransfer?.is_transferred}>
<Button <Button
className={'ml1'}
disabled={isSubmitting} disabled={isSubmitting}
loading={isSubmitting} onClick={handleClearBtnClick}
intent={Intent.PRIMARY} text={warehouseTransfer ? <T id={'reset'} /> : <T id={'clear'} />}
onClick={handleSubmitTransferredBtnClick}
style={{ minWidth: '100px' }}
text={<T id={'save'} />}
/> />
</If>
{/* ----------- Clear & Reset----------- */}
<Button
className={'ml1'}
disabled={isSubmitting}
onClick={handleClearBtnClick}
text={warehouseTransfer ? <T id={'reset'} /> : <T id={'clear'} />}
/>
{/* ----------- Cancel ----------- */} {/* ----------- Cancel ----------- */}
<Button <Button
className={'ml1'} className={'ml1'}
disabled={isSubmitting} disabled={isSubmitting}
onClick={handleCancelBtnClick} onClick={handleCancelBtnClick}
text={<T id={'cancel'} />} text={<T id={'cancel'} />}
/> />
</Group>
</div> </div>
); );
} }

View File

@@ -80,6 +80,7 @@ function WarehouseTransferFormHeaderFields({
inputProps={{ inputProps={{
leftIcon: <Icon icon={'date-range'} />, leftIcon: <Icon icon={'date-range'} />,
}} }}
fill
fastField fastField
/> />
</FFormGroup> </FFormGroup>

View File

@@ -205,7 +205,7 @@ export function useAccountTransactions(id, props) {
[t.ACCOUNT_TRANSACTION, id], [t.ACCOUNT_TRANSACTION, id],
{ method: 'get', url: `accounts/transactions?account_id=${id}` }, { method: 'get', url: `accounts/transactions?account_id=${id}` },
{ {
select: (res) => res.data.transactions, select: (res) => res.data,
defaultData: [], defaultData: [],
...props, ...props,
}, },

View File

@@ -8,12 +8,19 @@
.avatar.td { .avatar.td {
.avatar { .avatar {
--x-color-background: #adbcc9;
--x-color-text: #fff;
.bp4-dark & {
--x-color-background: rgba(255, 255, 255, 0.2);
--x-color-text: #fff;
}
display: inline-block; display: inline-block;
background: #adbcc9; background: var(--x-color-background);
border-radius: 50%; border-radius: 50%;
text-align: center; text-align: center;
font-weight: 400; font-weight: 400;
color: #fff; color: var(--x-color-text);
&[data-size='medium'] { &[data-size='medium'] {
height: 30px; height: 30px;

View File

@@ -9,12 +9,19 @@
.avatar.td { .avatar.td {
.avatar { .avatar {
--x-color-background: #adbcc9;
--x-color-text: #fff;
.bp4-dark & {
--x-color-background: rgba(255, 255, 255, 0.2);
--x-color-text: #fff;
}
display: inline-block; display: inline-block;
background: #adbcc9; background: var(--x-color-background);
color: var(--x-color-text);
border-radius: 50%; border-radius: 50%;
text-align: center; text-align: center;
font-weight: 400; font-weight: 400;
color: #fff;
&[data-size='medium'] { &[data-size='medium'] {
height: 30px; height: 30px;

View File

@@ -54,6 +54,11 @@ export default defineConfig(({ mode }) => {
target: env.VITE_API_PROXY_TARGET || 'http://localhost:3000', target: env.VITE_API_PROXY_TARGET || 'http://localhost:3000',
changeOrigin: true, changeOrigin: true,
}, },
'/socket': {
target: env.VITE_API_PROXY_TARGET || 'http://localhost:3000',
changeOrigin: true,
ws: true,
},
}, },
}, },
build: { build: {

View File

@@ -0,0 +1,257 @@
import {
PaperTemplate,
PaperTemplateProps,
PaperTemplateTotalBorder,
} from './PaperTemplate';
import { Box } from '../lib/layout/Box';
import { Text } from '../lib/text/Text';
import { Stack } from '../lib/layout/Stack';
import { Group } from '../lib/layout/Group';
import {
DefaultPdfTemplateTerms,
DefaultPdfTemplateItemDescription,
DefaultPdfTemplateItemName,
DefaultPdfTemplateAddressBilledTo,
DefaultPdfTemplateAddressBilledFrom,
} from './_constants';
interface CreditNoteLine {
item?: string;
description?: string;
quantity?: string;
rate?: string;
total?: string;
}
export interface CreditNotePaperTemplateProps extends PaperTemplateProps {
primaryColor?: string;
secondaryColor?: string;
// Company
showCompanyLogo?: boolean;
companyLogoUri?: string;
companyName?: string;
// Credit Note number
showCreditNoteNumber?: boolean;
creditNoteNumebr?: string;
creditNoteNumberLabel?: string;
// Credit Note date
showCreditNoteDate?: boolean;
creditNoteDate?: string;
creditNoteDateLabel?: string;
// Address
showCustomerAddress?: boolean;
customerAddress?: string;
showCompanyAddress?: boolean;
companyAddress?: string;
billedToLabel?: string;
// Entries
lineItemLabel?: string;
lineQuantityLabel?: string;
lineRateLabel?: string;
lineTotalLabel?: string;
// Subtotal
showSubtotal?: boolean;
subtotalLabel?: string;
subtotal?: string;
// Total
showTotal?: boolean;
totalLabel?: string;
total?: string;
// Customer Note
showCustomerNote?: boolean;
customerNote?: string;
customerNoteLabel?: string;
// Terms & Conditions
showTermsConditions?: boolean;
termsConditions?: string;
termsConditionsLabel?: string;
lines?: Array<CreditNoteLine>;
}
export function CreditNotePaperTemplate({
// # Colors
primaryColor,
secondaryColor,
// # Company
companyName = 'Bigcapital Technology, Inc.',
showCompanyLogo = true,
companyLogoUri = '',
// # Credit Note number
creditNoteNumberLabel = 'Credit Note Number',
creditNoteNumebr = '346D3D40-0001',
showCreditNoteNumber = true,
// # Credit Note date
creditNoteDate = 'September 3, 2024',
creditNoteDateLabel = 'Credit Note Date',
showCreditNoteDate = true,
// Address
showCustomerAddress = true,
customerAddress = DefaultPdfTemplateAddressBilledTo,
showCompanyAddress = true,
companyAddress = DefaultPdfTemplateAddressBilledFrom,
billedToLabel = 'Billed To',
// Entries
lineItemLabel = 'Item',
lineQuantityLabel = 'Qty',
lineRateLabel = 'Rate',
lineTotalLabel = 'Total',
// Subtotal
subtotalLabel = 'Subtotal',
showSubtotal = true,
subtotal = '1000.00',
// Total
totalLabel = 'Total',
showTotal = true,
total = '$1000.00',
// Customer Note
showCustomerNote = true,
customerNote = '',
customerNoteLabel = 'Customer Note',
// Terms & Conditions
termsConditionsLabel = 'Terms & Conditions',
showTermsConditions = true,
termsConditions = DefaultPdfTemplateTerms,
lines = [
{
item: DefaultPdfTemplateItemName,
description: DefaultPdfTemplateItemDescription,
rate: '1',
quantity: '1000',
total: '$1000.00',
},
],
...props
}: CreditNotePaperTemplateProps) {
return (
<PaperTemplate
primaryColor={primaryColor}
secondaryColor={secondaryColor}
{...props}
>
<Stack spacing={24}>
<Group align="start" spacing={10}>
<Stack flex={1}>
<PaperTemplate.BigTitle title={'Credit Note'} />
<PaperTemplate.TermsList>
{showCreditNoteNumber && (
<PaperTemplate.TermsItem label={creditNoteNumberLabel}>
{creditNoteNumebr}
</PaperTemplate.TermsItem>
)}
{showCreditNoteDate && (
<PaperTemplate.TermsItem label={creditNoteDateLabel}>
{creditNoteDate}
</PaperTemplate.TermsItem>
)}
</PaperTemplate.TermsList>
</Stack>
{companyLogoUri && showCompanyLogo && (
<PaperTemplate.Logo logoUri={companyLogoUri} />
)}
</Group>
<PaperTemplate.AddressesGroup>
{showCompanyAddress && (
<PaperTemplate.Address>
<Box dangerouslySetInnerHTML={{ __html: companyAddress }} />
</PaperTemplate.Address>
)}
{showCustomerAddress && (
<PaperTemplate.Address>
<strong>{billedToLabel}</strong>
<Box dangerouslySetInnerHTML={{ __html: customerAddress }} />
</PaperTemplate.Address>
)}
</PaperTemplate.AddressesGroup>
<Stack spacing={0}>
<PaperTemplate.Table
columns={[
{
label: lineItemLabel,
accessor: (data) => (
<Stack spacing={2}>
<Text>{data.item}</Text>
{data.description && (
<Text color={'#5f6b7c'} fontSize={12}>
{data.description}
</Text>
)}
</Stack>
),
thStyle: { width: '60%' },
},
{
label: lineQuantityLabel,
accessor: 'quantity',
align: 'right',
},
{ label: lineRateLabel, accessor: 'rate', align: 'right' },
{ label: lineTotalLabel, accessor: 'total', align: 'right' },
]}
data={lines}
/>
<PaperTemplate.Totals>
{showSubtotal && (
<PaperTemplate.TotalLine
label={subtotalLabel}
amount={subtotal}
border={PaperTemplateTotalBorder.Gray}
/>
)}
{showTotal && (
<PaperTemplate.TotalLine
label={totalLabel}
amount={total}
border={PaperTemplateTotalBorder.Dark}
style={{ fontWeight: 500 }}
/>
)}
</PaperTemplate.Totals>
</Stack>
<Stack spacing={0}>
{showCustomerNote && customerNote && (
<PaperTemplate.Statement label={customerNoteLabel}>
{customerNote}
</PaperTemplate.Statement>
)}
{showTermsConditions && termsConditions && (
<PaperTemplate.Statement label={termsConditionsLabel}>
{termsConditions}
</PaperTemplate.Statement>
)}
</Stack>
</Stack>
</PaperTemplate>
);
}

View File

@@ -1,5 +1,6 @@
export * from './components/PaperTemplate'; export * from './components/PaperTemplate';
export * from './components/InvoicePaperTemplate'; export * from './components/InvoicePaperTemplate';
export * from './components/CreditNotePaperTemplate';
export * from './components/EstimatePaperTemplate'; export * from './components/EstimatePaperTemplate';
export * from './components/ReceiptPaperTemplate'; export * from './components/ReceiptPaperTemplate';
export * from './components/PaymentReceivedPaperTemplate'; export * from './components/PaymentReceivedPaperTemplate';
@@ -7,6 +8,7 @@ export * from './components/FinancialSheetTemplate';
export * from './components/ExportResourceTableTemplate'; export * from './components/ExportResourceTableTemplate';
export * from './renders/render-invoice-paper-template'; export * from './renders/render-invoice-paper-template';
export * from './renders/render-credit-note-paper-template';
export * from './renders/render-estimate-paper-template'; export * from './renders/render-estimate-paper-template';
export * from './renders/render-receipt-paper-template'; export * from './renders/render-receipt-paper-template';
export * from './renders/render-payment-received-paper-template'; export * from './renders/render-payment-received-paper-template';

View File

@@ -0,0 +1,17 @@
import {
CreditNotePaperTemplate,
CreditNotePaperTemplateProps,
} from '../components/CreditNotePaperTemplate';
import { renderSSR } from './render-ssr';
/**
* Renders credit note paper template html.
* @param {CreditNotePaperTemplateProps} props
* @returns {string}
*/
export const renderCreditNotePaperTemplateHtml = (
props: CreditNotePaperTemplateProps
) => {
return renderSSR(<CreditNotePaperTemplate {...props} />);
};