Compare commits

...

16 Commits

Author SHA1 Message Date
Ahmed Bouhuolia
f7b53692f5 fix(server): Transaction type of credit note and vendor credit are not defined on account transactions 2023-08-22 13:51:15 +02:00
Ahmed Bouhuolia
b665d05526 chore: remove not used files 2023-08-21 11:39:01 +02:00
Ahmed Bouhuolia
de5300b186 Merge pull request #224 from bigcapitalhq/abouhuolia/big-54-specific-items-filter-on-purchasessells-by-items-reports
fix(webapp): filter by customers, vendors and items in reports do not work
2023-08-20 23:20:22 +02:00
Ahmed Bouhuolia
abc5631ac2 chore(webapp): document functions 2023-08-20 23:17:06 +02:00
Ahmed Bouhuolia
9e7b906c86 Merge pull request #221 from bigcapitalhq/abouhuolia/big-56-should-not-write-gl-entries-when-save-transaction-as-draft
fix(server): shouldn't write GL entries when save transaction as draft.
2023-08-20 23:04:31 +02:00
Ahmed Bouhuolia
d5decbbd0b fix(webap): sales by items query state from query string 2023-08-20 22:39:37 +02:00
Ahmed Bouhuolia
fbeb489128 fix(webapp): filter by customers, vendors and items in reports do not work 2023-08-20 01:59:44 +02:00
Ahmed Bouhuolia
5bf8a9e0ff chore: update CONTRIBUTING.md file 2023-08-17 23:06:06 +02:00
Ahmed Bouhuolia
68fa5cf5c5 Merge remote-tracking branch 'refs/remotes/origin/develop' into develop 2023-08-17 23:02:43 +02:00
Ahmed Bouhuolia
b1662c3175 chore: update CONTRIBUTING.md file 2023-08-17 23:02:13 +02:00
Ahmed Bouhuolia
0fcee0eaa7 fix(server): wirte GL entries only when publish transaction 2023-08-17 21:49:07 +02:00
Ahmed Bouhuolia
5b2be2ac19 fix(server): shouldn't write GL entries when save transaction as draft. 2023-08-16 23:05:39 +02:00
Ahmed Bouhuolia
5bb80fde34 Merge pull request #220 from bigcapitalhq/all-contributors/add-KalliopiPliogka
docs: add KalliopiPliogka as a contributor for bug
2023-08-16 21:39:26 +02:00
Ahmed Bouhuolia
58f90a0bcd Merge pull request #219 from KalliopiPliogka/bill-message-without-bill-number
Update index.json
2023-08-16 21:36:11 +02:00
Kalliopi Pliogka
74c4418549 Update BillForm.tsx
Removed the injected number value where the deleted keywords were used.
2023-08-16 22:30:31 +03:00
Kalliopi Pliogka
6b6e19f53b Update index.json
Fixed bill message. Now, bill message is showing without the bill number.
2023-08-16 21:39:00 +03:00
78 changed files with 991 additions and 794 deletions

View File

@@ -7,6 +7,7 @@ Please read through this document before submitting any issues or pull requests
## Sections
- [General Instructions](#general-instructions)
- [Local Setup Prerequisites](#local-setup-prerequisites)
- [Contribute to Backend](#contribute-to-backend)
- [Contribute to Frontend](#contribute-to-frontend)
- [Other Ways to Contribute](#other-ways-to-contribute)
@@ -31,9 +32,18 @@ Contributions via pull requests are much appreciated. Once the approach is agree
---
## Local Setup Prerequisites
- The application currently supports **Node.js v14.x**. Please ensure that you are using this version of Node.js when developing. (use [nvm](https://github.com/nvm-sh/nvm#installing-and-updating) to switch between node versions)
## Contribute to Backend
- Clone the `bigcapital` repository and `cd` into `bigcapital` directory.
- Create `.env` file by copying `.env.example` file to `.env`. (The ``.env.example`` file has all the necessary values of variables to start development directly).
```
cp .env.example .env
```
- Install all npm dependencies of the monorepo, you don't have to change directory to the `backend` package. just hit these command on root directory and it will install dependencies of all packages.
```

View File

@@ -58,6 +58,7 @@ export interface IAccountTransaction {
date: string | Date;
referenceType: string;
referenceTypeFormatted: string;
referenceId: number;
referenceNumber?: string;

View File

@@ -1,7 +1,7 @@
import { Knex } from 'knex';
import { IDynamicListFilterDTO } from './DynamicFilter';
import { IItemEntry, IItemEntryDTO } from './ItemEntry';
import { IBillLandedCost } from './LandedCost';
import { IBillLandedCost } from './LandedCost';
export interface IBillDTO {
vendorId: number;
billNumber: string;
@@ -99,17 +99,17 @@ export interface IBillCreatedPayload {
trx: Knex.Transaction;
}
export interface IBillCreatingPayload{
export interface IBillCreatingPayload {
tenantId: number;
billDTO: IBillDTO;
trx: Knex.Transaction;
trx: Knex.Transaction;
}
export interface IBillEditingPayload {
tenantId: number;
oldBill: IBill;
billDTO: IBillEditDTO;
trx: Knex.Transaction;
trx: Knex.Transaction;
}
export interface IBillEditedPayload {
tenantId: number;
@@ -129,7 +129,7 @@ export interface IBIllEventDeletedPayload {
export interface IBillEventDeletingPayload {
tenantId: number;
oldBill: IBill;
trx: Knex.Transaction;
trx: Knex.Transaction;
}
export enum BillAction {
Create = 'Create',
@@ -138,3 +138,16 @@ export enum BillAction {
View = 'View',
NotifyBySms = 'NotifyBySms',
}
export interface IBillOpeningPayload {
trx: Knex.Transaction;
tenantId: number;
oldBill: IBill;
}
export interface IBillOpenedPayload {
trx: Knex.Transaction;
bill: IBill;
oldBill: IBill;
tenantId: number;
}

View File

@@ -1,6 +1,5 @@
import { ISystemUser } from '@/interfaces';
import { Knex } from 'knex';
import { pick } from 'lodash';
import { ISystemUser } from '@/interfaces';
import { ILedgerEntry } from './Ledger';
import { ISaleInvoice } from './SaleInvoice';

View File

@@ -156,6 +156,7 @@ export interface ISaleInvoiceEventDeliveredPayload {
tenantId: number;
saleInvoiceId: number;
saleInvoice: ISaleInvoice;
trx: Knex.Transaction;
}
export interface ISaleInvoiceDeliveringPayload {

View File

@@ -1,6 +1,5 @@
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
import ItemSubscriber from '@/subscribers/Items/ItemSubscriber';
import InventoryAdjustmentsSubscriber from '@/subscribers/Inventory/InventoryAdjustment';
import BillWriteInventoryTransactionsSubscriber from '@/subscribers/Bills/WriteInventoryTransactions';
import PaymentSyncBillBalance from '@/subscribers/PaymentMades/PaymentSyncBillBalance';
@@ -87,7 +86,6 @@ export default () => {
export const susbcribers = () => {
return [
ItemSubscriber,
InventoryAdjustmentsSubscriber,
BillWriteInventoryTransactionsSubscriber,
PaymentSyncBillBalance,

View File

@@ -2,8 +2,11 @@ import { Model, raw } from 'objection';
import moment from 'moment';
import { isEmpty, castArray } from 'lodash';
import TenantModel from 'models/TenantModel';
import { getTransactionTypeLabel } from '@/utils/transactions-types';
export default class AccountTransaction extends TenantModel {
referenceType: string;
/**
* Table name
*/
@@ -30,40 +33,7 @@ export default class AccountTransaction extends TenantModel {
* @return {string}
*/
get referenceTypeFormatted() {
return AccountTransaction.getReferenceTypeFormatted(this.referenceType);
}
/**
* Reference type formatted.
*/
static getReferenceTypeFormatted(referenceType) {
const mapped = {
SaleInvoice: 'Sale invoice',
SaleReceipt: 'Sale receipt',
PaymentReceive: 'Payment receive',
Bill: 'Bill',
BillPayment: 'Payment made',
VendorOpeningBalance: 'Vendor opening balance',
CustomerOpeningBalance: 'Customer opening balance',
InventoryAdjustment: 'Inventory adjustment',
ManualJournal: 'Manual journal',
Journal: 'Manual journal',
Expense: 'Expense',
OwnerContribution: 'Owner contribution',
TransferToAccount: 'Transfer to account',
TransferFromAccount: 'Transfer from account',
OtherIncome: 'Other income',
OtherExpense: 'Other expense',
OwnerDrawing: 'Owner drawing',
InvoiceWriteOff: 'Invoice write-off',
CreditNote: 'transaction_type.credit_note',
VendorCredit: 'transaction_type.vendor_credit',
RefundCreditNote: 'transaction_type.refund_credit_note',
RefundVendorCredit: 'transaction_type.refund_vendor_credit',
};
return mapped[referenceType] || '';
return getTransactionTypeLabel(this.referenceType);
}
/**

View File

@@ -1,9 +1,13 @@
import { Model, raw } from 'objection';
import { castArray, isEmpty } from 'lodash';
import { castArray } from 'lodash';
import moment from 'moment';
import TenantModel from 'models/TenantModel';
import { getTransactionTypeLabel } from '@/utils/transactions-types';
export default class InventoryTransaction extends TenantModel {
transactionId: number;
transactionType: string;
/**
* Table name
*/
@@ -23,27 +27,7 @@ export default class InventoryTransaction extends TenantModel {
* @return {string}
*/
get transcationTypeFormatted() {
return InventoryTransaction.getReferenceTypeFormatted(this.transactionType);
}
/**
* Reference type formatted.
*/
static getReferenceTypeFormatted(referenceType) {
const mapped = {
SaleInvoice: 'Sale invoice',
SaleReceipt: 'Sale receipt',
PaymentReceive: 'Payment receive',
Bill: 'Bill',
BillPayment: 'Payment made',
VendorOpeningBalance: 'Vendor opening balance',
CustomerOpeningBalance: 'Customer opening balance',
InventoryAdjustment: 'Inventory adjustment',
ManualJournal: 'Manual journal',
Journal: 'Manual journal',
LandedCost: 'transaction_type.landed_cost',
};
return mapped[referenceType] || '';
return getTransactionTypeLabel(this.transactionType);
}
/**

View File

@@ -46,7 +46,7 @@ export default class AccountTransactionTransformer extends Transformer {
* @returns {string}
*/
public transactionTypeFormatted(transaction: IAccountTransaction) {
return transaction.referenceTypeFormatted;
return this.context.i18n.__(transaction.referenceTypeFormatted);
}
/**

View File

@@ -23,15 +23,6 @@ export class GetAccounts {
@Inject()
private transformer: TransformerInjectable;
/**
* Parsees accounts list filter DTO.
* @param filterDTO
* @returns
*/
private parseListFilterDTO(filterDTO) {
return R.compose(this.dynamicListService.parseStringifiedFilter)(filterDTO);
}
/**
* Retrieve accounts datatable list.
* @param {number} tenantId
@@ -75,4 +66,13 @@ export class GetAccounts {
filterMeta: dynamicList.getResponseMeta(),
};
};
/**
* Parsees accounts list filter DTO.
* @param filterDTO
* @returns
*/
private parseListFilterDTO(filterDTO) {
return R.compose(this.dynamicListService.parseStringifiedFilter)(filterDTO);
}
}

View File

@@ -1,9 +0,0 @@
export class AccountsReceivableRepository {
findOrCreateAccount = (currencyCode?: string) => {
};
}

View File

@@ -16,16 +16,16 @@ import BaseCreditNotes from './CreditNotes';
@Service()
export default class CreateCreditNote extends BaseCreditNotes {
@Inject()
uow: UnitOfWork;
private uow: UnitOfWork;
@Inject()
itemsEntriesService: ItemsEntriesService;
private itemsEntriesService: ItemsEntriesService;
@Inject()
tenancy: HasTenancyService;
private tenancy: HasTenancyService;
@Inject()
eventPublisher: EventPublisher;
private eventPublisher: EventPublisher;
/**
* Creates a new credit note.

View File

@@ -1,5 +1,4 @@
import { Service, Inject } from 'typedi';
import HasTenancyService from '@/services/Tenancy/TenancyService';
import events from '@/subscribers/events';
import {
IApplyCreditToInvoicesCreatedPayload,
@@ -10,15 +9,12 @@ import CreditNoteApplySyncInvoicesCreditedAmount from './CreditNoteApplySyncInvo
@Service()
export default class CreditNoteApplySyncInvoicesCreditedAmountSubscriber {
@Inject()
tenancy: HasTenancyService;
@Inject()
syncInvoicesWithCreditNote: CreditNoteApplySyncInvoicesCreditedAmount;
private syncInvoicesWithCreditNote: CreditNoteApplySyncInvoicesCreditedAmount;
/**
* Attaches events with handlers.
*/
attach(bus) {
public attach(bus) {
bus.subscribe(
events.creditNote.onApplyToInvoicesCreated,
this.incrementAppliedInvoicesOnceCreditCreated

View File

@@ -15,7 +15,7 @@ export default class CreditNoteInventoryTransactionsSubscriber {
/**
* Attaches events with publisher.
*/
attach(bus) {
public attach(bus) {
bus.subscribe(
events.creditNote.onCreated,
this.writeInventoryTranscationsOnceCreated
@@ -37,6 +37,7 @@ export default class CreditNoteInventoryTransactionsSubscriber {
/**
* Writes inventory transactions once credit note created.
* @param {ICreditNoteCreatedPayload} payload -
* @returns {Promise<void>}
*/
public writeInventoryTranscationsOnceCreated = async ({
tenantId,
@@ -44,9 +45,8 @@ export default class CreditNoteInventoryTransactionsSubscriber {
trx,
}: ICreditNoteCreatedPayload) => {
// Can't continue if the credit note is open yet.
if (!creditNote.isOpen) {
return;
}
if (!creditNote.isOpen) return;
await this.inventoryTransactions.createInventoryTransactions(
tenantId,
creditNote,
@@ -57,6 +57,7 @@ export default class CreditNoteInventoryTransactionsSubscriber {
/**
* Rewrites inventory transactions once credit note edited.
* @param {ICreditNoteEditedPayload} payload -
* @returns {Promise<void>}
*/
public rewriteInventoryTransactionsOnceEdited = async ({
tenantId,
@@ -65,9 +66,8 @@ export default class CreditNoteInventoryTransactionsSubscriber {
trx,
}: ICreditNoteEditedPayload) => {
// Can't continue if the credit note is open yet.
if (!creditNote.isOpen) {
return;
}
if (!creditNote.isOpen) return;
await this.inventoryTransactions.editInventoryTransactions(
tenantId,
creditNoteId,
@@ -87,9 +87,8 @@ export default class CreditNoteInventoryTransactionsSubscriber {
trx,
}: ICreditNoteDeletedPayload) => {
// Can't continue if the credit note is open yet.
if (!oldCreditNote.isOpen) {
return;
}
if (!oldCreditNote.isOpen) return;
await this.inventoryTransactions.deleteInventoryTransactions(
tenantId,
creditNoteId,

View File

@@ -21,7 +21,7 @@ export class ExpensesWriteGLSubscriber {
* Attaches events with handlers.
* @param bus
*/
attach(bus) {
public attach(bus) {
bus.subscribe(
events.expenses.onCreated,
this.handleWriteGLEntriesOnceCreated

View File

@@ -48,6 +48,7 @@ export class ManualJournalWriteGLSubscriber {
/**
* Handle manual journal created event.
* @param {IManualJournalEventCreatedPayload} payload -
* @returns {Promise<void>}
*/
private handleWriteJournalEntriesOnCreated = async ({
tenantId,
@@ -55,18 +56,19 @@ export class ManualJournalWriteGLSubscriber {
trx,
}: IManualJournalEventCreatedPayload) => {
// Ingore writing manual journal journal entries in case was not published.
if (manualJournal.publishedAt) {
await this.manualJournalGLEntries.createManualJournalGLEntries(
tenantId,
manualJournal.id,
trx
);
}
if (!manualJournal.publishedAt) return;
await this.manualJournalGLEntries.createManualJournalGLEntries(
tenantId,
manualJournal.id,
trx
);
};
/**
* Handles the manual journal next number increment once the journal be created.
* @param {IManualJournalEventCreatedPayload} payload -
* @return {Promise<void>}
*/
private handleJournalNumberIncrement = async ({
tenantId,
@@ -77,6 +79,7 @@ export class ManualJournalWriteGLSubscriber {
/**
* Handle manual journal edited event.
* @param {IManualJournalEventEditedPayload}
* @return {Promise<void>}
*/
private handleRewriteJournalEntriesOnEdited = async ({
tenantId,
@@ -96,6 +99,7 @@ export class ManualJournalWriteGLSubscriber {
/**
* Handles writing journal entries once the manula journal publish.
* @param {IManualJournalEventPublishedPayload} payload -
* @return {Promise<void>}
*/
private handleWriteJournalEntriesOnPublished = async ({
tenantId,

View File

@@ -4,6 +4,7 @@ import {
IBillCreatedPayload,
IBillEditedPayload,
IBIllEventDeletedPayload,
IBillOpenedPayload,
} from '@/interfaces';
import { BillGLEntries } from './BillGLEntries';
@@ -20,6 +21,10 @@ export class BillGLEntriesSubscriber {
events.bill.onCreated,
this.handlerWriteJournalEntriesOnCreate
);
bus.subscribe(
events.bill.onOpened,
this.handlerWriteJournalEntriesOnCreate
);
bus.subscribe(
events.bill.onEdited,
this.handleOverwriteJournalEntriesOnEdit
@@ -33,10 +38,12 @@ export class BillGLEntriesSubscriber {
*/
private handlerWriteJournalEntriesOnCreate = async ({
tenantId,
billId,
bill,
trx,
}: IBillCreatedPayload) => {
await this.billGLEntries.writeBillGLEntries(tenantId, billId, trx);
}: IBillCreatedPayload | IBillOpenedPayload) => {
if (!bill.openedAt) return null;
await this.billGLEntries.writeBillGLEntries(tenantId, bill.id, trx);
};
/**
@@ -46,8 +53,11 @@ export class BillGLEntriesSubscriber {
private handleOverwriteJournalEntriesOnEdit = async ({
tenantId,
billId,
bill,
trx,
}: IBillEditedPayload) => {
if (!bill.openedAt) return null;
await this.billGLEntries.rewriteBillGLEntries(tenantId, billId, trx);
};

View File

@@ -132,7 +132,7 @@ export class EditBill {
} as IBillEditingPayload);
// Update the bill transaction.
const bill = await Bill.query(trx).upsertGraph({
const bill = await Bill.query(trx).upsertGraphAndFetch({
id: billId,
...billObj,
});

View File

@@ -5,6 +5,9 @@ import { ERRORS } from './constants';
import HasTenancyService from '@/services/Tenancy/TenancyService';
import UnitOfWork from '@/services/UnitOfWork';
import { BillsValidators } from './BillsValidators';
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
import events from '@/subscribers/events';
import { IBillOpenedPayload, IBillOpeningPayload } from '@/interfaces';
@Service()
export class OpenBill {
@@ -17,6 +20,9 @@ export class OpenBill {
@Inject()
private validators: BillsValidators;
@Inject()
private eventPublisher: EventPublisher;
/**
* Mark the bill as open.
* @param {number} tenantId
@@ -37,10 +43,27 @@ export class OpenBill {
throw new ServiceError(ERRORS.BILL_ALREADY_OPEN);
}
return this.uow.withTransaction(tenantId, async (trx) => {
// Record the bill opened at on the storage.
await Bill.query(trx).findById(billId).patch({
openedAt: moment().toMySqlDateTime(),
});
// Triggers `onBillCreating` event.
await this.eventPublisher.emitAsync(events.bill.onOpening, {
trx,
tenantId,
oldBill,
} as IBillOpeningPayload);
// Save the bill opened at on the storage.
const bill = await Bill.query(trx)
.patchAndFetchById(billId, {
openedAt: moment().toMySqlDateTime(),
})
.withGraphFetched('entries');
// Triggers `onBillCreating` event.
await this.eventPublisher.emitAsync(events.bill.onOpened, {
trx,
bill,
oldBill,
tenantId,
} as IBillOpenedPayload);
});
}
}

View File

@@ -10,7 +10,7 @@ import VendorCreditInventoryTransactions from './VendorCreditInventoryTransactio
@Service()
export default class VendorCreditInventoryTransactionsSubscriber {
@Inject()
inventoryTransactions: VendorCreditInventoryTransactions;
private inventoryTransactions: VendorCreditInventoryTransactions;
/**
* Attaches events with handlers.
@@ -21,6 +21,10 @@ export default class VendorCreditInventoryTransactionsSubscriber {
events.vendorCredit.onCreated,
this.writeInventoryTransactionsOnceCreated
);
bus.subscribe(
events.vendorCredit.onOpened,
this.writeInventoryTransactionsOnceCreated
);
bus.subscribe(
events.vendorCredit.onEdited,
this.rewriteInventroyTransactionsOnceEdited
@@ -40,6 +44,9 @@ export default class VendorCreditInventoryTransactionsSubscriber {
vendorCredit,
trx,
}: IVendorCreditCreatedPayload) => {
// Can't continue if vendor credit is not opened.
if (!vendorCredit.openedAt) return null;
await this.inventoryTransactions.createInventoryTransactions(
tenantId,
vendorCredit,
@@ -57,6 +64,9 @@ export default class VendorCreditInventoryTransactionsSubscriber {
vendorCredit,
trx,
}: IVendorCreditEditedPayload) => {
// Can't continue if vendor credit is not opened.
if (!vendorCredit.openedAt) return null;
await this.inventoryTransactions.editInventoryTransactions(
tenantId,
vendorCreditId,

View File

@@ -63,14 +63,17 @@ export class DeliverSaleInvoice {
// Record the delivered at on the storage.
const saleInvoice = await SaleInvoice.query(trx)
.where({ id: saleInvoiceId })
.update({ deliveredAt: moment().toMySqlDateTime() });
.patchAndFetchById(saleInvoiceId, {
deliveredAt: moment().toMySqlDateTime(),
})
.withGraphFetched('entries');
// Triggers `onSaleInvoiceDelivered` event.
await this.eventPublisher.emitAsync(events.saleInvoice.onDelivered, {
tenantId,
saleInvoiceId,
saleInvoice,
trx,
} as ISaleInvoiceEventDeliveredPayload);
});
}

View File

@@ -58,12 +58,12 @@ export class CloseSaleReceipt {
} as ISaleReceiptEventClosingPayload);
// Mark the sale receipt as closed on the storage.
const saleReceipt = await SaleReceipt.query(trx)
.findById(saleReceiptId)
.patch({
const saleReceipt = await SaleReceipt.query(trx).patchAndFetchById(
saleReceiptId,
{
closedAt: moment().toMySqlDateTime(),
});
}
);
// Triggers `onSaleReceiptClosed` event.
await this.eventPublisher.emitAsync(events.saleReceipt.onClosed, {
saleReceiptId,

View File

@@ -4,6 +4,7 @@ import {
IBillCreatedPayload,
IBillEditedPayload,
IBIllEventDeletedPayload,
IBillOpenedPayload,
} from '@/interfaces';
import { BillInventoryTransactions } from '@/services/Purchases/Bills/BillInventoryTransactions';
@@ -20,6 +21,10 @@ export default class BillWriteInventoryTransactionsSubscriber {
events.bill.onCreated,
this.handleWritingInventoryTransactions
);
bus.subscribe(
events.bill.onOpened,
this.handleWritingInventoryTransactions
);
bus.subscribe(
events.bill.onEdited,
this.handleOverwritingInventoryTransactions
@@ -32,15 +37,19 @@ export default class BillWriteInventoryTransactionsSubscriber {
/**
* Handles writing the inventory transactions once bill created.
* @param {IBillCreatedPayload | IBillOpenedPayload} payload -
*/
private handleWritingInventoryTransactions = async ({
tenantId,
billId,
bill,
trx,
}: IBillCreatedPayload) => {
}: IBillCreatedPayload | IBillOpenedPayload) => {
// Can't continue if the bill is not opened yet.
if (!bill.openedAt) return null;
await this.billsInventory.recordInventoryTransactions(
tenantId,
billId,
bill.id,
false,
trx
);
@@ -48,12 +57,17 @@ export default class BillWriteInventoryTransactionsSubscriber {
/**
* Handles the overwriting the inventory transactions once bill edited.
* @param {IBillEditedPayload} payload -
*/
private handleOverwritingInventoryTransactions = async ({
tenantId,
billId,
bill,
trx,
}: IBillEditedPayload) => {
// Can't continue if the bill is not opened yet.
if (!bill.openedAt) return null;
await this.billsInventory.recordInventoryTransactions(
tenantId,
billId,
@@ -64,6 +78,7 @@ export default class BillWriteInventoryTransactionsSubscriber {
/**
* Handles the reverting the inventory transactions once the bill deleted.
* @param {IBIllEventDeletedPayload} payload -
*/
private handleRevertInventoryTransactions = async ({
tenantId,

View File

@@ -19,7 +19,7 @@ export default class BillWriteGLEntriesSubscriber {
/**
* Attachs events with handles.
*/
attach(bus) {
public attach(bus) {
bus.subscribe(
events.bill.onCreated,
this.handlerWriteJournalEntriesOnCreate
@@ -38,8 +38,12 @@ export default class BillWriteGLEntriesSubscriber {
private handlerWriteJournalEntriesOnCreate = async ({
tenantId,
billId,
bill,
trx,
}: IBillCreatedPayload) => {
// Can't continue if the bill is not opened yet.
if (!bill.openedAt) return null;
await this.billsService.recordJournalTransactions(
tenantId,
billId,
@@ -55,8 +59,12 @@ export default class BillWriteGLEntriesSubscriber {
private handleOverwriteJournalEntriesOnEdit = async ({
tenantId,
billId,
bill,
trx,
}: IBillEditedPayload) => {
// Can't continue if the bill is not opened yet.
if (!bill.openedAt) return null;
await this.billsService.recordJournalTransactions(
tenantId,
billId,

View File

@@ -1,37 +0,0 @@
import { Container } from 'typedi';
import { EventSubscriber, On } from 'event-dispatch';
import { map, head } from 'lodash';
import events from '@/subscribers/events';
import TenancyService from '@/services/Tenancy/TenancyService';
import SaleInvoicesCost from '@/services/Sales/SalesInvoicesCost';
import InventoryItemsQuantitySync from '@/services/Inventory/InventoryItemsQuantitySync';
import InventoryService from '@/services/Inventory/Inventory';
@EventSubscriber()
export class OwnerContributionCashflowSubscriber {
depends: number = 0;
startingDate: Date;
saleInvoicesCost: SaleInvoicesCost;
tenancy: TenancyService;
itemsQuantitySync: InventoryItemsQuantitySync;
inventoryService: InventoryService;
agenda: any;
/**
* Constructor method.
*/
constructor() {
this.tenancy = Container.get(TenancyService);
}
/**
* Marks items cost compute running state.
*/
@On(events.cashflow.onOwnerContributionCreate)
async writeOwnerContributionJournalEntries({
}) {
}
}

View File

@@ -1,18 +0,0 @@
import events from '@/subscribers/events';
import { EventSubscriber } from '@/lib/EventPublisher/EventPublisher';
import { Service } from 'typedi';
@Service()
export default class ItemSubscriber extends EventSubscriber {
/**
* Attaches the events with handles.
* @param bus
*/
attach(bus) {
bus.subscribe(events.item.onCreated, this.handleItemCreated);
}
handleItemCreated() {
}
}

View File

@@ -37,7 +37,6 @@ export default class PaymentReceiveSyncInvoicesSubscriber {
*/
private handleInvoiceIncrementPaymentOnceCreated = async ({
tenantId,
paymentReceiveId,
paymentReceive,
trx,
}: IPaymentReceiveCreatedPayload) => {

View File

@@ -4,6 +4,7 @@ import {
ISaleInvoiceCreatedPayload,
ISaleInvoiceDeletedPayload,
ISaleInvoiceEditedPayload,
ISaleInvoiceEventDeliveredPayload,
} from '@/interfaces';
import { InvoiceInventoryTransactions } from '@/services/Sales/Invoices/InvoiceInventoryTransactions';
@@ -20,6 +21,10 @@ export default class WriteInventoryTransactions {
events.saleInvoice.onCreated,
this.handleWritingInventoryTransactions
);
bus.subscribe(
events.saleInvoice.onDelivered,
this.handleWritingInventoryTransactions
);
bus.subscribe(
events.saleInvoice.onEdited,
this.handleRewritingInventoryTransactions
@@ -38,7 +43,10 @@ export default class WriteInventoryTransactions {
tenantId,
saleInvoice,
trx,
}: ISaleInvoiceCreatedPayload) => {
}: ISaleInvoiceCreatedPayload | ISaleInvoiceEventDeliveredPayload) => {
// Can't continue if the sale invoice is not delivered yet.
if (!saleInvoice.deliveredAt) return null;
await this.saleInvoiceInventory.recordInventoryTranscactions(
tenantId,
saleInvoice,

View File

@@ -15,11 +15,15 @@ export default class SaleInvoiceWriteGLEntriesSubscriber {
/**
* Constructor method.
*/
attach(bus) {
public attach(bus) {
bus.subscribe(
events.saleInvoice.onCreated,
this.handleWriteJournalEntriesOnInvoiceCreated
);
bus.subscribe(
events.saleInvoice.onDelivered,
this.handleWriteJournalEntriesOnInvoiceCreated
);
bus.subscribe(
events.saleInvoice.onEdited,
this.handleRewriteJournalEntriesOnceInvoiceEdit
@@ -32,12 +36,18 @@ export default class SaleInvoiceWriteGLEntriesSubscriber {
/**
* Records journal entries of the non-inventory invoice.
* @param {ISaleInvoiceCreatedPayload} payload -
* @returns {Promise<void>}
*/
private handleWriteJournalEntriesOnInvoiceCreated = async ({
tenantId,
saleInvoiceId,
saleInvoice,
trx,
}: ISaleInvoiceCreatedPayload) => {
// Can't continue if the sale invoice is not delivered yet.
if (!saleInvoice.deliveredAt) return null;
await this.saleInvoiceGLEntries.writeInvoiceGLEntries(
tenantId,
saleInvoiceId,
@@ -47,12 +57,17 @@ export default class SaleInvoiceWriteGLEntriesSubscriber {
/**
* Records journal entries of the non-inventory invoice.
* @param {ISaleInvoiceEditedPayload} payload -
* @returns {Promise<void>}
*/
private handleRewriteJournalEntriesOnceInvoiceEdit = async ({
tenantId,
saleInvoice,
trx,
}: ISaleInvoiceEditedPayload) => {
// Can't continue if the sale invoice is not delivered yet.
if (!saleInvoice.deliveredAt) return null;
await this.saleInvoiceGLEntries.rewritesInvoiceGLEntries(
tenantId,
saleInvoice.id,
@@ -62,6 +77,8 @@ export default class SaleInvoiceWriteGLEntriesSubscriber {
/**
* Handle reverting journal entries once sale invoice delete.
* @param {ISaleInvoiceDeletePayload} payload -
* @returns {Promise<void>}
*/
private handleRevertingInvoiceJournalEntriesOnDelete = async ({
tenantId,

View File

@@ -40,6 +40,9 @@ export default class SaleReceiptInventoryTransactionsSubscriber {
saleReceipt,
trx,
}: ISaleReceiptCreatedPayload) => {
// Can't continue if the sale receipt is not closed yet.
if (!saleReceipt.closedAt) return null;
await this.saleReceiptInventory.recordInventoryTransactions(
tenantId,
saleReceipt,
@@ -57,6 +60,9 @@ export default class SaleReceiptInventoryTransactionsSubscriber {
saleReceipt,
trx,
}: ISaleReceiptEditedPayload) => {
// Can't continue if the sale receipt is not closed yet.
if (!saleReceipt.closedAt) return null;
await this.saleReceiptInventory.recordInventoryTransactions(
tenantId,
saleReceipt,

View File

@@ -21,6 +21,10 @@ export default class SaleReceiptWriteGLEntriesSubscriber {
events.saleReceipt.onCreated,
this.handleWriteReceiptIncomeJournalEntrieOnCreate
);
bus.subscribe(
events.saleReceipt.onClosed,
this.handleWriteReceiptIncomeJournalEntrieOnCreate
);
bus.subscribe(
events.saleReceipt.onEdited,
this.handleWriteReceiptIncomeJournalEntrieOnEdited
@@ -38,8 +42,12 @@ export default class SaleReceiptWriteGLEntriesSubscriber {
public handleWriteReceiptIncomeJournalEntrieOnCreate = async ({
tenantId,
saleReceiptId,
saleReceipt,
trx,
}: ISaleReceiptCreatedPayload) => {
// Can't continue if the sale receipt is not closed yet.
if (!saleReceipt.closedAt) return null;
// Writes the sale receipt income journal entries.
await this.saleReceiptGLEntries.writeIncomeGLEntries(
tenantId,
@@ -71,8 +79,12 @@ export default class SaleReceiptWriteGLEntriesSubscriber {
private handleWriteReceiptIncomeJournalEntrieOnEdited = async ({
tenantId,
saleReceiptId,
saleReceipt,
trx,
}: ISaleReceiptEditedPayload) => {
// Can't continue if the sale receipt is not closed yet.
if (!saleReceipt.closedAt) return null;
// Writes the sale receipt income journal entries.
await this.saleReceiptGLEntries.rewriteReceiptGLEntries(
tenantId,

View File

@@ -220,6 +220,9 @@ export default {
onPublishing: 'onBillPublishing',
onPublished: 'onBillPublished',
onOpening: 'onBillOpening',
onOpened: 'onBillOpened',
},
/**

View File

@@ -0,0 +1,5 @@
import { TransactionTypes } from '@/data/TransactionTypes';
export const getTransactionTypeLabel = (transactionType: string) => {
return TransactionTypes[transactionType];
};

View File

@@ -1,43 +1,78 @@
// @ts-nocheck
import React, { useCallback } from 'react';
import { MenuItem } from '@blueprintjs/core';
import { MultiSelect } from '../MultiSelectTaggable';
import * as R from 'ramda';
import { FMultiSelect } from '../Forms';
import withDrawerActions from '@/containers/Drawer/withDrawerActions';
import { DRAWERS } from '@/constants/drawers';
/**
* Contacts multi-select component.
*/
export function ContactsMultiSelect({ ...multiSelectProps }) {
// Filters accounts items.
const filterContactsPredicater = useCallback(
(query, contact, _index, exactMatch) => {
const normalizedTitle = contact.display_name.toLowerCase();
const normalizedQuery = query.toLowerCase();
if (exactMatch) {
return normalizedTitle === normalizedQuery;
} else {
return normalizedTitle.indexOf(normalizedQuery) >= 0;
}
},
[],
);
export function ContactsMultiSelect({ allowCreate, ...multiSelectProps }) {
// Maybe inject new item props to select component.
const maybeCreateNewItemRenderer = allowCreate ? createNewItemRenderer : null;
const maybeCreateNewItemFromQuery = allowCreate
? createNewItemFromQuery
: null;
return (
<MultiSelect
itemRenderer={(contact, { selected, active, handleClick }) => (
<MenuItem
active={active}
icon={selected ? 'tick' : 'blank'}
text={contact.display_name}
key={contact.id}
onClick={handleClick}
/>
)}
<FMultiSelect
valueAccessor={'id'}
textAccessor={'display_name'}
tagAccessor={'display_name'}
popoverProps={{ minimal: true }}
fill={true}
itemPredicate={filterContactsPredicater}
tagRenderer={(item) => item.display_name}
createNewItemRenderer={maybeCreateNewItemRenderer}
createNewItemFromQuery={maybeCreateNewItemFromQuery}
{...multiSelectProps}
/>
);
}
/**
* Customers multi-select component.
*/
function CustomersMultiSelectRoot({
// #withDrawerAction
openDrawer,
closeDrawer,
...props
}) {
const handleCreateItemClick = () => {
openDrawer(DRAWERS.QUICK_CREATE_CUSTOMER);
};
return (
<ContactsMultiSelect
onCreateItemSelect={handleCreateItemClick}
{...props}
/>
);
}
/**
* Vendors multi-select component.
*/
function VendorsMultiSelectRoot({
// #withDrawerAction
openDrawer,
closeDrawer,
...props
}) {
const handleCreateItemClick = () => {
openDrawer(DRAWERS.QUICK_WRITE_VENDOR);
};
return (
<ContactsMultiSelect
onCreateItemSelect={handleCreateItemClick}
{...props}
/>
);
}
export const CustomersMultiSelect = R.compose(withDrawerActions)(
CustomersMultiSelectRoot,
);
export const VendorsMultiSelect = R.compose(withDrawerActions)(
VendorsMultiSelectRoot,
);

View File

@@ -1,49 +1,48 @@
// @ts-nocheck
import React, { useCallback } from 'react';
import { MenuItem } from '@blueprintjs/core';
import { MultiSelect } from '@/components';
import React from 'react';
import * as R from 'ramda';
import { FMultiSelect } from '@/components/Forms';
import withDialogActions from '@/containers/Dialog/withDialogActions';
/**
* Items multi-select.
*/
export function ItemsMultiSelect({ ...multiSelectProps }) {
// Filters accounts items.
const filterItemsPredicater = useCallback(
(query, item, _index, exactMatch) => {
const normalizedTitle = item.name.toLowerCase();
const normalizedQuery = query.toLowerCase();
function ItemsMultiSelectRoot({
// #withDialogAction
openDialog,
closeDialog,
if (exactMatch) {
return normalizedTitle === normalizedQuery;
} else {
return `${normalizedTitle} ${item.code}`.indexOf(normalizedQuery) >= 0;
}
},
[],
);
// #props
allowCreate,
...multiSelectProps
}) {
// Maybe inject new item props to select component.
const maybeCreateNewItemRenderer = allowCreate ? createNewItemRenderer : null;
const maybeCreateNewItemFromQuery = allowCreate
? createNewItemFromQuery
: null;
// Handles the create item click.
const handleCreateItemClick = () => {
openDialog(DialogsName.AccountForm);
};
return (
<MultiSelect
itemRenderer={(item, { selected, handleClick, active }) => (
<MenuItem
active={active}
icon={selected ? 'tick' : 'blank'}
text={item.name}
label={item.code}
key={item.id}
onClick={handleClick}
/>
)}
popoverProps={{ minimal: true, usePortal: false, targetTagName: 'div ' }}
<FMultiSelect
valueAccessor={'id'}
textAccessor={'name'}
labelAccessor={'code'}
tagAccessor={'name'}
fill={true}
itemPredicate={filterItemsPredicater}
tagRenderer={(item) => item.name}
popoverProps={{ minimal: true }}
resetOnSelect={true}
createNewItemRenderer={maybeCreateNewItemRenderer}
createNewItemFromQuery={maybeCreateNewItemFromQuery}
onCreateItemSelect={handleCreateItemClick}
{...multiSelectProps}
/>
);
}
ItemsMultiSelect.defaultProps = {
initialSelectedItems: [],
};
export const ItemsMultiSelect =
R.compose(withDialogActions)(ItemsMultiSelectRoot);

View File

@@ -1,8 +1,8 @@
// @ts-nocheck
import React, { useState, useCallback, useEffect } from 'react';
import React, { useCallback, useEffect } from 'react';
import moment from 'moment';
import { getDefaultAPAgingSummaryQuery } from './common';
import { useAPAgingSummaryQuery } from './common';
import { FinancialStatement, DashboardPageContent } from '@/components';
import APAgingSummaryHeader from './APAgingSummaryHeader';
@@ -26,25 +26,22 @@ function APAgingSummary({
// #withAPAgingSummaryActions
toggleAPAgingSummaryFilterDrawer: toggleDisplayFilterDrawer,
}) {
const [filter, setFilter] = useState({
...getDefaultAPAgingSummaryQuery(),
});
const { query, setLocationQuery } = useAPAgingSummaryQuery();
// Handle filter submit.
const handleFilterSubmit = useCallback((filter) => {
const _filter = {
...filter,
asDate: moment(filter.asDate).format('YYYY-MM-DD'),
};
setFilter(_filter);
}, []);
const handleFilterSubmit = useCallback(
(filter) => {
const _filter = {
...filter,
asDate: moment(filter.asDate).format('YYYY-MM-DD'),
};
setLocationQuery(_filter);
},
[setLocationQuery],
);
// Handle number format submit.
const handleNumberFormatSubmit = (numberFormat) => {
setFilter({
...filter,
numberFormat,
});
setLocationQuery({ ...filter, numberFormat });
};
// Hide the report filter drawer once the page unmount.
useEffect(
@@ -55,9 +52,9 @@ function APAgingSummary({
);
return (
<APAgingSummaryProvider filter={filter}>
<APAgingSummaryProvider filter={query}>
<APAgingSummaryActionsBar
numberFormat={filter.numberFormat}
numberFormat={query.numberFormat}
onNumberFormatSubmit={handleNumberFormatSubmit}
/>
<APAgingSummarySheetLoadingBar />
@@ -65,7 +62,7 @@ function APAgingSummary({
<DashboardPageContent>
<FinancialStatement name={'AP-aging-summary'}>
<APAgingSummaryHeader
pageFilter={filter}
pageFilter={query}
onSubmitFilter={handleFilterSubmit}
/>
<APAgingSummaryBody organizationName={organizationName} />

View File

@@ -1,7 +1,5 @@
// @ts-nocheck
import React from 'react';
import moment from 'moment';
import * as Yup from 'yup';
import styled from 'styled-components';
import { FormattedMessage as T } from '@/components';
import { Formik, Form } from 'formik';
@@ -17,6 +15,10 @@ import withAPAgingSummaryActions from './withAPAgingSummaryActions';
import { transformToForm, compose } from '@/utils';
import { useFeatureCan } from '@/hooks/state';
import { Features } from '@/constants';
import {
getAPAgingSummaryQuerySchema,
getDefaultAPAgingSummaryQuery,
} from './common';
/**
* AP Aging Summary Report - Drawer Header.
@@ -33,39 +35,22 @@ function APAgingSummaryHeader({
isFilterDrawerOpen,
}) {
// Validation schema.
const validationSchema = Yup.object({
asDate: Yup.date().required().label('asDate'),
agingDaysBefore: Yup.number()
.required()
.integer()
.positive()
.label('agingBeforeDays'),
agingPeriods: Yup.number()
.required()
.integer()
.positive()
.label('agingPeriods'),
});
const validationSchema = getAPAgingSummaryQuerySchema();
// Initial values.
const defaultValues = {
asDate: moment(pageFilter.asDate).toDate(),
agingDaysBefore: 30,
agingPeriods: 3,
vendorsIds: [],
branchesIds: [],
filterByOption: 'without-zero-balance',
};
// Formik initial values.
const initialValues = transformToForm({ ...pageFilter }, defaultValues);
const defaultValues = getDefaultAPAgingSummaryQuery();
// Formik initial values.
const initialValues = transformToForm(
{ ...defaultValues, ...pageFilter },
defaultValues,
);
// Handle form submit.
const handleSubmit = (values, { setSubmitting }) => {
onSubmitFilter(values);
toggleFilterDrawerDisplay(false);
setSubmitting(false);
};
// Handle cancel button click.
const handleCancelClick = () => {
toggleFilterDrawerDisplay(false);
@@ -74,9 +59,8 @@ function APAgingSummaryHeader({
const handleDrawerClose = () => {
toggleFilterDrawerDisplay(false);
};
// Detarmines the feature whether is enabled.
// Detarmines whether the feature is enabled.
const { featureCan } = useFeatureCan();
const isBranchesFeatureCan = featureCan(Features.Branches);
return (

View File

@@ -1,21 +1,15 @@
// @ts-nocheck
import React from 'react';
import { FastField, Field } from 'formik';
import { FastField } from 'formik';
import { Intent, FormGroup, InputGroup, Position } from '@blueprintjs/core';
import { DateInput } from '@blueprintjs/datetime';
import {
Intent,
FormGroup,
InputGroup,
Position,
Classes,
} from '@blueprintjs/core';
import classNames from 'classnames';
import {
FormattedMessage as T,
ContactsMultiSelect,
Row,
Col,
FieldHint,
FFormGroup,
VendorsMultiSelect,
} from '@/components';
import { useAPAgingSummaryGeneralContext } from './APAgingSummaryGeneralProvider';
import FinancialStatementsFilter from '../FinancialStatementsFilter';
@@ -104,22 +98,9 @@ export default function APAgingSummaryHeaderGeneralContent() {
<Row>
<Col xs={5}>
<Field name={'vendorsIds'}>
{({ form: { setFieldValue }, field: { value } }) => (
<FormGroup
label={<T id={'specific_vendors'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ContactsMultiSelect
items={vendors}
onItemSelect={(vendors) => {
const vendorsIds = vendors.map((customer) => customer.id);
setFieldValue('vendorsIds', vendorsIds);
}}
/>
</FormGroup>
)}
</Field>
<FFormGroup label={<T id={'specific_vendors'} />} name={'vendorsIds'}>
<VendorsMultiSelect name={'vendorsIds'} items={vendors} />
</FFormGroup>
</Col>
</Row>
</div>

View File

@@ -1,18 +1,80 @@
// @ts-nocheck
import moment from 'moment';
import { transformToCamelCase, flatObject } from '@/utils';
import * as Yup from 'yup';
import { transformToCamelCase, flatObject, transformToForm } from '@/utils';
import { useAppQueryString } from '@/hooks';
import { useMemo } from 'react';
import { castArray } from 'lodash';
export const transformFilterFormToQuery = (form) => {
return flatObject(transformToCamelCase(form));
};
/**
* The default query of AP aging summary.
* @returns
*/
export const getDefaultAPAgingSummaryQuery = () => {
return {
asDate: moment().endOf('day').format('YYYY-MM-DD'),
agingDaysBefore: 30,
agingPeriods: 3,
filterByOption: 'without-zero-balance',
vendorsIds: [],
branchesIds: [],
filterByOption: 'without-zero-balance',
}
}
};
};
/**
* Retrieves the query validation schema.
* @returns {Yup}
*/
export const getAPAgingSummaryQuerySchema = () => {
return Yup.object({
asDate: Yup.date().required().label('asDate'),
agingDaysBefore: Yup.number()
.required()
.integer()
.positive()
.label('agingBeforeDays'),
agingPeriods: Yup.number()
.required()
.integer()
.positive()
.label('agingPeriods'),
});
};
/**
* Parses the AP aging summary query state.
* @param locationQuery
* @returns
*/
const parseAPAgingSummaryQuery = (locationQuery) => {
const defaultQuery = getDefaultAPAgingSummaryQuery();
const transformed = {
...defaultQuery,
...transformToForm(locationQuery, defaultQuery),
};
return {
...transformed,
vendorsIds: castArray(transformed.vendorsIds),
branchesIds: castArray(transformed.branchesIds),
};
};
/**
* AP aging summary query state.
*/
export const useAPAgingSummaryQuery = () => {
// Retrieves location query.
const [locationQuery, setLocationQuery] = useAppQueryString();
// Merges the default filter query with location URL query.
const query = useMemo(
() => parseAPAgingSummaryQuery(locationQuery),
[locationQuery],
);
return { query, locationQuery, setLocationQuery };
};

View File

@@ -2,7 +2,6 @@
import React, { useState, useCallback, useEffect } from 'react';
import moment from 'moment';
import ARAgingSummaryHeader from './ARAgingSummaryHeader';
import ARAgingSummaryActionsBar from './ARAgingSummaryActionsBar';
@@ -13,7 +12,7 @@ import { ARAgingSummaryBody } from './ARAgingSummaryBody';
import withARAgingSummaryActions from './withARAgingSummaryActions';
import { getDefaultARAgingSummaryQuery } from './common';
import { useARAgingSummaryQuery } from './common';
import { compose } from '@/utils';
/**
@@ -23,9 +22,7 @@ function ReceivableAgingSummarySheet({
// #withARAgingSummaryActions
toggleARAgingSummaryFilterDrawer: toggleDisplayFilterDrawer,
}) {
const [filter, setFilter] = useState({
...getDefaultARAgingSummaryQuery(),
});
const { query, setLocationQuery } = useARAgingSummaryQuery();
// Handle filter submit.
const handleFilterSubmit = useCallback((filter) => {
@@ -33,25 +30,23 @@ function ReceivableAgingSummarySheet({
...filter,
asDate: moment(filter.asDate).format('YYYY-MM-DD'),
};
setFilter(_filter);
}, []);
setLocationQuery(_filter);
}, [setLocationQuery]);
// Handle number format submit.
const handleNumberFormatSubmit = (numberFormat) => {
setFilter({ ...filter, numberFormat });
setLocationQuery({ ...query, numberFormat });
};
// Hide the filter drawer once the page unmount.
useEffect(
() => () => {
toggleDisplayFilterDrawer(false);
},
() => () => toggleDisplayFilterDrawer(false),
[toggleDisplayFilterDrawer],
);
return (
<ARAgingSummaryProvider filter={filter}>
<ARAgingSummaryProvider filter={query}>
<ARAgingSummaryActionsBar
numberFormat={filter.numberFormat}
numberFormat={query.numberFormat}
onNumberFormatSubmit={handleNumberFormatSubmit}
/>
<ARAgingSummarySheetLoadingBar />
@@ -59,7 +54,7 @@ function ReceivableAgingSummarySheet({
<DashboardPageContent>
<FinancialStatement>
<ARAgingSummaryHeader
pageFilter={filter}
pageFilter={query}
onSubmitFilter={handleFilterSubmit}
/>
<ARAgingSummaryBody />

View File

@@ -2,7 +2,6 @@
import React from 'react';
import styled from 'styled-components';
import moment from 'moment';
import * as Yup from 'yup';
import { FormattedMessage as T } from '@/components';
import { Formik, Form } from 'formik';
import { Tabs, Tab, Button, Intent } from '@blueprintjs/core';
@@ -17,6 +16,10 @@ import withARAgingSummaryActions from './withARAgingSummaryActions';
import { compose, transformToForm } from '@/utils';
import { useFeatureCan } from '@/hooks/state';
import { Features } from '@/constants';
import {
getARAgingSummaryQuerySchema,
getDefaultARAgingSummaryQuery,
} from './common';
/**
* AR Aging Summary Report - Drawer Header.
@@ -33,32 +36,15 @@ function ARAgingSummaryHeader({
isFilterDrawerOpen,
}) {
// Validation schema.
const validationSchema = Yup.object().shape({
asDate: Yup.date().required().label('asDate'),
agingDaysBefore: Yup.number()
.required()
.integer()
.positive()
.label('agingDaysBefore'),
agingPeriods: Yup.number()
.required()
.integer()
.positive()
.label('agingPeriods'),
});
const validationSchema = getARAgingSummaryQuerySchema();
// Initial values.
const defaultValues = {
asDate: moment().toDate(),
agingDaysBefore: 30,
agingPeriods: 3,
customersIds: [],
branchesIds: [],
filterByOption: 'without-zero-balance',
};
const defaultValues = getDefaultARAgingSummaryQuery();
// Initial values.
const initialValues = transformToForm(
{
...defaultValues,
...pageFilter,
asDate: moment(pageFilter.asDate).toDate(),
},
@@ -80,7 +66,6 @@ function ARAgingSummaryHeader({
};
// Detarmines the feature whether is enabled.
const { featureCan } = useFeatureCan();
const isBranchesFeatureCan = featureCan(Features.Branches);
return (

View File

@@ -2,22 +2,16 @@
import React from 'react';
import { FastField, Field } from 'formik';
import { DateInput } from '@blueprintjs/datetime';
import {
Intent,
FormGroup,
InputGroup,
Position,
Classes,
} from '@blueprintjs/core';
import classNames from 'classnames';
import { Intent, FormGroup, InputGroup, Position } from '@blueprintjs/core';
import FinancialStatementsFilter from '../FinancialStatementsFilter';
import {
FormattedMessage as T,
ContactsMultiSelect,
Row,
Col,
FieldHint,
FInputGroup,
FFormGroup,
CustomersMultiSelect,
} from '@/components';
import { momentFormatter } from '@/utils';
import { useARAgingSummaryGeneralContext } from './ARAgingSummaryGeneralProvider';
@@ -81,22 +75,13 @@ export default function ARAgingSummaryHeaderGeneralContent() {
<Row>
<Col xs={5}>
<FastField name={'agingPeriods'}>
{({ field, meta: { error, touched } }) => (
<FormGroup
label={<T id={'aging_periods'} />}
labelInfo={<FieldHint />}
className={'form-group--aging-periods'}
intent={error && Intent.DANGER}
>
<InputGroup
medium={true}
intent={error && Intent.DANGER}
{...field}
/>
</FormGroup>
)}
</FastField>
<FFormGroup
name={'agingPeriods'}
label={<T id={'aging_periods'} />}
labelInfo={<FieldHint />}
>
<FInputGroup name={'agingPeriods'} medium={true} />
</FFormGroup>
</Col>
</Row>
@@ -111,24 +96,12 @@ export default function ARAgingSummaryHeaderGeneralContent() {
<Row>
<Col xs={5}>
<Field name="customersIds">
{({ form: { setFieldValue }, field: { value } }) => (
<FormGroup
label={<T id={'specific_customers'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ContactsMultiSelect
items={customers}
onItemSelect={(customers) => {
const customersIds = customers.map(
(customer) => customer.id,
);
setFieldValue('customersIds', customersIds);
}}
/>
</FormGroup>
)}
</Field>
<FFormGroup
name="customersIds"
label={<T id={'specific_customers'} />}
>
<CustomersMultiSelect name="customersIds" items={customers} />
</FFormGroup>
</Col>
</Row>
</div>

View File

@@ -1,6 +1,10 @@
// @ts-nocheck
import moment from 'moment';
import { transformToCamelCase, flatObject } from '@/utils';
import * as Yup from 'yup';
import { transformToCamelCase, flatObject, transformToForm } from '@/utils';
import { useAppQueryString } from '@/hooks';
import { useMemo } from 'react';
import { castArray } from 'lodash';
export const transfromFilterFormToQuery = (form) => {
return flatObject(transformToCamelCase(form));
@@ -14,8 +18,57 @@ export const getDefaultARAgingSummaryQuery = () => {
asDate: moment().endOf('day').format('YYYY-MM-DD'),
agingDaysBefore: 30,
agingPeriods: 3,
customersIds: [],
filterByOption: 'without-zero-balance',
customersIds: [],
branchesIds: [],
};
};
/**
* Retrieves the AR aging summary query schema.
* @returns {Yup}
*/
export const getARAgingSummaryQuerySchema = () => {
return Yup.object().shape({
asDate: Yup.date().required().label('asDate'),
agingDaysBefore: Yup.number()
.required()
.integer()
.positive()
.label('agingDaysBefore'),
agingPeriods: Yup.number()
.required()
.integer()
.positive()
.label('agingPeriods'),
});
};
/**
* Parses the AR aging summary state.
*/
const parseARAgingSummaryQuery = (locationQuery) => {
const defaultQuery = getDefaultARAgingSummaryQuery();
const transformed = {
...defaultQuery,
...transformToForm(locationQuery, defaultQuery),
};
return {
...transformed,
branchesIds: castArray(transformed.branchesIds),
customersIds: castArray(transformed.customersIds),
};
};
/**
* AR aging summary query state.
*/
export const useARAgingSummaryQuery = () => {
const [locationQuery, setLocationQuery] = useAppQueryString();
const query = useMemo(
() => parseARAgingSummaryQuery(locationQuery),
[locationQuery],
);
return { query, locationQuery, setLocationQuery };
};

View File

@@ -68,7 +68,6 @@ function BalanceSheetHeader({
};
// Detarmines the given feature whether is enabled.
const { featureCan } = useFeatureCan();
const isBranchesFeatureCan = featureCan(Features.Branches);
return (

View File

@@ -1,5 +1,5 @@
// @ts-nocheck
import React, { useEffect, useState } from 'react';
import React, { useEffect } from 'react';
import moment from 'moment';
import * as R from 'ramda';
@@ -10,11 +10,10 @@ import CustomersBalanceSummaryHeader from './CustomersBalanceSummaryHeader';
import { CustomerBalanceSummaryBody } from './CustomerBalanceSummaryBody';
import { CustomersBalanceSummaryProvider } from './CustomersBalanceSummaryProvider';
import { getDefaultCustomersBalanceQuery } from './utils';
import { useCustomerBalanceSummaryQuery } from './utils';
import { CustomersBalanceLoadingBar } from './components';
import withCustomersBalanceSummaryActions from './withCustomersBalanceSummaryActions';
/**
* Customers Balance summary.
*/
@@ -22,36 +21,33 @@ function CustomersBalanceSummary({
// #withCustomersBalanceSummaryActions
toggleCustomerBalanceFilterDrawer,
}) {
const [filter, setFilter] = useState({
...getDefaultCustomersBalanceQuery(),
});
const { query, setLocationQuery } = useCustomerBalanceSummaryQuery();
// Handle re-fetch customers balance summary after filter change.
const handleFilterSubmit = (filter) => {
const _filter = {
...filter,
asDate: moment(filter.asDate).format('YYYY-MM-DD'),
};
setFilter({ ..._filter });
setLocationQuery({ ..._filter });
};
// Handle number format.
const handleNumberFormat = (values) => {
setFilter({
setLocationQuery({
...filter,
numberFormat: values,
});
};
useEffect(
() => () => {
toggleCustomerBalanceFilterDrawer(false);
},
() => () => toggleCustomerBalanceFilterDrawer(false),
[toggleCustomerBalanceFilterDrawer],
);
return (
<CustomersBalanceSummaryProvider filter={filter}>
<CustomersBalanceSummaryProvider filter={query}>
<CustomersBalanceSummaryActionsBar
numberFormat={filter?.numberFormat}
numberFormat={query?.numberFormat}
onNumberFormatSubmit={handleNumberFormat}
/>
<CustomersBalanceLoadingBar />
@@ -59,7 +55,7 @@ function CustomersBalanceSummary({
<DashboardPageContent>
<FinancialStatement>
<CustomersBalanceSummaryHeader
pageFilter={filter}
pageFilter={query}
onSubmitFilter={handleFilterSubmit}
/>
<CustomerBalanceSummaryBody />

View File

@@ -1,17 +1,16 @@
// @ts-nocheck
import React from 'react';
import { FastField, Field } from 'formik';
import { FastField } from 'formik';
import { DateInput } from '@blueprintjs/datetime';
import { Classes, FormGroup, Position, Checkbox } from '@blueprintjs/core';
import { FormGroup, Position, Checkbox } from '@blueprintjs/core';
import {
ContactsMultiSelect,
FormattedMessage as T,
Row,
Col,
FieldHint,
CustomersMultiSelect,
FFormGroup,
} from '@/components';
import classNames from 'classnames';
import {
momentFormatter,
tansformDateValue,
@@ -86,26 +85,12 @@ export default function CustomersBalanceSummaryGeneralPanelContent() {
<Row>
<Col xs={5}>
<Field name={'customersIds'}>
{({
form: { setFieldValue },
field: { value },
meta: { error, touched },
}) => (
<FormGroup
label={<T id={'specific_customers'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ContactsMultiSelect
items={customers}
onItemSelect={(contacts) => {
const customersIds = contacts.map((contact) => contact.id);
setFieldValue('customersIds', customersIds);
}}
/>
</FormGroup>
)}
</Field>
<FFormGroup
name={'customersIds'}
label={<T id={'specific_customers'} />}
>
<CustomersMultiSelect name={'customersIds'} items={customers} />
</FFormGroup>
</Col>
</Row>
</div>

View File

@@ -1,6 +1,6 @@
// @ts-nocheck
import React from 'react';
import * as Yup from 'yup';
import styled from 'styled-components';
import moment from 'moment';
import { Formik, Form } from 'formik';
@@ -13,6 +13,7 @@ import withCustomersBalanceSummaryActions from './withCustomersBalanceSummaryAct
import CustomersBalanceSummaryGeneralPanel from './CustomersBalanceSummaryGeneralPanel';
import { compose, transformToForm } from '@/utils';
import { getCustomersBalanceQuerySchema } from './utils';
/**
* Customers balance summary.
@@ -29,9 +30,8 @@ function CustomersBalanceSummaryHeader({
toggleCustomerBalanceFilterDrawer,
}) {
// validation schema.
const validationSchema = Yup.object().shape({
asDate: Yup.date().required().label('asDate'),
});
const validationSchema = getCustomersBalanceQuerySchema();
// Default form values.
const defaultValues = {
...pageFilter,

View File

@@ -1,9 +1,58 @@
// @ts-nocheck
import { useMemo } from 'react';
import { castArray } from 'lodash';
import moment from 'moment';
import * as Yup from 'yup';
import { useAppQueryString } from '@/hooks';
import { getDefaultARAgingSummaryQuery } from '../ARAgingSummary/common';
import { transformToForm } from '@/utils';
/**
* Default query of customers balance summary.
*/
export const getDefaultCustomersBalanceQuery = () => {
return {
asDate: moment().endOf('day').format('YYYY-MM-DD'),
filterByOption: 'with-transactions',
customersIds: [],
};
};
/**
* Retrieves the customers balance query schema.
* @returns {Yup}
*/
export const getCustomersBalanceQuerySchema = () => {
return Yup.object().shape({
asDate: Yup.date().required().label('asDate'),
});
};
/**
* Parses the customer balance summary query.
*/
const parseCustomersBalanceSummaryQuery = (locationQuery) => {
const defaultQuery = getDefaultARAgingSummaryQuery();
const transformed = {
...defaultQuery,
...transformToForm(locationQuery, defaultQuery),
};
return {
...transformed,
customersIds: castArray(transformed.customersIds),
};
};
/**
* Getter/setter query state of customers balance summary.
*/
export const useCustomerBalanceSummaryQuery = () => {
const [locationQuery, setLocationQuery] = useAppQueryString();
const query = useMemo(
() => parseCustomersBalanceSummaryQuery(locationQuery),
[locationQuery],
);
return { query, locationQuery, setLocationQuery };
};

View File

@@ -1,7 +1,5 @@
// @ts-nocheck
import React from 'react';
import * as Yup from 'yup';
import intl from 'react-intl-universal';
import moment from 'moment';
import styled from 'styled-components';
import { Tabs, Tab, Button, Intent } from '@blueprintjs/core';
@@ -15,6 +13,10 @@ import withCustomersTransactions from './withCustomersTransactions';
import withCustomersTransactionsActions from './withCustomersTransactionsActions';
import { compose, transformToForm } from '@/utils';
import {
getCustomersTransactionsDefaultQuery,
getCustomersTransactionsQuerySchema,
} from './_utils';
/**
* Customers transactions header.
@@ -31,12 +33,8 @@ function CustomersTransactionsHeader({
toggleCustomersTransactionsFilterDrawer: toggleFilterDrawer,
}) {
// Default form values.
const defaultValues = {
...pageFilter,
fromDate: moment().toDate(),
toDate: moment().toDate(),
customersIds: [],
};
const defaultValues = getCustomersTransactionsDefaultQuery();
// Initial form values.
const initialValues = transformToForm(
{
@@ -49,13 +47,7 @@ function CustomersTransactionsHeader({
);
// Validation schema.
const validationSchema = Yup.object().shape({
fromDate: Yup.date().required().label(intl.get('fromDate')),
toDate: Yup.date()
.min(Yup.ref('fromDate'))
.required()
.label(intl.get('toDate')),
});
const validationSchema = getCustomersTransactionsQuerySchema();
// Handle form submit.
const handleSubmit = (values, { setSubmitting }) => {

View File

@@ -1,15 +1,13 @@
// @ts-nocheck
import React from 'react';
import classNames from 'classnames';
import { Field } from 'formik';
import { Classes, FormGroup } from '@blueprintjs/core';
import FinancialStatementDateRange from '../FinancialStatementDateRange';
import FinancialStatementsFilter from '../FinancialStatementsFilter';
import {
Row,
Col,
ContactsMultiSelect,
FormattedMessage as T,
CustomersMultiSelect,
FFormGroup,
} from '@/components';
import { filterCustomersOptions } from '../constants';
@@ -51,24 +49,12 @@ function CustomersTransactionsHeaderGeneralPanelContent() {
<Row>
<Col xs={4}>
<Field name={'customersIds'}>
{({ form: { setFieldValue }, field: { value } }) => (
<FormGroup
label={<T id={'specific_customers'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ContactsMultiSelect
items={customers}
onItemSelect={(customers) => {
const customersIds = customers.map(
(customer) => customer.id,
);
setFieldValue('customersIds', customersIds);
}}
/>
</FormGroup>
)}
</Field>
<FFormGroup
label={<T id={'specific_customers'} />}
name={'customersIds'}
>
<CustomersMultiSelect name={'customersIds'} items={customers} />
</FFormGroup>
</Col>
</Row>
</div>

View File

@@ -0,0 +1,19 @@
import * as Yup from 'yup';
import intl from 'react-intl-universal';
import moment from 'moment';
export const getCustomersTransactionsQuerySchema = () => {
return Yup.object().shape({
fromDate: Yup.date().required().label(intl.get('fromDate')),
toDate: Yup.date()
.min(Yup.ref('fromDate'))
.required()
.label(intl.get('toDate')),
});
};
export const getCustomersTransactionsDefaultQuery = () => ({
fromDate: moment().toDate(),
toDate: moment().toDate(),
customersIds: [],
});

View File

@@ -1,5 +1,5 @@
// @ts-nocheck
import React, { useCallback } from 'react';
import React, { useCallback, useEffect } from 'react';
import moment from 'moment';
import GeneralLedgerHeader from './GeneralLedgerHeader';
@@ -41,10 +41,8 @@ function GeneralLedger({
);
// Hide the filter drawer once the page unmount.
React.useEffect(
() => () => {
toggleGeneralLedgerFilterDrawer(false);
},
useEffect(
() => () => toggleGeneralLedgerFilterDrawer(false),
[toggleGeneralLedgerFilterDrawer],
);

View File

@@ -2,12 +2,14 @@
import React from 'react';
import moment from 'moment';
import styled from 'styled-components';
import * as Yup from 'yup';
import { Formik, Form } from 'formik';
import { Tabs, Tab, Button, Intent } from '@blueprintjs/core';
import { FormattedMessage as T } from '@/components';
import { getDefaultGeneralLedgerQuery } from './common';
import {
getDefaultGeneralLedgerQuery,
getGeneralLedgerQuerySchema,
} from './common';
import { compose, transformToForm, saveInvoke } from '@/utils';
import FinancialStatementHeader from '../FinancialStatementHeader';
@@ -39,6 +41,7 @@ function GeneralLedgerHeader({
// Initial values.
const initialValues = transformToForm(
{
...defaultValues,
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
@@ -46,11 +49,8 @@ function GeneralLedgerHeader({
defaultValues,
);
// Validation schema.
const validationSchema = Yup.object().shape({
dateRange: Yup.string().optional(),
fromDate: Yup.date().required(),
toDate: Yup.date().min(Yup.ref('fromDate')).required(),
});
const validationSchema = getGeneralLedgerQuerySchema();
// Handle form submit.
const handleSubmit = (values, { setSubmitting }) => {
saveInvoke(onSubmitFilter, values);
@@ -68,6 +68,7 @@ function GeneralLedgerHeader({
// Detarmines the feature whether is enabled.
const { featureCan } = useFeatureCan();
// Detarmine if the feature is enabled.
const isBranchesFeatureCan = featureCan(Features.Branches);
return (

View File

@@ -2,6 +2,7 @@
import React from 'react';
import intl from 'react-intl-universal';
import moment from 'moment';
import * as Yup from 'yup';
import { castArray } from 'lodash';
import { useAppQueryString } from '@/hooks';
@@ -26,15 +27,25 @@ export const filterAccountsOptions = [
/**
* Retrieves the default general ledger query.
*/
export const getDefaultGeneralLedgerQuery = () => {
return {
fromDate: moment().startOf('year').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'),
basis: 'accrual',
filterByOption: 'with-transactions',
branchesIds: [],
accountsIds: [],
};
export const getDefaultGeneralLedgerQuery = () => ({
fromDate: moment().startOf('year').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'),
basis: 'accrual',
filterByOption: 'with-transactions',
branchesIds: [],
accountsIds: [],
});
/**
* Retrieves the validation schema of general ledger.
* @returns {Yup}
*/
export const getGeneralLedgerQuerySchema = () => {
return Yup.object().shape({
dateRange: Yup.string().optional(),
fromDate: Yup.date().required(),
toDate: Yup.date().min(Yup.ref('fromDate')).required(),
});
};
/**

View File

@@ -1,10 +1,9 @@
// @ts-nocheck
import React from 'react';
import * as Yup from 'yup';
import moment from 'moment';
import { Formik, Form } from 'formik';
import { Tabs, Tab, Button, Intent } from '@blueprintjs/core';
import intl from 'react-intl-universal';
import styled from 'styled-components';
import { FormattedMessage as T } from '@/components';
@@ -16,7 +15,10 @@ import InventoryItemDetailsHeaderDimensionsPanel from './InventoryItemDetailsHea
import withInventoryItemDetails from './withInventoryItemDetails';
import withInventoryItemDetailsActions from './withInventoryItemDetailsActions';
import { getInventoryItemDetailsDefaultQuery } from './utils2';
import {
getInventoryItemDetailsDefaultQuery,
getInventoryItemDetailsQuerySchema,
} from './utils2';
import { compose, transformToForm } from '@/utils';
import { useFeatureCan } from '@/hooks/state';
import { Features } from '@/constants';
@@ -28,6 +30,7 @@ function InventoryItemDetailsHeader({
// #ownProps
onSubmitFilter,
pageFilter,
// #withInventoryItemDetails
isFilterDrawerOpen,
@@ -40,30 +43,29 @@ function InventoryItemDetailsHeader({
// Filter form initial values.
const initialValues = transformToForm(
{
...defaultValues,
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
},
defaultValues,
);
// Validation schema.
const validationSchema = Yup.object().shape({
fromDate: Yup.date().required().label(intl.get('fromDate')),
toDate: Yup.date()
.min(Yup.ref('fromDate'))
.required()
.label(intl.get('toDate')),
});
const validationSchema = getInventoryItemDetailsQuerySchema();
// Handle form submit.
const handleSubmit = (values, { setSubmitting }) => {
onSubmitFilter(values);
toggleFilterDrawer(false);
setSubmitting(false);
};
// Handle drawer close action.
const handleDrawerClose = () => {
toggleFilterDrawer(false);
};
// Detarmines the given feature whether is enabled.
const { featureCan } = useFeatureCan();

View File

@@ -1,14 +1,12 @@
// @ts-nocheck
import React from 'react';
import { FormGroup, Classes } from '@blueprintjs/core';
import { Field } from 'formik';
import {
ItemsMultiSelect,
Row,
Col,
FormattedMessage as T,
FFormGroup,
} from '@/components';
import classNames from 'classnames';
import FinancialStatementDateRange from '../FinancialStatementDateRange';
import {
@@ -39,26 +37,9 @@ function InventoryItemDetailsHeaderGeneralPanelContent() {
<Row>
<Col xs={4}>
<Field name={'itemsIds'}>
{({
form: { setFieldValue },
field: { value },
meta: { error, touched },
}) => (
<FormGroup
label={<T id={'Specific items'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ItemsMultiSelect
items={items}
onItemSelect={(items) => {
const itemsIds = items.map((item) => item.id);
setFieldValue('itemsIds', itemsIds);
}}
/>
</FormGroup>
)}
</Field>
<FFormGroup label={<T id={'Specific items'} />} name={'itemsIds'}>
<ItemsMultiSelect name={'itemsIds'} items={items} />
</FFormGroup>
</Col>
</Row>
</div>

View File

@@ -2,6 +2,8 @@
import React from 'react';
import moment from 'moment';
import { castArray } from 'lodash';
import * as Yup from 'yup';
import intl from 'react-intl-universal';
import { useAppQueryString } from '@/hooks';
import { transformToForm } from '@/utils';
@@ -9,13 +11,26 @@ import { transformToForm } from '@/utils';
/**
* Retrieves inventory item details default query.
*/
export const getInventoryItemDetailsDefaultQuery = () => {
return {
fromDate: moment().startOf('year').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'),
warehousesIds: [],
branchesIds: [],
};
export const getInventoryItemDetailsDefaultQuery = () => ({
fromDate: moment().startOf('year').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'),
itemsIds: [],
warehousesIds: [],
branchesIds: [],
});
/**
* Retrieves inventory item details query schema.
* @returns {Yup}
*/
export const getInventoryItemDetailsQuerySchema = () => {
return Yup.object().shape({
fromDate: Yup.date().required().label(intl.get('fromDate')),
toDate: Yup.date()
.min(Yup.ref('fromDate'))
.required()
.label(intl.get('toDate')),
});
};
/**
@@ -32,7 +47,8 @@ const parseInventoryItemDetailsQuery = (locationQuery) => {
return {
...transformed,
// Ensures the branches/warehouses ids is always array.
// Ensure the branches, warehouses and items ids is always array.
itemsIds: castArray(transformed.itemsIds),
branchesIds: castArray(transformed.branchesIds),
warehousesIds: castArray(transformed.warehousesIds),
};

View File

@@ -1,6 +1,5 @@
// @ts-nocheck
import React from 'react';
import * as Yup from 'yup';
import moment from 'moment';
import styled from 'styled-components';
import { Formik, Form } from 'formik';
@@ -17,6 +16,10 @@ import withInventoryValuationActions from './withInventoryValuationActions';
import { compose, transformToForm } from '@/utils';
import { useFeatureCan } from '@/hooks/state';
import { Features } from '@/constants';
import {
getInventoryValuationQuery,
getInventoryValuationQuerySchema,
} from './utils';
/**
* inventory valuation header.
@@ -33,25 +36,17 @@ function InventoryValuationHeader({
toggleInventoryValuationFilterDrawer,
}) {
// Form validation schema.
const validationSchema = Yup.object().shape({
asDate: Yup.date().required().label('asDate'),
});
const validationSchema = getInventoryValuationQuerySchema();
const defaultQuery = getInventoryValuationQuery();
// Default values.
const defaultValues = {
...pageFilter,
asDate: moment().toDate(),
itemsIds: [],
warehousesIds: [],
};
// Initial values.
const initialValues = transformToForm(
{
...defaultValues,
...defaultQuery,
...pageFilter,
asDate: moment(pageFilter.asDate).toDate(),
},
defaultValues,
defaultQuery,
);
// Handle the form of header submit.
@@ -71,6 +66,7 @@ function InventoryValuationHeader({
// Detarmines the given feature whether is enabled.
const { featureCan } = useFeatureCan();
// Detarmine if these feature are enabled.
const isBranchesFeatureCan = featureCan(Features.Branches);
const isWarehousesFeatureCan = featureCan(Features.Warehouses);

View File

@@ -2,8 +2,7 @@
import React from 'react';
import { FastField, Field } from 'formik';
import { DateInput } from '@blueprintjs/datetime';
import { FormGroup, Position, Classes } from '@blueprintjs/core';
import classNames from 'classnames';
import { FormGroup, Position } from '@blueprintjs/core';
import {
FormattedMessage as T,
@@ -11,9 +10,9 @@ import {
Row,
Col,
FieldHint,
FFormGroup,
} from '@/components';
import { filterInventoryValuationOptions } from '../constants';
import {
momentFormatter,
tansformDateValue,
@@ -83,22 +82,9 @@ function InventoryValuationHeaderGeneralPanelContent() {
<Row>
<Col xs={4}>
<Field name={'itemsIds'}>
{({ form: { setFieldValue } }) => (
<FormGroup
label={<T id={'Specific items'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ItemsMultiSelect
items={items}
onItemSelect={(items) => {
const itemsIds = items.map((item) => item.id);
setFieldValue('itemsIds', itemsIds);
}}
/>
</FormGroup>
)}
</Field>
<FFormGroup name={'itemsIds'} label={<T id={'Specific items'} />}>
<ItemsMultiSelect name={'itemsIds'} items={items} />
</FFormGroup>
</Col>
</Row>
</div>

View File

@@ -2,25 +2,33 @@
import React from 'react';
import moment from 'moment';
import { castArray } from 'lodash';
import * as Yup from 'yup';
import { useAppQueryString } from '@/hooks';
import { transformToForm } from '@/utils';
/**
* Retrieves the inventory valuation sheet default query.
* Retrieves the validation schema of inventory valuation query.
*/
export const getInventoryValuationQuery = () => {
return {
asDate: moment().endOf('day').format('YYYY-MM-DD'),
filterByOption: 'with-transactions',
branchesIds: [],
warehousesIds: [],
};
export const getInventoryValuationQuerySchema = () => {
return Yup.object().shape({
asDate: Yup.date().required().label('asDate'),
});
};
/**
* Parses inventory valiation location query to report query.
* Retrieves the inventory valuation sheet default query.
*/
export const getInventoryValuationQuery = () => ({
asDate: moment().endOf('day').format('YYYY-MM-DD'),
filterByOption: 'with-transactions',
itemsIds: [],
branchesIds: [],
warehousesIds: [],
});
/**
* Parses inventory valuation location query to report query.
*/
const parseInventoryValuationQuery = (locationQuery) => {
const defaultQuery = getInventoryValuationQuery();
@@ -33,6 +41,7 @@ const parseInventoryValuationQuery = (locationQuery) => {
...transformed,
// Ensures the branches/warehouses ids is always array.
itemsIds: castArray(transformed.itemsIds),
branchesIds: castArray(transformed.branchesIds),
warehousesIds: castArray(transformed.warehousesIds),
};

View File

@@ -1,5 +1,5 @@
// @ts-nocheck
import React, { useEffect, useState, useCallback } from 'react';
import React, { useEffect, useCallback } from 'react';
import moment from 'moment';
import PurchasesByItemsActionsBar from './PurchasesByItemsActionsBar';
@@ -9,7 +9,7 @@ import { FinancialStatement, DashboardPageContent } from '@/components';
import { PurchasesByItemsLoadingBar } from './components';
import { PurchasesByItemsProvider } from './PurchasesByItemsProvider';
import { PurchasesByItemsBody } from './PurchasesByItemsBody';
import { getDefaultPurchasesByItemsQuery } from './utils';
import { usePurchasesByItemsQuery } from './utils';
import { compose } from '@/utils';
import withPurchasesByItemsActions from './withPurchasesByItemsActions';
@@ -21,9 +21,7 @@ function PurchasesByItems({
// #withPurchasesByItemsActions
togglePurchasesByItemsFilterDrawer,
}) {
const [filter, setFilter] = useState({
...getDefaultPurchasesByItemsQuery(),
});
const { query, setLocationQuery } = usePurchasesByItemsQuery();
// Handle filter form submit.
const handleFilterSubmit = useCallback(
@@ -33,11 +31,10 @@ function PurchasesByItems({
fromDate: moment(filter.fromDate).format('YYYY-MM-DD'),
toDate: moment(filter.toDate).format('YYYY-MM-DD'),
};
setFilter(parsedFilter);
setLocationQuery(parsedFilter);
},
[setFilter],
[setLocationQuery],
);
// Handle number format form submit.
const handleNumberFormatSubmit = (numberFormat) => {
setFilter({
@@ -45,7 +42,6 @@ function PurchasesByItems({
numberFormat,
});
};
// Hide the filter drawer once the page unmount.
useEffect(
() => () => {
@@ -55,9 +51,9 @@ function PurchasesByItems({
);
return (
<PurchasesByItemsProvider query={filter}>
<PurchasesByItemsProvider query={query}>
<PurchasesByItemsActionsBar
numberFormat={filter.numberFormat}
numberFormat={query.numberFormat}
onNumberFormatSubmit={handleNumberFormatSubmit}
/>
<PurchasesByItemsLoadingBar />
@@ -65,7 +61,7 @@ function PurchasesByItems({
<DashboardPageContent>
<FinancialStatement>
<PurchasesByItemsHeader
pageFilter={filter}
pageFilter={query}
onSubmitFilter={handleFilterSubmit}
/>
<PurchasesByItemsBody />

View File

@@ -1,14 +1,12 @@
// @ts-nocheck
import React from 'react';
import { FormGroup, Classes } from '@blueprintjs/core';
import { Field } from 'formik';
import {
Row,
Col,
FormattedMessage as T,
ItemsMultiSelect,
FFormGroup,
} from '@/components';
import classNames from 'classnames';
import FinancialStatementDateRange from '../FinancialStatementDateRange';
import FinancialStatementsFilter from '../FinancialStatementsFilter';
import { filterItemsOptions } from '../constants';
@@ -51,22 +49,9 @@ function PurchasesByItemsGeneralPanelContent() {
<Row>
<Col xs={4}>
<Field name={'itemsIds'}>
{({ form: { setFieldValue } }) => (
<FormGroup
label={<T id={'Specific items'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ItemsMultiSelect
items={items}
onItemSelect={(items) => {
const itemsIds = items.map((item) => item.id);
setFieldValue('itemsIds', itemsIds);
}}
/>
</FormGroup>
)}
</Field>
<FFormGroup name={'itemsIds'} label={<T id={'Specific items'} />}>
<ItemsMultiSelect name={'itemsIds'} items={items} />
</FFormGroup>
</Col>
</Row>
</div>

View File

@@ -1,14 +1,11 @@
// @ts-nocheck
import React from 'react';
import * as Yup from 'yup';
import moment from 'moment';
import intl from 'react-intl-universal';
import styled from 'styled-components';
import styled from 'styled-components';
import { Formik, Form } from 'formik';
import { Tabs, Tab, Button, Intent } from '@blueprintjs/core';
import { FormattedMessage as T } from '@/components';
import FinancialStatementHeader from '@/containers/FinancialStatements/FinancialStatementHeader';
import PurchasesByItemsGeneralPanel from './PurchasesByItemsGeneralPanel';
@@ -16,6 +13,10 @@ import withPurchasesByItems from './withPurchasesByItems';
import withPurchasesByItemsActions from './withPurchasesByItemsActions';
import { compose, transformToForm } from '@/utils';
import {
getDefaultPurchasesByItemsQuery,
getPurchasesByItemsQuerySchema,
} from './utils';
/**
* Purchases by items header.
@@ -32,38 +33,26 @@ function PurchasesByItemsHeader({
togglePurchasesByItemsFilterDrawer,
}) {
// Form validation schema.
const validationSchema = Yup.object().shape({
fromDate: Yup.date().required().label(intl.get('from_date')),
toDate: Yup.date()
.min(Yup.ref('fromDate'))
.required()
.label(intl.get('to_date')),
});
// Default form values.
const defaultValues = {
...pageFilter,
fromDate: moment().toDate(),
toDate: moment().toDate(),
itemsIds: [],
};
const validationSchema = getPurchasesByItemsQuerySchema();
const defaultQuery = getDefaultPurchasesByItemsQuery();
// Initial form values.
const initialValues = transformToForm(
{
...defaultValues,
...defaultQuery,
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
},
defaultValues,
defaultQuery,
);
// Handle form submit.
const handleSubmit = (values, { setSubmitting }) => {
onSubmitFilter(values);
setSubmitting(false);
togglePurchasesByItemsFilterDrawer(false);
};
// Handle drawer close & cancel action.
const handleDrawerClose = () => {
togglePurchasesByItemsFilterDrawer(false);

View File

@@ -1,11 +1,62 @@
// @ts-nocheck
import React from 'react';
import moment from 'moment';
import * as Yup from 'yup';
import intl from 'react-intl-universal';
import { useAppQueryString } from '@/hooks';
import { transformToForm } from '@/utils';
import { castArray } from 'lodash';
/**
* Retrieves the purchases by items query.
*/
export const getDefaultPurchasesByItemsQuery = () => ({
fromDate: moment().startOf('year').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'),
filterByOption: 'with-transactions',
itemsIds: [],
});
export const getDefaultPurchasesByItemsQuery = () => {
/**
* Retrieves the purchases by items query validation schema.
* @returns {Yup}
*/
export const getPurchasesByItemsQuerySchema = () => {
return Yup.object().shape({
fromDate: Yup.date().required().label(intl.get('from_date')),
toDate: Yup.date()
.min(Yup.ref('fromDate'))
.required()
.label(intl.get('to_date')),
});
};
/**
* Parses the purchases by items query.
*/
const parsePurchasesByItemsQuery = (locationQuery) => {
const defaultQuery = getDefaultPurchasesByItemsQuery();
const transformed = {
...defaultQuery,
...transformToForm(locationQuery, defaultQuery),
};
return {
fromDate: moment().startOf('year').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'),
filterByOption: 'with-transactions',
}
}
...transformed,
itemsIds: castArray(transformed.itemsIds),
};
};
/**
* Purchases by items query state.
*/
export const usePurchasesByItemsQuery = () => {
// Retrieves location query.
const [locationQuery, setLocationQuery] = useAppQueryString();
const query = React.useMemo(
() => parsePurchasesByItemsQuery(locationQuery),
[locationQuery],
);
return { query, locationQuery, setLocationQuery };
};

View File

@@ -1,5 +1,5 @@
// @ts-nocheck
import React, { useEffect, useState, useCallback } from 'react';
import React, { useEffect, useCallback } from 'react';
import moment from 'moment';
import { SalesByItemsBody } from './SalesByItemsBody';
@@ -11,7 +11,7 @@ import SalesByItemsHeader from './SalesByItemsHeader';
import withSalesByItemsActions from './withSalesByItemsActions';
import { getDefaultSalesByItemsQuery } from './utils';
import { useSalesByItemsQuery } from './utils';
import { compose } from '@/utils';
/**
@@ -21,9 +21,7 @@ function SalesByItems({
// #withSellsByItemsActions
toggleSalesByItemsFilterDrawer,
}) {
const [filter, setFilter] = useState({
...getDefaultSalesByItemsQuery(),
});
const { query, setLocationQuery } = useSalesByItemsQuery();
// Handle filter form submit.
const handleFilterSubmit = useCallback(
@@ -33,30 +31,28 @@ function SalesByItems({
fromDate: moment(filter.fromDate).format('YYYY-MM-DD'),
toDate: moment(filter.toDate).format('YYYY-MM-DD'),
};
setFilter(parsedFilter);
setLocationQuery(parsedFilter);
},
[setFilter],
[setLocationQuery],
);
// Handle number format form submit.
const handleNumberFormatSubmit = (numberFormat) => {
setFilter({
setLocationQuery({
...filter,
numberFormat,
});
};
// Hide the filter drawer once the page unmount.
useEffect(
() => () => {
toggleSalesByItemsFilterDrawer(false);
},
() => () => toggleSalesByItemsFilterDrawer(false),
[toggleSalesByItemsFilterDrawer],
);
return (
<SalesByItemProvider query={filter}>
<SalesByItemProvider query={query}>
<SalesByItemsActionsBar
numberFormat={filter.numberFormat}
numberFormat={query.numberFormat}
onNumberFormatSubmit={handleNumberFormatSubmit}
/>
<SalesByItemsLoadingBar />
@@ -64,7 +60,7 @@ function SalesByItems({
<DashboardPageContent>
<FinancialStatement>
<SalesByItemsHeader
pageFilter={filter}
pageFilter={query}
onSubmitFilter={handleFilterSubmit}
/>
<SalesByItemsBody />

View File

@@ -1,8 +1,6 @@
// @ts-nocheck
import React from 'react';
import * as Yup from 'yup';
import moment from 'moment';
import intl from 'react-intl-universal';
import styled from 'styled-components';
import { Formik, Form } from 'formik';
import { Tabs, Tab, Button, Intent } from '@blueprintjs/core';
@@ -14,7 +12,11 @@ import SalesByItemsHeaderGeneralPanel from './SalesByItemsHeaderGeneralPanel';
import withSalesByItems from './withSalesByItems';
import withSalesByItemsActions from './withSalesByItemsActions';
import { compose } from '@/utils';
import { compose, transformToForm } from '@/utils';
import {
getDefaultSalesByItemsQuery,
getSalesByItemsQueryShema,
} from './utils';
/**
* Sales by items header.
@@ -31,21 +33,22 @@ function SalesByItemsHeader({
toggleSalesByItemsFilterDrawer,
}) {
// Form validation schema.
const validationSchema = Yup.object().shape({
fromDate: Yup.date().required().label(intl.get('from_date')),
toDate: Yup.date()
.min(Yup.ref('fromDate'))
.required()
.label(intl.get('to_date')),
});
const validationSchema = getSalesByItemsQueryShema();
const defaultQuery = getDefaultSalesByItemsQuery();
// Initial values.
const initialValues = {
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
};
const initialValues = transformToForm(
{
...defaultQuery,
...pageFilter,
fromDate: moment(pageFilter.fromDate).toDate(),
toDate: moment(pageFilter.toDate).toDate(),
},
defaultQuery,
);
// Handle the form submitting.
const handleSubmit = (values, { setSubmitting }) => {
onSubmitFilter(values);
setSubmitting(false);

View File

@@ -1,13 +1,15 @@
// @ts-nocheck
import React from 'react';
import { FormGroup, Classes } from '@blueprintjs/core';
import { Field } from 'formik';
import classNames from 'classnames';
import { filterItemsOptions } from '../constants';
import { Row, Col, ItemsMultiSelect, FormattedMessage as T } from '@/components';
import {
Row,
Col,
ItemsMultiSelect,
FormattedMessage as T,
FFormGroup,
} from '@/components';
import FinancialStatementDateRange from '../FinancialStatementDateRange';
import FinancialStatementsFilter from '../FinancialStatementsFilter';
import { filterItemsOptions } from '../constants';
import {
SalesByItemGeneralPanelProvider,
useSalesByItemsGeneralPanelContext,
@@ -46,22 +48,9 @@ function SalesByItemsHeaderGeneralPanelContent() {
<Row>
<Col xs={4}>
<Field name={'itemsIds'}>
{({ form: { setFieldValue }, field: { value } }) => (
<FormGroup
label={<T id={'Specific items'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ItemsMultiSelect
items={items}
onItemSelect={(items) => {
const itemsIds = items.map((item) => item.id);
setFieldValue('itemsIds', itemsIds);
}}
/>
</FormGroup>
)}
</Field>
<FFormGroup label={<T id={'Specific items'} />} name={'itemsIds'}>
<ItemsMultiSelect name={'itemsIds'} items={items} />
</FFormGroup>
</Col>
</Row>
</div>

View File

@@ -1,10 +1,63 @@
// @ts-nocheck
import React from 'react';
import moment from 'moment';
import * as Yup from 'yup';
import intl from 'react-intl-universal';
import { castArray } from 'lodash';
import { useAppQueryString } from '@/hooks';
import { transformToForm } from '@/utils';
export const getDefaultSalesByItemsQuery = () => {
/**
* Retrieves the validation schema.
* @returns {Yup}
*/
export const getSalesByItemsQueryShema = () => {
return Yup.object().shape({
fromDate: Yup.date().required().label(intl.get('from_date')),
toDate: Yup.date()
.min(Yup.ref('fromDate'))
.required()
.label(intl.get('to_date')),
});
};
/**
* Retrieves the default query.
*/
export const getDefaultSalesByItemsQuery = () => ({
fromDate: moment().startOf('year').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'),
filterByOption: 'with-transactions',
itemsIds: [],
});
/**
* Parses sales by items query of browser location.
*/
const parseSalesByItemsQuery = (locationQuery) => {
const defaultQuery = getDefaultSalesByItemsQuery();
const transformed = {
...defaultQuery,
...transformToForm(locationQuery, defaultQuery),
};
return {
fromDate: moment().startOf('year').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'),
filterByOption: 'with-transactions',
...transformed,
itemsIds: castArray(transformed.itemsIds),
};
};
/**
* Sales by items query state.
*/
export const useSalesByItemsQuery = () => {
// Retrieves location query.
const [locationQuery, setLocationQuery] = useAppQueryString();
// Merges the default filter query with location URL query.
const query = React.useMemo(
() => parseSalesByItemsQuery(locationQuery),
[locationQuery],
);
return { query, locationQuery, setLocationQuery };
};

View File

@@ -13,7 +13,7 @@ import { VendorBalanceSummaryBody } from './VendorsBalanceSummaryBody';
import withVendorsBalanceSummaryActions from './withVendorsBalanceSummaryActions';
import { getDefaultVendorsBalanceQuery } from './utils';
import { useVendorsBalanceSummaryQuery } from './utils';
import { compose } from '@/utils';
/**
@@ -23,9 +23,7 @@ function VendorsBalanceSummary({
// #withVendorsBalanceSummaryActions
toggleVendorSummaryFilterDrawer,
}) {
const [filter, setFilter] = useState({
...getDefaultVendorsBalanceQuery(),
});
const { query, setLocationQuery } = useVendorsBalanceSummaryQuery();
// Handle refetch vendors balance summary.
const handleFilterSubmit = (filter) => {
@@ -33,28 +31,26 @@ function VendorsBalanceSummary({
...filter,
asDate: moment(filter.asDate).format('YYYY-MM-DD'),
};
setFilter(_filter);
setLocationQuery(_filter);
};
// Handle number format submit.
const handleNumberFormatSubmit = (format) => {
setFilter({
setLocationQuery({
...filter,
numberFormat: format,
});
};
useEffect(
() => () => {
toggleVendorSummaryFilterDrawer(false);
},
() => () => toggleVendorSummaryFilterDrawer(false),
[toggleVendorSummaryFilterDrawer],
);
return (
<VendorsBalanceSummaryProvider filter={filter}>
<VendorsBalanceSummaryProvider filter={query}>
<VendorsBalanceSummaryActionsBar
numberFormat={filter?.numberFormat}
numberFormat={query?.numberFormat}
onNumberFormatSubmit={handleNumberFormatSubmit}
/>
<VendorsSummarySheetLoadingBar />
@@ -62,7 +58,7 @@ function VendorsBalanceSummary({
<DashboardPageContent>
<FinancialStatement>
<VendorsBalanceSummaryHeader
pageFilter={filter}
pageFilter={query}
onSubmitFilter={handleFilterSubmit}
/>
<VendorBalanceSummaryBody />

View File

@@ -1,6 +1,6 @@
// @ts-nocheck
import React from 'react';
import * as Yup from 'yup';
import moment from 'moment';
import styled from 'styled-components';
import { Formik, Form } from 'formik';
@@ -13,6 +13,7 @@ import FinancialStatementHeader from '../FinancialStatementHeader';
import VendorsBalanceSummaryHeaderGeneral from './VendorsBalanceSummaryHeaderGeneral';
import withVendorsBalanceSummary from './withVendorsBalanceSummary';
import withVendorsBalanceSummaryActions from './withVendorsBalanceSummaryActions';
import { getVendorsBalanceQuerySchema } from './utils';
/**
* Vendors balance summary drawer header.
@@ -28,10 +29,8 @@ function VendorsBalanceSummaryHeader({
//#withVendorsBalanceSummaryActions
toggleVendorSummaryFilterDrawer,
}) {
// validation schema.
const validationSchema = Yup.object().shape({
asDate: Yup.date().required().label('asDate'),
});
// Validation schema.
const validationSchema = getVendorsBalanceQuerySchema();
// filter form initial values.
const defaultValues = {
@@ -80,6 +79,7 @@ function VendorsBalanceSummaryHeader({
panel={<VendorsBalanceSummaryHeaderGeneral />}
/>
</Tabs>
<div className={'financial-header-drawer__footer'}>
<Button className={'mr1'} intent={Intent.PRIMARY} type={'submit'}>
<T id={'calculate_report'} />

View File

@@ -1,19 +1,18 @@
// @ts-nocheck
import React from 'react';
import { Field, FastField } from 'formik';
import { FastField } from 'formik';
import { DateInput } from '@blueprintjs/datetime';
import classNames from 'classnames';
import { FormGroup, Position, Classes, Checkbox } from '@blueprintjs/core';
import { FormGroup, Position, Checkbox } from '@blueprintjs/core';
import {
ContactsMultiSelect,
Row,
Col,
FieldHint,
FormattedMessage as T,
FFormGroup,
VendorsMultiSelect,
} from '@/components';
import { filterVendorsOptions } from '../constants';
import {
momentFormatter,
tansformDateValue,
@@ -87,22 +86,9 @@ export default function VendorsBalanceSummaryHeaderGeneralContent() {
<Row>
<Col xs={5}>
<Field name={'vendorsIds'}>
{({ form: { setFieldValue } }) => (
<FormGroup
label={<T id={'specific_vendors'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ContactsMultiSelect
items={vendors}
onItemSelect={(contacts) => {
const vendorsIds = contacts.map((contact) => contact.id);
setFieldValue('vendorsIds', vendorsIds);
}}
/>
</FormGroup>
)}
</Field>
<FFormGroup label={<T id={'specific_vendors'} />} name={'vendorsIds'}>
<VendorsMultiSelect name={'vendorsIds'} items={vendors} />
</FFormGroup>
</Col>
</Row>
</div>

View File

@@ -1,9 +1,44 @@
// @ts-nocheck
import moment from 'moment';
import { useMemo } from 'react';
import * as Yup from 'yup';
import { castArray } from 'lodash';
import { useAppQueryString } from '@/hooks';
import { transformToForm } from '@/utils';
export const getDefaultVendorsBalanceQuery = () => {
return {
asDate: moment().endOf('day').format('YYYY-MM-DD'),
filterByOption: 'with-transactions',
vendorsIds: [],
};
}
};
export const getVendorsBalanceQuerySchema = () => {
return Yup.object().shape({
asDate: Yup.date().required().label('asDate'),
});
};
export const parseVendorsBalanceSummaryQuery = (locationQuery) => {
const defaultQuery = getDefaultVendorsBalanceQuery();
const transformed = {
...defaultQuery,
...transformToForm(locationQuery, defaultQuery),
};
return {
...transformed,
vendorsIds: castArray(transformed.vendorsIds),
};
};
export const useVendorsBalanceSummaryQuery = () => {
const [locationQuery, setLocationQuery] = useAppQueryString();
const query = useMemo(
() => parseVendorsBalanceSummaryQuery(locationQuery),
[locationQuery],
);
return { query, locationQuery, setLocationQuery };
};

View File

@@ -1,8 +1,7 @@
// @ts-nocheck
import React from 'react';
import * as Yup from 'yup';
import moment from 'moment';
import intl from 'react-intl-universal';
import { Formik, Form } from 'formik';
import { Tabs, Tab, Button, Intent } from '@blueprintjs/core';
import { FormattedMessage as T } from '@/components';
@@ -14,11 +13,14 @@ import withVendorsTransaction from './withVendorsTransaction';
import withVendorsTransactionsActions from './withVendorsTransactionsActions';
import { compose, transformToForm } from '@/utils';
import {
getVendorTransactionsQuerySchema,
getVendorsTransactionsDefaultQuery,
} from './_utils';
/**
* Vendors transactions header.
*/
function VendorsTransactionsHeader({
// #ownProps
onSubmitFilter,
@@ -31,12 +33,7 @@ function VendorsTransactionsHeader({
toggleVendorsTransactionsFilterDrawer: toggleFilterDrawer,
}) {
// Default form values.
const defaultValues = {
...pageFilter,
fromDate: moment().toDate(),
toDate: moment().toDate(),
vendorsIds: [],
};
const defaultValues = getVendorsTransactionsDefaultQuery();
// Initial form values.
const initialValues = transformToForm(
@@ -48,15 +45,8 @@ function VendorsTransactionsHeader({
},
defaultValues,
);
// Validation schema.
const validationSchema = Yup.object().shape({
fromDate: Yup.date().required().label(intl.get('fromDate')),
toDate: Yup.date()
.min(Yup.ref('fromDate'))
.required()
.label(intl.get('toDate')),
});
const validationSchema = getVendorTransactionsQuerySchema();
// Handle form submit.
const handleSubmit = (values, { setSubmitting }) => {
@@ -64,7 +54,6 @@ function VendorsTransactionsHeader({
toggleFilterDrawer(false);
setSubmitting(false);
};
// Handle drawer close action.
const handleDrawerClose = () => {
toggleFilterDrawer(false);

View File

@@ -1,8 +1,5 @@
// @ts-nocheck
import React from 'react';
import { Field } from 'formik';
import { Classes, FormGroup } from '@blueprintjs/core';
import classNames from 'classnames';
import FinancialStatementDateRange from '../FinancialStatementDateRange';
import FinancialStatementsFilter from '../FinancialStatementsFilter';
@@ -10,8 +7,9 @@ import FinancialStatementsFilter from '../FinancialStatementsFilter';
import {
Row,
Col,
ContactsMultiSelect,
FormattedMessage as T,
FFormGroup,
VendorsMultiSelect,
} from '@/components';
import { filterVendorsOptions } from '../constants';
@@ -53,22 +51,9 @@ function VendorsTransactionsHeaderGeneralPanelContent() {
<Row>
<Col xs={4}>
<Field name={'vendorsIds'}>
{({ form: { setFieldValue }, field: { value } }) => (
<FormGroup
label={<T id={'specific_vendors'} />}
className={classNames('form-group--select-list', Classes.FILL)}
>
<ContactsMultiSelect
items={vendors}
onItemSelect={(vendors) => {
const vendorsIds = vendors.map((customer) => customer.id);
setFieldValue('vendorsIds', vendorsIds);
}}
/>
</FormGroup>
)}
</Field>
<FFormGroup label={<T id={'specific_vendors'} />} name={'vendorsIds'}>
<VendorsMultiSelect name={'vendorsIds'} items={vendors} />
</FFormGroup>
</Col>
</Row>
</div>

View File

@@ -0,0 +1,25 @@
import * as Yup from 'yup';
import intl from 'react-intl-universal';
import moment from 'moment';
/**
* The validation schema of vendors transactions.
*/
export const getVendorTransactionsQuerySchema = () => {
return Yup.object().shape({
fromDate: Yup.date().required().label(intl.get('fromDate')),
toDate: Yup.date()
.min(Yup.ref('fromDate'))
.required()
.label(intl.get('toDate')),
});
};
/**
* Retrieves the default query of vendors transactions.
*/
export const getVendorsTransactionsDefaultQuery = () => ({
fromDate: moment().toDate(),
toDate: moment().toDate(),
vendorsIds: [],
});

View File

@@ -82,7 +82,6 @@ function BillForm({
isNewMode
? 'the_bill_has_been_created_successfully'
: 'the_bill_has_been_edited_successfully',
{ number: values.bill_number },
),
intent: Intent.SUCCESS,
});

View File

@@ -558,8 +558,8 @@
"bill_date_": "Bill date",
"bill_number_": "Bill number",
"delete_bill": "Delete Bill",
"the_bill_has_been_edited_successfully": "The bill #{number} has been edited successfully.",
"the_bill_has_been_created_successfully": "The bill #{number} has been created successfully.",
"the_bill_has_been_edited_successfully": "The bill has been edited successfully.",
"the_bill_has_been_created_successfully": "The bill has been created successfully.",
"the_bill_has_been_deleted_successfully": "The bill has been deleted successfully.",
"once_delete_this_bill_you_will_able_to_restore_it": "Once you delete this bill, you won't be able to restore it later. Are you sure you want to delete this bill?",
"deposit_to": "Deposit to",
@@ -2294,4 +2294,4 @@
"sidebar.new_time_entry": "New Time Entry",
"sidebar.project_profitability_summary": "Project Profitability Summary",
"global_error.too_many_requests": "Too many requests"
}
}