Compare commits

...

170 Commits

Author SHA1 Message Date
Ahmed Bouhuolia
ded4e2bb59 Merge pull request #560 from bigcapitalhq/fix-onboarding-on-small-screens
fix: Onboarding layout on small screens
2024-08-01 19:53:09 +02:00
Ahmed Bouhuolia
219e6fb466 fix: onboarding page layout on small screens 2024-08-01 19:51:25 +02:00
Ahmed Bouhuolia
4cd0405078 fix: quick payment received and payment made form initial values 2024-07-30 11:06:45 +02:00
Ahmed Bouhuolia
783102449f fix: create quick payment received and payment made transactions 2024-07-30 11:06:35 +02:00
Denis
ae617b2e1d Fixed Quick Payment Dialogs
PaymentReceives and BillsPayments Controllers expect 'amount' parameter, but webapp sends 'payment_amount'
2024-07-30 11:06:24 +02:00
Ahmed Bouhuolia
53f37f4f48 Merge pull request #546 from bigcapitalhq/remove-views-tabs
feat: Remove the views tabs bar from all tables
2024-07-25 19:21:50 +02:00
Ahmed Bouhuolia
0a7b522b87 chore: remove unused import 2024-07-25 19:21:16 +02:00
Ahmed Bouhuolia
9e6500ac79 feat: remove the views tabs bar from all tables 2024-07-25 19:17:54 +02:00
Ahmed Bouhuolia
b93cb546f4 Merge pull request #545 from bigcapitalhq/excessed-payments-as-credit
Excessed payments as credit
2024-07-25 18:57:31 +02:00
Ahmed Bouhuolia
6d17f9cbeb feat: record excessed payments as credit 2024-07-25 18:46:24 +02:00
Ahmed Bouhuolia
fe214b1b2d feat: push CHANGELOG 2024-07-17 16:53:47 +02:00
Ahmed Bouhuolia
6b6b73b77c feat: send signup event to Loops (#531)
* feat: send signup event to Loops

* feat: fix
2024-07-17 15:56:05 +02:00
Ahmed Bouhuolia
107a6f793b Merge pull request #526 from bigcapitalhq/monthly-plans
feat: upgrade the subscription plans
2024-07-14 14:21:57 +02:00
Ahmed Bouhuolia
67d155759e feat: backend the new monthly susbcription plans 2024-07-14 14:19:04 +02:00
Ahmed Bouhuolia
7e2e87256f Merge pull request #527 from bigcapitalhq/fix-sync-removed-transactions
fix: sync the removed bank transactions from the source
2024-07-13 21:56:13 +02:00
Ahmed Bouhuolia
df7790d7c1 fix: sync the removed bank transactions from the source 2024-07-13 21:54:44 +02:00
Ahmed Bouhuolia
72128a72c4 feat: add variant ids to new subscription plans 2024-07-13 19:53:52 +02:00
Ahmed Bouhuolia
eb3f23554f feat: upgrade the subscription plans 2024-07-13 18:19:18 +02:00
Ahmed Bouhuolia
69ddf43b3e fix: duplicated event emitter 2024-07-13 03:23:25 +02:00
Ahmed Bouhuolia
249eadaeaa Merge pull request #525 from bigcapitalhq/fix-plaid-transactions-syncing
fix: Plaid transactions syncing
2024-07-12 23:44:27 +02:00
Ahmed Bouhuolia
59168bc691 fix: Plaid transactions syncing 2024-07-12 23:43:20 +02:00
Ahmed Bouhuolia
81b26c6f13 fix(hotfix): uniqid import 2024-07-12 20:15:28 +02:00
Ahmed Bouhuolia
da435d85d9 Merge pull request #524 from bigcapitalhq/fix-cashflow-transactions-type
fix: Cashflow transactions types
2024-07-09 14:57:43 +02:00
Ahmed Bouhuolia
533006b90e fix: Cashflow transactions types 2024-07-09 14:47:30 +02:00
Ahmed Bouhuolia
d096e49d45 Merge pull request #523 from bigcapitalhq/matching-transactions-fixes
fix: Matching transactions bugs
2024-07-08 22:18:12 +02:00
Ahmed Bouhuolia
73acdb6240 fix: add bank rule categories 2024-07-08 21:48:16 +02:00
Ahmed Bouhuolia
38d4122d11 fix: matching transactions bugs 2024-07-08 19:37:11 +02:00
Ahmed Bouhuolia
24a77c81b3 fix: unexpected char in cashflow transactions report 2024-07-08 15:25:28 +02:00
Ahmed Bouhuolia
7f41b4280e fix: the database migration schema 2024-07-08 15:18:58 +02:00
Ahmed Bouhuolia
aa89653967 Merge pull request #522 from bigcapitalhq/reconcile-match-transactionss
Reconcile match transactionss
2024-07-07 23:52:30 +02:00
Ahmed Bouhuolia
b80bc95fa5 fix: increment/decrement uncategorized transactions on excluding 2024-07-07 23:35:26 +02:00
Ahmed Bouhuolia
9a5befbee7 fix: bank transactions report 2024-07-07 22:11:57 +02:00
Ahmed Bouhuolia
b7487f19d3 fix: improvements to bank matching transactions 2024-07-06 19:10:07 +02:00
Ahmed Bouhuolia
cd9039fe16 fix(server): match transactions query 2024-07-06 16:10:34 +02:00
Ahmed Bouhuolia
87f60f7461 feat: cashflow transaction matching 2024-07-04 22:44:20 +02:00
Ahmed Bouhuolia
202179ec0b feat: reconcile matching transactions 2024-07-04 19:21:05 +02:00
Ahmed Bouhuolia
168883a933 fix: syntax error 2024-07-04 17:50:48 +02:00
Ahmed Bouhuolia
f62ec83e29 Merge branch 'main' into develop 2024-07-04 17:28:05 +02:00
Ahmed Bouhuolia
eff8b41720 Merge pull request #519 from bigcapitalhq/change-settings-value-colum-to-text
fix: alter value column of the settings table to text instead of string
2024-07-04 09:05:17 +02:00
Ahmed Bouhuolia
632cc3d72e fix: alter value column of the settings table to text instead of string 2024-07-04 08:58:41 +02:00
Ahmed Bouhuolia
aefdaac68d Merge pull request #511 from bigcapitalhq/BIG-208
feat: Bank rules for uncategorized transactions
2024-07-03 19:43:28 +02:00
Ahmed Bouhuolia
b8a0a5509d fix: style matching bank transactions 2024-07-03 19:41:43 +02:00
Ahmed Bouhuolia
a5eb42edaf feat: wip bank transaction matching 2024-07-03 18:49:21 +02:00
Ahmed Bouhuolia
67b519db61 fix: filter the uncategorized transactions out of matched transactions 2024-07-03 17:23:12 +02:00
Ahmed Bouhuolia
91730d204e feat: get bank account meta summary 2024-07-02 19:21:31 +02:00
Ahmed Bouhuolia
8a09de9771 fix: bank rules 2024-07-02 12:17:01 +02:00
Ahmed Bouhuolia
50861940a8 feat: style the banking service 2024-07-01 20:11:30 +02:00
Ahmed Bouhuolia
55caf037cd fix: match transaction aside layout 2024-07-01 19:24:09 +02:00
Ahmed Bouhuolia
c95eec565d feat: auto fill categorize form from recognized transaction 2024-07-01 15:48:40 +02:00
Ahmed Bouhuolia
79616cf1eb feat: sort the matched transactions 2024-07-01 13:03:38 +02:00
Ahmed Bouhuolia
c27458ebcc feat: wip matching bank transactions 2024-07-01 12:02:59 +02:00
Ahmed Bouhuolia
da0fab9a58 fix: Bank rules conditions column 2024-07-01 10:48:11 +02:00
Ahmed Bouhuolia
5bbcb7913d fix: Delete bank rule if it has no associations 2024-06-30 16:54:25 +02:00
Ahmed Bouhuolia
48ff93b6ab feat: Typing the bank rules hooks 2024-06-30 08:27:32 +02:00
Ahmed Bouhuolia
f816e7f25c fix(webapp): Switch between uncategorized transactions tabs 2024-06-29 19:31:13 +02:00
Ahmed Bouhuolia
3cd66ba4d6 feat: merge the boot provider of categorize and matching forms 2024-06-29 17:00:36 +02:00
Ahmed Bouhuolia
5d5d4a1972 feat: Calculate the total pending when matching. 2024-06-29 14:35:24 +02:00
Ahmed Bouhuolia
b01528c06b fix: group matches to get possible and perfect matches 2024-06-29 13:21:59 +02:00
Ahmed Bouhuolia
cb1f587637 fix(server): Handle the delete error when the matched transaction 2024-06-29 10:30:03 +02:00
Ahmed Bouhuolia
978ce6c441 feat: excluded bank transactions 2024-06-27 22:14:53 +02:00
Ahmed Bouhuolia
fab22c9820 feat: endpoint to get recognized transactions 2024-06-27 14:23:17 +02:00
Ahmed Bouhuolia
7edf268e75 fix: mathcing bank transaction styling 2024-06-26 22:25:59 +02:00
Ahmed Bouhuolia
87bf29f28c fix(server): getting matched transaction transformer 2024-06-26 22:25:37 +02:00
Ahmed Bouhuolia
d305c7ad32 feat: toggle banking matching aside 2024-06-26 19:33:01 +02:00
Ahmed Bouhuolia
7a9c7209bc feat: hook up the matching form to the server 2024-06-26 17:39:12 +02:00
Ahmed Bouhuolia
d2d37820f5 feat(webapp): edit bank rule 2024-06-26 00:04:54 +02:00
Ahmed Bouhuolia
1889969191 feat: bank rules table 2024-06-25 23:45:31 +02:00
Ahmed Bouhuolia
8c2888fcd8 fix(server): delete bank rule 2024-06-25 23:44:57 +02:00
Ahmed Bouhuolia
47879d04b2 feat(webapp): bank rule 2024-06-25 22:20:36 +02:00
Ahmed Bouhuolia
f1f52ce972 feat(webapp): bank rule form 2024-06-25 17:31:32 +02:00
Ahmed Bouhuolia
dad8aeaff1 feat(webapp): rule form 2024-06-25 13:42:19 +02:00
Ahmed Bouhuolia
5aae45c8a8 feat(webapp): bank rules 2024-06-25 11:57:02 +02:00
Ahmed Bouhuolia
3e437a041c Merge pull request #518 from bigcapitalhq/BIG-213
fix: Tax rate not saving on creating a new invoice
2024-06-24 10:47:21 +02:00
Ahmed Bouhuolia
e783cfeafa fix: Tax rate not saving on creating a new invoice 2024-06-24 10:46:19 +02:00
Ahmed Bouhuolia
5dde7f5584 Merge pull request #516 from bigcapitalhq/BIG-212
fix: Reorder 'debit' and 'credit' columns
2024-06-24 10:44:28 +02:00
Ahmed Bouhuolia
8e0911ec85 fix: Reorder 'debit' and 'credit' columns 2024-06-24 10:43:34 +02:00
Ahmed Bouhuolia
66d2d6a612 feat: avoid categorize excluded transaction 2024-06-23 23:34:20 +02:00
Ahmed Bouhuolia
8dc2b18707 feat: recognize the syncd bank transactions 2024-06-23 18:49:46 +02:00
Ahmed Bouhuolia
589b29bbdd feat: validate the matched linked transacation on deleting. 2024-06-23 14:34:40 +02:00
Ahmed Bouhuolia
ca403872b3 feat: exclude bank transaction 2024-06-21 11:33:03 +02:00
Ahmed Bouhuolia
738a84bb4b feat: match bank transaction 2024-06-20 23:31:46 +02:00
Ahmed Bouhuolia
b37002bea6 feat: exclude/unexclude the uncategorized transactions 2024-06-20 13:50:29 +02:00
Ahmed Bouhuolia
b6deb842ff feat: retrieve the matching transactions 2024-06-20 10:20:18 +02:00
Ahmed Bouhuolia
d3230767dd feat: matching uncategorized transactions 2024-06-19 22:40:10 +02:00
Ahmed Bouhuolia
6c4b0cdac5 feat: auto recognize uncategorized transactions 2024-06-19 13:49:12 +02:00
Ahmed Bouhuolia
0b5cee070a feat: recognize uncategorized transactions 2024-06-18 21:43:54 +02:00
Ahmed Bouhuolia
906835c396 feat: bank rules for uncategorized transactions 2024-06-18 17:14:30 +02:00
Ahmed Bouhuolia
7b4afd3859 Update .env.example 2024-06-17 18:30:13 +02:00
Ahmed Bouhuolia
590715037b chore: dump CHANGELOG.md 2024-06-17 15:33:49 +02:00
Ahmed Bouhuolia
1e53a8e85e Merge pull request #506 from bigcapitalhq/BIG-206
feat: Setting up the date format in the whole system dates
2024-06-17 12:53:31 +02:00
Ahmed Bouhuolia
2ad77103ac feat: cashflow tranasction date format 2024-06-17 12:50:31 +02:00
Ahmed Bouhuolia
c1fc70863b Merge pull request #497 from bigcapitalhq/BIG-195
fix: Disable email confirmation does not work with invited users
2024-06-17 10:34:33 +02:00
Ahmed Bouhuolia
125dff8376 feat: format created at date 2024-06-17 10:27:02 +02:00
Ahmed Bouhuolia
84da7b7df5 Merge pull request #509 from bigcapitalhq/BIG-193
feat: Migrating to Envoy proxy instead of Nginx
2024-06-17 09:22:23 +02:00
Ahmed Bouhuolia
4c82f6f8ad feat: Migrating to Envoy proxy instead of Nginx 2024-06-15 11:54:19 +02:00
Ahmed Bouhuolia
0d7aad5448 Merge pull request #508 from bigcapitalhq/BIG-142
fix: add space between buttons on floating actions bar
2024-06-14 08:29:45 +02:00
Ahmed Bouhuolia
74b74a2722 fix: add space between buttons on floating actions bar 2024-06-14 08:27:30 +02:00
Ahmed Bouhuolia
3a0a0db8a7 feat: setting up the date format in the whole system dates 2024-06-12 19:43:42 +02:00
Ahmed Bouhuolia
265ea9ca48 Merge pull request #501 from bigcapitalhq/BIG-202
fix: Balance sheet and P/L nested accounts
2024-06-12 13:06:37 +02:00
Ahmed Bouhuolia
cfd37f8894 fix: Balance sheet and P/L nested accounts 2024-06-12 13:05:02 +02:00
Ahmed Bouhuolia
d1caa5c5ce fix: Disable email confirmation does not work with invited users 2024-06-10 15:59:33 +02:00
Ahmed Bouhuolia
d998d716b7 Merge pull request #496 from bigcapitalhq/fix-payment-receive-attachments
fix: Edit the payment received transactions with attachments
2024-06-10 13:41:44 +02:00
Ahmed Bouhuolia
031ccc4a0b fix: Edit the payment received transactions with attachments 2024-06-10 13:41:10 +02:00
Ahmed Bouhuolia
e4f61823b3 Merge pull request #485 from bigcapitalhq/BIG-186
fix: Closing balance in general ledger report does not sum the negative figures
2024-06-10 08:17:01 +02:00
Ahmed Bouhuolia
1cbc1c056f feat: general ledger filter nodes 2024-06-10 08:08:47 +02:00
Ahmed Bouhuolia
4d4ef54c56 Merge pull request #494 from bigcapitalhq/BIG-192
fix: Concurrency controlling multiple processes in Bigcapital CLI commands
2024-06-09 22:54:02 +02:00
Ahmed Bouhuolia
f7fcfefc78 fix: Concurrency controlling multiple processes in Bigcapital CLI commands 2024-06-09 22:52:56 +02:00
Ahmed Bouhuolia
858f347fd4 Merge pull request #493 from bigcapitalhq/BIG-198
fix: Something wrong in uploading uncategorized bank transactions
2024-06-09 21:30:32 +02:00
Ahmed Bouhuolia
4d73b59cf3 fix: Something wrong in uploading uncategorized bank transactions 2024-06-09 21:30:07 +02:00
Ahmed Bouhuolia
bc67f0cca8 fix: increment/decrement the uncategorized transactios on accounts 2024-06-09 21:05:43 +02:00
Ahmed Bouhuolia
ef2d1ff141 feat: Add COGS type to cash transactions categorization 2024-06-09 21:05:19 +02:00
Ahmed Bouhuolia
dc4cdb2a8f fix: Assign branch in categorize bank transaction 2024-06-09 20:05:15 +02:00
Ahmed Bouhuolia
8862810706 Merge pull request #489 from bigcapitalhq/fix-plaid-syncing
fix: Plaid data available syncing
2024-06-07 01:31:34 +02:00
Ahmed Bouhuolia
3dadbeac4d fix: all sql queries should be under one transaction 2024-06-07 01:30:08 +02:00
Ahmed Bouhuolia
494d2c1fe0 fix: TS typing 2024-06-07 01:11:19 +02:00
Ahmed Bouhuolia
d27562bd43 fix: Plaid data available syncing 2024-06-07 01:07:17 +02:00
Ahmed Bouhuolia
8b99e0938d fix: remove un-used code 2024-06-06 18:50:24 +02:00
Ahmed Bouhuolia
94192bfc29 fix: doctype general ledger 2024-06-06 18:48:33 +02:00
Ahmed Bouhuolia
708a4dda9e chore: remove the console.log 2024-06-06 18:44:19 +02:00
Ahmed Bouhuolia
10fcf94c92 feat: general ledger closing balance with accounts row 2024-06-06 18:42:07 +02:00
Ahmed Bouhuolia
fc9995c4da chore: dump CHANGELOG.md 2024-06-06 12:32:31 +02:00
Ahmed Bouhuolia
7dc769004d fix: billing variant id 2024-06-06 11:19:19 +02:00
Ahmed Bouhuolia
5dbfd36415 feat: optimize the style of general ledger sub-accounts rows 2024-06-05 22:42:12 +02:00
Ahmed Bouhuolia
044f11ff74 feat: general ledger sub-accounts 2024-06-05 21:45:01 +02:00
Ahmed Bouhuolia
6afe1a09c6 fix: Closing balance in general ledger report does not sum the negative figures. 2024-06-04 21:26:46 +02:00
Ahmed Bouhuolia
909a70e2c5 feat: correct the migration files 2024-06-04 17:42:29 +02:00
Ahmed Bouhuolia
84dd0fa86b Merge remote-tracking branch 'refs/remotes/origin/develop' into develop 2024-06-04 16:22:07 +02:00
Ahmed Bouhuolia
a4719fe15b fix: add Plaid env variables to docker-compose.prod file 2024-06-04 16:21:49 +02:00
Ahmed Bouhuolia
fd915b503f fix: Run migrations only for initialized tenants (#484) 2024-06-04 16:13:18 +02:00
Ahmed Bouhuolia
bbba54c08e fix: validate the s3 configures exist (#482) 2024-06-04 15:11:21 +02:00
Ahmed Bouhuolia
f241e2bede fix: Plaid syncs deposit imports as withdrawals (#481) 2024-06-03 21:56:29 +02:00
Ahmed Bouhuolia
175bc243f3 fix: Organize Plaid env variables for development and sandbox envs (#480) 2024-06-03 20:50:02 +02:00
Ahmed Bouhuolia
7c06c8bb8a fix: Lemon Squeezy redirect to base url (#479)
fix: Lemon Squeezy redirect to base url
2024-06-03 19:54:40 +02:00
Ahmed Bouhuolia
8fd930caac Merge pull request #478 from bigcapitalhq/virtual-docker-internal-network
feat: Internal docker virtual network
2024-06-02 21:25:55 +02:00
Ahmed Bouhuolia
e175307da4 feat: internal docker virtual network 2024-06-02 21:25:15 +02:00
Ahmed Bouhuolia
b1bf932e88 fix: add S3 env variables to docker-compose prod 2024-06-02 17:46:10 +02:00
Ahmed Bouhuolia
aa897212ab Merge remote-tracking branch 'refs/remotes/origin/develop' into develop 2024-06-02 17:35:49 +02:00
Ahmed Bouhuolia
890903e08b chore: change the variant id. 2024-06-02 17:34:52 +02:00
Ahmed Bouhuolia
16b2a33cf6 Merge pull request #476 from bigcapitalhq/abouolia-patch-1
Build and deploy develop Docker container
2024-06-02 16:57:36 +02:00
Ahmed Bouhuolia
382d4ab028 Build and deploy develop Docker container 2024-06-02 16:57:07 +02:00
Ahmed Bouhuolia
85f26e1079 Merge pull request #460 from bigcapitalhq/print-resources
feat: Export resource tables to pdf
2024-06-02 13:24:43 +02:00
Ahmed Bouhuolia
1b237323f6 feat: document export functions 2024-06-02 13:24:21 +02:00
Ahmed Bouhuolia
f15fecde54 feat: resource tables printing 2024-06-02 13:15:56 +02:00
Ahmed Bouhuolia
79be4266bb feat: style resource printable columns 2024-05-31 18:12:09 +02:00
Ahmed Bouhuolia
08ad117331 feat: migrate the printing from Attachment to Document model 2024-05-31 15:32:51 +02:00
Ahmed Bouhuolia
958f78e7a4 feat: improve UI experience of resource priting 2024-05-31 15:30:49 +02:00
Ahmed Bouhuolia
ba77351e44 Merge branch 'develop' into print-resources 2024-05-30 19:50:05 +02:00
Ahmed Bouhuolia
09a15966f0 Merge pull request #459 from bigcapitalhq/skip-sending-confirm-email-if-disabled
fix: skip send confirmation email if disabled
2024-05-30 18:38:17 +02:00
Ahmed Bouhuolia
7ff36e8c4f feat: add s3 env variables to .env.example 2024-05-30 17:58:58 +02:00
Ahmed Bouhuolia
8ed24748ec Merge pull request #461 from bigcapitalhq/big-157-attach-documents-to-transactions
feat: upload and attach documents
2024-05-30 17:47:53 +02:00
Ahmed Bouhuolia
6a6dcadaf9 fix: TS types 2024-05-30 17:47:27 +02:00
Ahmed Bouhuolia
308a4f62ae feat: catch exceptions link attachment service 2024-05-29 22:15:31 +02:00
Ahmed Bouhuolia
6e50de1d28 feat: style tweaks to upload attachments popover 2024-05-29 19:03:21 +02:00
Ahmed Bouhuolia
ceb133e29a feat: getting presigned url of the uploaded attachment 2024-05-29 16:16:08 +02:00
Ahmed Bouhuolia
e7871e34a9 feat: wip upload attachmentsx 2024-05-29 13:58:08 +02:00
Ahmed Bouhuolia
cfdbcea9c0 feat: wip UI upload attachments 2024-05-28 23:34:51 +02:00
Ahmed Bouhuolia
fcd61c6159 feat: wip UI attachments 2024-05-28 15:59:15 +02:00
Ahmed Bouhuolia
2244cc6116 feat: wip attach attachments to resource models 2024-05-26 21:59:39 +02:00
Ahmed Bouhuolia
15dbc4137c Merge branch 'develop' into big-157-attach-documents-to-transactions 2024-05-24 20:22:43 +02:00
Ahmed Bouhuolia
8f904fae3a feat: link and unlink document to resource model 2024-05-24 19:50:06 +02:00
Ahmed Bouhuolia
c8f31f33be feat: wip upload documents 2024-05-24 14:28:21 +02:00
Ahmed Bouhuolia
dc5bdf0b66 feat: print action when click on print button 2024-05-23 19:39:23 +02:00
Ahmed Bouhuolia
fe41f7976d feat: export resource tables to pdf 2024-05-23 14:23:49 +02:00
Ahmed Bouhuolia
2c7da86a00 fix: skip send confirmation email if disabled 2024-05-23 10:09:48 +02:00
Ahmed Bouhuolia
8c2b9fba29 fix: add the signup email confirmation env var (#458) 2024-05-22 21:10:56 +02:00
Ahmed Bouhuolia
7208b8fab5 feat: add the missing Newrelic env vars to docker-compose.prod file (#457) 2024-05-22 20:42:00 +02:00
Ahmed Bouhuolia
0836fe14e0 feat: handle http exceptions (#456) 2024-05-22 19:30:41 +02:00
Ahmed Bouhuolia
1227111fae fix: typo 2024-05-18 15:44:53 +02:00
Ahmed Bouhuolia
2ada57a2b4 fix: auto-increment setting parsing. (#453) 2024-05-17 12:49:04 +02:00
Ahmed Bouhuolia
e380c598d3 fix: Showing the real mail address on email confirmation view (#445)
* fix: Showing the real mail address on email confirmation view

* chore: remove the unused hook
2024-05-15 14:03:58 +02:00
585 changed files with 24244 additions and 8527 deletions

View File

@@ -75,31 +75,17 @@ PLAID_ENV=sandbox
# Your Plaid keys, which can be found in the Plaid Dashboard.
# https://dashboard.plaid.com/account/keys
PLAID_CLIENT_ID=
PLAID_SECRET_DEVELOPMENT=
PLAID_SECRET_SANDBOX=
PLAID_SECRET=
PLAID_LINK_WEBHOOK=
# (Optional) Redirect URI settings section
# Only required for OAuth redirect URI testing (not common on desktop):
# Sandbox Mode:
# Set the PLAID_SANDBOX_REDIRECT_URI below to 'http://localhost:3001/oauth-link'.
# The OAuth redirect flow requires an endpoint on the developer's website
# that the bank website should redirect to. You will also need to configure
# this redirect URI for your client ID through the Plaid developer dashboard
# at https://dashboard.plaid.com/team/api.
# Development mode:
# When running in development mode, you must use an https:// url.
# You will need to configure this https:// redirect URI in the Plaid developer dashboard.
# Instructions to create a self-signed certificate for localhost can be found at
# https://github.com/plaid/pattern/blob/master/README.md#testing-oauth.
# If your system is not set up to run localhost with https://, you will be unable to test
# the OAuth in development and should leave the PLAID_DEVELOPMENT_REDIRECT_URI blank.
PLAID_SANDBOX_REDIRECT_URI=
PLAID_DEVELOPMENT_REDIRECT_URI=
# https://docs.lemonsqueezy.com/guides/developer-guide/getting-started#create-an-api-key
LEMONSQUEEZY_API_KEY=
LEMONSQUEEZY_STORE_ID=
LEMONSQUEEZY_WEBHOOK_SECRET=
# S3 documents and attachments
S3_REGION=US
S3_ACCESS_KEY_ID=
S3_SECRET_ACCESS_KEY=
S3_ENDPOINT=
S3_BUCKET=

View File

@@ -0,0 +1,127 @@
# This workflow will build a docker container, publish it to Github Registry.
name: Build and Deploy Develop Docker Container
on:
push:
branches:
- develop
env:
WEBAPP_IMAGE_NAME: bigcapitalhq/webapp
SERVER_IMAGE_NAME: bigcapitalhq/server
jobs:
build-publish-webapp:
strategy:
fail-fast: false
name: Build and deploy webapp container
runs-on: ubuntu-latest
environment: production
steps:
- name: Prepare
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
- name: Checkout
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
# Login to Container registry.
- name: Log in to the Container registry
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
with:
images: ${{ env.WEBAPP_IMAGE_NAME }}
# Builds and push the Docker image.
- name: Build and push Docker image
uses: docker/build-push-action@v5
id: build
with:
context: ./
file: ./packages/webapp/Dockerfile
platforms: linux/amd64
push: true
labels: ${{ steps.meta.outputs.labels }}
tags: bigcapitalhq/webapp:develop
- name: Export digest
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v4
with:
name: digests-webapp
path: /tmp/digests/*
if-no-files-found: error
retention-days: 1
# Send notification to Slack channel.
- name: Slack Notification built and published webapp container successfully.
uses: rtCamp/action-slack-notify@v2
env:
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
build-publish-server:
name: Build and deploy server container
runs-on: ubuntu-latest
steps:
- name: Prepare
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
- name: Checkout
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
# Login to Container registry.
- name: Log in to the Container registry
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
# Builds and push the Docker image.
- name: Build and push Docker image
uses: docker/build-push-action@v5
id: build
with:
context: ./
file: ./packages/server/Dockerfile
platforms: linux/amd64
push: true
tags: bigcapitalhq/server:develop
labels: ${{ steps.meta.outputs.labels }}
- name: Export digest
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v4
with:
name: digests-server
path: /tmp/digests/*
if-no-files-found: error
retention-days: 1
# Send notification to Slack channel.
- name: Slack Notification built and published server container successfully.
uses: rtCamp/action-slack-notify@v2
env:
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}

View File

@@ -2,6 +2,57 @@
All notable changes to Bigcapital server-side will be in this file.
## [v0.18.0] - 10-08-2024
* feat: Bank rules for automated categorization by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/511
* feat: Categorize & match bank transaction by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/511
* feat: Reconcile match transactions by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/522
* fix: Issues in matching transactions by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/523
* fix: Cashflow transactions types by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/524
## [v0.17.5] - 17-06-2024
* fix: Balance sheet and P/L nested accounts by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/501
* fix: add space between buttons on floating actions bar by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/508
* feat: Migrating to Envoy proxy instead of Nginx by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/509
* fix: Disable email confirmation does not work with invited users by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/497
* feat: Setting up the date format in the whole system dates by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/506
## [0.17.0] - 04-06-2024
### New
* feat: Upload and attach documents by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/461
* feat: Export resource tables to pdf by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/460
* feat: Build and deploy develop Docker container by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/476
* feat: Internal docker virtual network by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/478
### Fixes
* fix: Skip send confirmation email if disabled by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/459
* fix: Lemon Squeezy redirect to base url by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/479
* fix: Organize Plaid env variables for development and sandbox envs by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/480
* fix: Plaid syncs deposit imports as withdrawals by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/481
* fix: Validate the s3 configures exist by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/482
* fix: Run migrations only for initialized tenants by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/484
## [0.16.16] -
* feat: handle http exceptions by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/456
* feat: add the missing Newrelic env vars to docker-compose.prod file by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/457
* fix: add the signup email confirmation env var by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/458
## [0.16.14] -
* fix: Typo in setup wizard by @ccantrell72 in https://github.com/bigcapitalhq/bigcapital/pull/440
* fix: Showing the real mail address on email confirmation view by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/445
* fix: Auto-increment setting parsing by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/453
## [0.16.12] -
* feat: Create a manifest list for `webapp` Docker image and push it to DockerHub. by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/436
* feat: Combine arm64 and amd64 in one Github action runner by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/437
## [0.16.11] - 06-05-2024
### improvements

View File

@@ -3,30 +3,27 @@
version: '3.3'
services:
nginx:
container_name: bigcapital-nginx-gateway
build:
context: ./docker/nginx
args:
- SERVER_PROXY_PORT=3000
- WEB_SSL=false
- SELF_SIGNED=false
volumes:
- ./data/logs/nginx/:/var/log/nginx
- ./docker/certbot/certs/:/var/certs
proxy:
image: envoyproxy/envoy:v1.30-latest
depends_on:
- server
- webapp
ports:
- '${PUBLIC_PROXY_PORT:-80}:80'
- '${PUBLIC_PROXY_SSL_PORT:-443}:443'
tty: true
depends_on:
- server
- webapp
volumes:
- ./docker/envoy/envoy.yaml:/etc/envoy/envoy.yaml
restart: on-failure
networks:
- bigcapital_network
webapp:
container_name: bigcapital-webapp
image: bigcapitalhq/webapp:latest
restart: on-failure
networks:
- bigcapital_network
server:
container_name: bigcapital-server
@@ -42,6 +39,8 @@ services:
- mongo
- redis
restart: on-failure
networks:
- bigcapital_network
environment:
# Mail
- MAIL_HOST=${MAIL_HOST}
@@ -82,18 +81,24 @@ services:
- SIGNUP_ALLOWED_DOMAINS=${SIGNUP_ALLOWED_DOMAINS}
- SIGNUP_ALLOWED_EMAILS=${SIGNUP_ALLOWED_EMAILS}
# Sign-up email confirmation
- SIGNUP_EMAIL_CONFIRMATION=${SIGNUP_EMAIL_CONFIRMATION}
# Gotenberg (Pdf generator)
- GOTENBERG_URL=${GOTENBERG_URL}
- GOTENBERG_DOCS_URL=${GOTENBERG_DOCS_URL}
# Exchange Rate
- EXCHANGE_RATE_SERVICE=${EXCHANGE_RATE_SERVICE}
- OPEN_EXCHANGE_RATE_APP_ID-${OPEN_EXCHANGE_RATE_APP_ID}
# Bank Sync
- BANKING_CONNECT=${BANKING_CONNECT}
# Plaid
- PLAID_ENV=${PLAID_ENV}
- PLAID_CLIENT_ID=${PLAID_CLIENT_ID}
- PLAID_SECRET_DEVELOPMENT=${PLAID_SECRET_DEVELOPMENT}
- PLAID_SECRET_SANDBOX=${b8cf42b441e110451e2f69ad7e1e9f}
- PLAID_SECRET=${PLAID_SECRET}
- PLAID_LINK_WEBHOOK=${PLAID_LINK_WEBHOOK}
# Lemon Squeez
@@ -108,7 +113,15 @@ services:
- NEW_RELIC_AI_MONITORING_ENABLED=${NEW_RELIC_AI_MONITORING_ENABLED}
- NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED=${NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED}
- NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED=${NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED}
- NEW_RELIC_LICENSE_KEY=${NEW_RELIC_LICENSE_KEY}
- NEW_RELIC_APP_NAME=${NEW_RELIC_APP_NAME}
# S3
- S3_REGION=${S3_REGION}
- S3_ACCESS_KEY_ID=${S3_ACCESS_KEY_ID}
- S3_SECRET_ACCESS_KEY=${S3_SECRET_ACCESS_KEY}
- S3_ENDPOINT=${S3_ENDPOINT}
- S3_BUCKET=${S3_BUCKET}
database_migration:
container_name: bigcapital-database-migration
@@ -126,6 +139,8 @@ services:
- TENANT_DB_NAME_PERFIX=${TENANT_DB_NAME_PERFIX}
depends_on:
- mysql
networks:
- bigcapital_network
mysql:
container_name: bigcapital-mysql
@@ -141,6 +156,8 @@ services:
- mysql:/var/lib/mysql
expose:
- '3306'
networks:
- bigcapital_network
mongo:
container_name: bigcapital-mongo
@@ -150,6 +167,8 @@ services:
- '27017'
volumes:
- mongo:/var/lib/mongodb
networks:
- bigcapital_network
redis:
container_name: bigcapital-redis
@@ -160,11 +179,15 @@ services:
- '6379'
volumes:
- redis:/data
networks:
- bigcapital_network
gotenberg:
image: gotenberg/gotenberg:7
expose:
- '9000'
networks:
- bigcapital_network
# Volumes
volumes:
@@ -179,3 +202,8 @@ volumes:
redis:
name: bigcapital_prod_redis
driver: local
# Networks
networks:
bigcapital_network:
driver: bridge

62
docker/envoy/envoy.yaml Normal file
View File

@@ -0,0 +1,62 @@
static_resources:
listeners:
- name: listener_0
address:
socket_address:
address: 0.0.0.0
port_value: 80
filter_chains:
- filters:
- name: envoy.filters.network.http_connection_manager
typed_config:
'@type': type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: ingress_http
route_config:
name: local_route
virtual_hosts:
- name: backend
domains: ['*']
routes:
- match:
prefix: '/api'
route:
cluster: dynamic_server
- match:
prefix: '/'
route:
cluster: webapp
http_filters:
- name: envoy.filters.http.router
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
clusters:
- name: dynamic_server
connect_timeout: 0.25s
type: STRICT_DNS
dns_lookup_family: V4_ONLY
lb_policy: ROUND_ROBIN
load_assignment:
cluster_name: dynamic_server
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: server
port_value: 3000
- name: webapp
connect_timeout: 0.25s
type: STRICT_DNS
dns_lookup_family: V4_ONLY
lb_policy: ROUND_ROBIN
load_assignment:
cluster_name: webapp
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: webapp
port_value: 80

View File

@@ -1,21 +0,0 @@
FROM nginx:1.11
RUN mkdir /etc/nginx/sites-available && rm /etc/nginx/conf.d/default.conf
ADD nginx.conf /etc/nginx/
COPY scripts /root/scripts/
COPY certs /etc/ssl/
COPY sites /etc/nginx/templates
ARG SERVER_PROXY_PORT=3000
ARG WEB_SSL=false
ARG SELF_SIGNED=false
ENV SERVER_PROXY_PORT=$SERVER_PROXY_PORT
ENV WEB_SSL=$WEB_SSL
ENV SELF_SIGNED=$SELF_SIGNED
RUN /bin/bash /root/scripts/build-nginx.sh
CMD nginx

View File

@@ -1,33 +0,0 @@
user www-data;
worker_processes auto;
pid /run/nginx.pid;
daemon off;
events {
worker_connections 2048;
use epoll;
}
http {
server_tokens off;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 15;
types_hash_max_size 2048;
client_max_body_size 20M;
open_file_cache max=100;
gzip on;
gzip_disable "msie6";
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS';
include /etc/nginx/mime.types;
default_type application/octet-stream;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-available/*;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
}

View File

@@ -1,9 +0,0 @@
#!/bin/bash
for conf in /etc/nginx/templates/*.conf; do
mv $conf "/etc/nginx/sites-available/"$(basename $conf) > /dev/null
done
for template in /etc/nginx/templates/*.template; do
envsubst < $template > "/etc/nginx/sites-available/"$(basename $template)".conf"
done

View File

@@ -1,16 +0,0 @@
server {
listen 80 default_server;
location /api {
proxy_pass http://server:${SERVER_PROXY_PORT};
}
location / {
proxy_pass http://webapp;
}
location /.well-known/acme-challenge/ {
root /var/www/letsencrypt/;
log_not_found off;
}
}

View File

@@ -20,9 +20,13 @@
"bigcapital": "./bin/bigcapital.js"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.576.0",
"@aws-sdk/s3-request-presigner": "^3.583.0",
"@casl/ability": "^5.4.3",
"@hapi/boom": "^7.4.3",
"@lemonsqueezy/lemonsqueezy.js": "^2.2.0",
"@supercharge/promise-pool": "^3.2.0",
"@types/express": "^4.17.21",
"@types/i18n": "^0.8.7",
"@types/knex": "^0.16.1",
"@types/mathjs": "^6.0.12",
@@ -73,12 +77,14 @@
"lru-cache": "^6.0.0",
"mathjs": "^9.4.0",
"memory-cache": "^0.2.0",
"mime-types": "^2.1.35",
"moment": "^2.24.0",
"moment-range": "^4.0.2",
"moment-timezone": "^0.5.43",
"mongodb": "^6.1.0",
"mongoose": "^5.10.0",
"multer": "1.4.5-lts.1",
"multer-s3": "^3.0.1",
"mustache": "^3.0.3",
"mysql": "^2.17.1",
"mysql2": "^1.6.5",
@@ -113,6 +119,7 @@
},
"devDependencies": {
"@types/lodash": "^4.14.158",
"@types/multer": "^1.4.11",
"@types/ramda": "^0.27.64",
"@typescript-eslint/eslint-plugin": "^5.50.0",
"@typescript-eslint/parser": "^5.50.0",

View File

@@ -0,0 +1,38 @@
@import "../base.scss";
body {
font-family: system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue","Noto Sans","Liberation Sans",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";
font-size: 12px;
line-height: 1.4;
margin: 0;
}
.sheet__title{
margin-bottom: 18px;
}
.sheet__title h2{
line-height: 1;
margin-top: 0;
margin-bottom: 10px;
font-size: 16px;
}
.sheet__table {
font-size: inherit;
line-height: inherit;
width: 100%;
}
.sheet__table {
table-layout: auto;
border-collapse: collapse;
width: 100%;
}
.sheet__table thead tr th {
border-top: 1px solid #000;
border-bottom: 1px solid #000;
background: #fff;
padding: 8px;
line-height: 1.2;
}
.sheet__table tbody tr td {
padding: 4px 8px;
border-bottom: 1px solid #CCC;
}

View File

@@ -0,0 +1,24 @@
block head
style
include ../../css/modules/export-resource-table.css
style.
!{customCSS}
block content
.sheet
.sheet__title
h2.sheetTitle= sheetTitle
p.sheetDesc= sheetDescription
table.sheet__table
thead
tr
each column in table.columns
th(style=column.style class='column--' + column.key)= column.name
tbody
each row in table.rows
tr(class=row.classNames)
each cell in row.cells
td(class='cell--' + cell.key)
span!= cell.value

View File

@@ -70,6 +70,10 @@ module.exports = {
src: `${RESOURCES_PATH}/scss/modules/financial-sheet.scss`,
dest: `${RESOURCES_PATH}/css/modules`,
},
{
src: `${RESOURCES_PATH}/scss/modules/export-resource-table.scss`,
dest: `${RESOURCES_PATH}/css/modules`,
},
],
// RTL builds.
rtl: [

View File

@@ -207,7 +207,6 @@ export default class AccountsController extends BaseController {
tenantId,
accountDTO
);
return res.status(200).send({
id: account.id,
message: 'The account has been created successfully.',

View File

@@ -0,0 +1,264 @@
import mime from 'mime-types';
import { Service, Inject } from 'typedi';
import { Router, Response, NextFunction, Request } from 'express';
import { body, param } from 'express-validator';
import BaseController from '@/api/controllers/BaseController';
import { AttachmentsApplication } from '@/services/Attachments/AttachmentsApplication';
import { AttachmentUploadPipeline } from '@/services/Attachments/S3UploadPipeline';
@Service()
export class AttachmentsController extends BaseController {
@Inject()
private attachmentsApplication: AttachmentsApplication;
@Inject()
private uploadPipelineService: AttachmentUploadPipeline;
/**
* Router constructor.
*/
public router() {
const router = Router();
router.post(
'/',
this.uploadPipelineService.validateS3Configured,
this.uploadPipelineService.uploadPipeline().single('file'),
this.validateUploadedFileExistance,
this.uploadAttachment.bind(this)
);
router.delete(
'/:id',
[param('id').exists()],
this.validationResult,
this.deleteAttachment.bind(this)
);
router.get(
'/:id',
[param('id').exists()],
this.validationResult,
this.getAttachment.bind(this)
);
router.post(
'/:id/link',
[body('modelRef').exists(), body('modelId').exists()],
this.validationResult
);
router.post(
'/:id/link',
[body('modelRef').exists(), body('modelId').exists()],
this.validationResult,
this.linkDocument.bind(this)
);
router.post(
'/:id/unlink',
[body('modelRef').exists(), body('modelId').exists()],
this.validationResult,
this.unlinkDocument.bind(this)
);
router.get(
'/:id/presigned-url',
[param('id').exists()],
this.validationResult,
this.getAttachmentPresignedUrl.bind(this)
);
return router;
}
/**
* Validates the upload file existance.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Response|void}
*/
private validateUploadedFileExistance(
req: Request,
res: Response,
next: NextFunction
) {
if (!req.file) {
return res.boom.badRequest(null, {
errorType: 'FILE_UPLOAD_FAILED',
message: 'Now file uploaded.',
});
}
next();
}
/**
* Uploads the attachments to S3 and store the file metadata to DB.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Response|void}
*/
private async uploadAttachment(
req: Request,
res: Response,
next: NextFunction
): Promise<Response | void> {
const { tenantId } = req;
const file = req.file;
try {
const data = await this.attachmentsApplication.upload(tenantId, file);
return res.status(200).send({
status: 200,
message: 'The document has uploaded successfully.',
data,
});
} catch (error) {
next(error);
}
}
/**
* Retrieves the given attachment key.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response|void>}
*/
private async getAttachment(
req: Request,
res: Response,
next: NextFunction
): Promise<Response | void> {
const { tenantId } = req;
const { id } = req.params;
try {
const data = await this.attachmentsApplication.get(tenantId, id);
const byte = await data.Body.transformToByteArray();
const extension = mime.extension(data.ContentType);
const buffer = Buffer.from(byte);
res.set(
'Content-Disposition',
`filename="${req.params.id}.${extension}"`
);
res.set('Content-Type', data.ContentType);
res.send(buffer);
} catch (error) {
next(error);
}
}
/**
* Deletes the given document key.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response|void>}
*/
private async deleteAttachment(
req: Request,
res: Response,
next: NextFunction
): Promise<Response | void> {
const { tenantId } = req;
const { id: documentId } = req.params;
try {
await this.attachmentsApplication.delete(tenantId, documentId);
return res.status(200).send({
status: 200,
message: 'The document has been delete successfully.',
});
} catch (error) {
next(error);
}
}
/**
* Links the given document key.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response|void>}
*/
private async linkDocument(
req: Request,
res: Response,
next: Function
): Promise<Response | void> {
const { tenantId } = req;
const { id: documentId } = req.params;
const { modelRef, modelId } = this.matchedBodyData(req);
try {
await this.attachmentsApplication.link(
tenantId,
documentId,
modelRef,
modelId
);
return res.status(200).send({
status: 200,
message: 'The document has been linked successfully.',
});
} catch (error) {
next(error);
}
}
/**
* Links the given document key.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response|void>}
*/
private async unlinkDocument(
req: Request,
res: Response,
next: NextFunction
): Promise<Response | void> {
const { tenantId } = req;
const { id: documentId } = req.params;
const { modelRef, modelId } = this.matchedBodyData(req);
try {
await this.attachmentsApplication.link(
tenantId,
documentId,
modelRef,
modelId
);
return res.status(200).send({
status: 200,
message: 'The document has been linked successfully.',
});
} catch (error) {
next(error);
}
}
/**
* Retreives the presigned url of the given attachment key.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response|void>}
*/
private async getAttachmentPresignedUrl(
req: Request,
res: Response,
next: NextFunction
): Promise<Response | void> {
const { id: documentKey } = req.params;
try {
const presignedUrl = await this.attachmentsApplication.getPresignedUrl(
documentKey
);
return res.status(200).send({ presignedUrl });
} catch (error) {
next(error);
}
}
}

View File

@@ -0,0 +1,49 @@
import { Inject, Service } from 'typedi';
import { NextFunction, Request, Response, Router } from 'express';
import BaseController from '@/api/controllers/BaseController';
import { CashflowApplication } from '@/services/Cashflow/CashflowApplication';
import { GetBankAccountSummary } from '@/services/Banking/BankAccounts/GetBankAccountSummary';
@Service()
export class BankAccountsController extends BaseController {
@Inject()
private getBankAccountSummaryService: GetBankAccountSummary;
/**
* Router constructor.
*/
router() {
const router = Router();
router.get('/:bankAccountId/meta', this.getBankAccountSummary.bind(this));
return router;
}
/**
* Retrieves the bank account meta summary.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response|null>}
*/
async getBankAccountSummary(
req: Request<{ bankAccountId: number }>,
res: Response,
next: NextFunction
) {
const { bankAccountId } = req.params;
const { tenantId } = req;
try {
const data =
await this.getBankAccountSummaryService.getBankAccountSummary(
tenantId,
bankAccountId
);
return res.status(200).send({ data });
} catch (error) {
next(error);
}
}
}

View File

@@ -0,0 +1,103 @@
import { Inject, Service } from 'typedi';
import { NextFunction, Request, Response, Router } from 'express';
import BaseController from '@/api/controllers/BaseController';
import { MatchBankTransactionsApplication } from '@/services/Banking/Matching/MatchBankTransactionsApplication';
import { body, param } from 'express-validator';
import {
GetMatchedTransactionsFilter,
IMatchTransactionsDTO,
} from '@/services/Banking/Matching/types';
@Service()
export class BankTransactionsMatchingController extends BaseController {
@Inject()
private bankTransactionsMatchingApp: MatchBankTransactionsApplication;
/**
* Router constructor.
*/
public router() {
const router = Router();
router.post(
'/:transactionId',
[
param('transactionId').exists(),
body('matchedTransactions').isArray({ min: 1 }),
body('matchedTransactions.*.reference_type').exists(),
body('matchedTransactions.*.reference_id').isNumeric().toInt(),
],
this.validationResult,
this.matchBankTransaction.bind(this)
);
router.post(
'/unmatch/:transactionId',
[param('transactionId').exists()],
this.validationResult,
this.unmatchMatchedBankTransaction.bind(this)
);
return router;
}
/**
* Matches the given bank transaction.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response|null>}
*/
private async matchBankTransaction(
req: Request<{ transactionId: number }>,
res: Response,
next: NextFunction
) {
const { tenantId } = req;
const { transactionId } = req.params;
const matchTransactionDTO = this.matchedBodyData(
req
) as IMatchTransactionsDTO;
try {
await this.bankTransactionsMatchingApp.matchTransaction(
tenantId,
transactionId,
matchTransactionDTO
);
return res.status(200).send({
id: transactionId,
message: 'The bank transaction has been matched.',
});
} catch (error) {
next(error);
}
}
/**
* Unmatches the matched bank transaction.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response|null>}
*/
private async unmatchMatchedBankTransaction(
req: Request<{ transactionId: number }>,
res: Response,
next: NextFunction
) {
const { tenantId } = req;
const { transactionId } = req.params;
try {
await this.bankTransactionsMatchingApp.unmatchMatchedTransaction(
tenantId,
transactionId
);
return res.status(200).send({
id: transactionId,
message: 'The bank matched transaction has been unmatched.',
});
} catch (error) {
next(error);
}
}
}

View File

@@ -2,17 +2,33 @@ import Container, { Inject, Service } from 'typedi';
import { Router } from 'express';
import BaseController from '@/api/controllers/BaseController';
import { PlaidBankingController } from './PlaidBankingController';
import { BankingRulesController } from './BankingRulesController';
import { BankTransactionsMatchingController } from './BankTransactionsMatchingController';
import { RecognizedTransactionsController } from './RecognizedTransactionsController';
import { BankAccountsController } from './BankAccountsController';
@Service()
export class BankingController extends BaseController {
/**
* Router constructor.
*/
router() {
public router() {
const router = Router();
router.use('/plaid', Container.get(PlaidBankingController).router());
router.use('/rules', Container.get(BankingRulesController).router());
router.use(
'/matches',
Container.get(BankTransactionsMatchingController).router()
);
router.use(
'/recognized',
Container.get(RecognizedTransactionsController).router()
);
router.use(
'/bank_accounts',
Container.get(BankAccountsController).router()
);
return router;
}
}

View File

@@ -0,0 +1,206 @@
import { Inject, Service } from 'typedi';
import { NextFunction, Request, Response, Router } from 'express';
import BaseController from '@/api/controllers/BaseController';
import { BankRulesApplication } from '@/services/Banking/Rules/BankRulesApplication';
import { body, param } from 'express-validator';
import {
ICreateBankRuleDTO,
IEditBankRuleDTO,
} from '@/services/Banking/Rules/types';
@Service()
export class BankingRulesController extends BaseController {
@Inject()
private bankRulesApplication: BankRulesApplication;
/**
* Bank rule DTO validation schema.
*/
private get bankRuleValidationSchema() {
return [
body('name').isString().exists(),
body('order').isInt({ min: 0 }),
// Apply to if transaction is.
body('apply_if_account_id')
.isInt({ min: 0 })
.optional({ nullable: true }),
body('apply_if_transaction_type').isIn(['deposit', 'withdrawal']),
// Conditions
body('conditions_type').isString().isIn(['and', 'or']).default('and'),
body('conditions').isArray({ min: 1 }),
body('conditions.*.field').exists().isIn(['description', 'amount']),
body('conditions.*.comparator')
.exists()
.isIn(['equals', 'contains', 'not_contain'])
.default('contain'),
body('conditions.*.value').exists(),
// Assign
body('assign_category').isString(),
body('assign_account_id').isInt({ min: 0 }),
body('assign_payee').isString().optional({ nullable: true }),
body('assign_memo').isString().optional({ nullable: true }),
body('recognition').isBoolean().toBoolean().optional({ nullable: true }),
];
}
/**
* Router constructor.
*/
public router() {
const router = Router();
router.post(
'/',
[...this.bankRuleValidationSchema],
this.validationResult,
this.createBankRule.bind(this)
);
router.post(
'/:id',
[param('id').toInt().exists(), ...this.bankRuleValidationSchema],
this.validationResult,
this.editBankRule.bind(this)
);
router.delete(
'/:id',
[param('id').toInt().exists()],
this.validationResult,
this.deleteBankRule.bind(this)
);
router.get(
'/:id',
[param('id').toInt().exists()],
this.validationResult,
this.getBankRule.bind(this)
);
router.get(
'/',
[param('id').toInt().exists()],
this.validationResult,
this.getBankRules.bind(this)
);
return router;
}
/**
* Creates a new bank rule.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
private async createBankRule(
req: Request,
res: Response,
next: NextFunction
) {
const { tenantId } = req;
const createBankRuleDTO = this.matchedBodyData(req) as ICreateBankRuleDTO;
try {
const bankRule = await this.bankRulesApplication.createBankRule(
tenantId,
createBankRuleDTO
);
return res.status(200).send({
id: bankRule.id,
message: 'The bank rule has been created successfully.',
});
} catch (error) {
next(error);
}
}
/**
* Edits the given bank rule.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
private async editBankRule(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req;
const { id: ruleId } = req.params;
const editBankRuleDTO = this.matchedBodyData(req) as IEditBankRuleDTO;
try {
await this.bankRulesApplication.editBankRule(
tenantId,
ruleId,
editBankRuleDTO
);
return res.status(200).send({
id: ruleId,
message: 'The bank rule has been updated successfully.',
});
} catch (error) {
next(error);
}
}
/**
* Deletes the given bank rule.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
private async deleteBankRule(
req: Request<{ id: number }>,
res: Response,
next: NextFunction
) {
const { id: ruleId } = req.params;
const { tenantId } = req;
try {
await this.bankRulesApplication.deleteBankRule(tenantId, ruleId);
return res
.status(200)
.send({ message: 'The bank rule has been deleted.', id: ruleId });
} catch (error) {
next(error);
}
}
/**
* Retrieve the given bank rule.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
private async getBankRule(req: Request, res: Response, next: NextFunction) {
const { id: ruleId } = req.params;
const { tenantId } = req;
try {
const bankRule = await this.bankRulesApplication.getBankRule(
tenantId,
ruleId
);
return res.status(200).send({ bankRule });
} catch (error) {
next(error);
}
}
/**
* Retrieves the bank rules.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
private async getBankRules(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req;
try {
const bankRules = await this.bankRulesApplication.getBankRules(tenantId);
return res.status(200).send({ bankRules });
} catch (error) {
next(error);
}
}
}

View File

@@ -0,0 +1,124 @@
import { Inject, Service } from 'typedi';
import { param } from 'express-validator';
import { NextFunction, Request, Response, Router, query } from 'express';
import BaseController from '../BaseController';
import { ExcludeBankTransactionsApplication } from '@/services/Banking/Exclude/ExcludeBankTransactionsApplication';
@Service()
export class ExcludeBankTransactionsController extends BaseController {
@Inject()
private excludeBankTransactionApp: ExcludeBankTransactionsApplication;
/**
* Router constructor.
*/
public router() {
const router = Router();
router.put(
'/transactions/:transactionId/exclude',
[param('transactionId').exists()],
this.validationResult,
this.excludeBankTransaction.bind(this)
);
router.put(
'/transactions/:transactionId/unexclude',
[param('transactionId').exists()],
this.validationResult,
this.unexcludeBankTransaction.bind(this)
);
router.get(
'/excluded',
[],
this.validationResult,
this.getExcludedBankTransactions.bind(this)
);
return router;
}
/**
* Marks a bank transaction as excluded.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns
*/
private async excludeBankTransaction(
req: Request,
res: Response,
next: NextFunction
): Promise<Response | void> {
const { tenantId } = req;
const { transactionId } = req.params;
try {
await this.excludeBankTransactionApp.excludeBankTransaction(
tenantId,
transactionId
);
return res.status(200).send({
message: 'The bank transaction has been excluded.',
id: transactionId,
});
} catch (error) {
next(error);
}
}
/**
* Marks a bank transaction as not excluded.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response|void>}
*/
private async unexcludeBankTransaction(
req: Request,
res: Response,
next: NextFunction
): Promise<Response | void> {
const { tenantId } = req;
const { transactionId } = req.params;
try {
await this.excludeBankTransactionApp.unexcludeBankTransaction(
tenantId,
transactionId
);
return res.status(200).send({
message: 'The bank transaction has been unexcluded.',
id: transactionId,
});
} catch (error) {
next(error);
}
}
/**
* Retrieves the excluded uncategorized bank transactions.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response|null>}
*/
private async getExcludedBankTransactions(
req: Request,
res: Response,
next: NextFunction
): Promise<Response | void> {
const { tenantId } = req;
const filter = this.matchedBodyData(req);
console.log('123');
try {
const data =
await this.excludeBankTransactionApp.getExcludedBankTransactions(
tenantId,
filter
);
return res.status(200).send(data);
} catch (error) {
next(error);
}
}
}

View File

@@ -0,0 +1,77 @@
import { Inject, Service } from 'typedi';
import { NextFunction, Request, Response, Router } from 'express';
import BaseController from '@/api/controllers/BaseController';
import { CashflowApplication } from '@/services/Cashflow/CashflowApplication';
@Service()
export class RecognizedTransactionsController extends BaseController {
@Inject()
private cashflowApplication: CashflowApplication;
/**
* Router constructor.
*/
router() {
const router = Router();
router.get('/', this.getRecognizedTransactions.bind(this));
router.get(
'/transactions/:uncategorizedTransactionId',
this.getRecognizedTransaction.bind(this)
);
return router;
}
/**
* Retrieves the recognized bank transactions.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response|null>}
*/
async getRecognizedTransactions(
req: Request<{ accountId: number }>,
res: Response,
next: NextFunction
) {
const filter = this.matchedQueryData(req);
const { tenantId } = req;
try {
const data = await this.cashflowApplication.getRecognizedTransactions(
tenantId,
filter
);
return res.status(200).send(data);
} catch (error) {
next(error);
}
}
/**
* Retrieves the recognized transaction of the ginen uncategorized transaction.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<Response|null>}
*/
async getRecognizedTransaction(
req: Request<{ uncategorizedTransactionId: number }>,
res: Response,
next: NextFunction
) {
const { tenantId } = req;
const { uncategorizedTransactionId } = req.params;
try {
const data = await this.cashflowApplication.getRecognizedTransaction(
tenantId,
uncategorizedTransactionId
);
return res.status(200).send({ data });
} catch (error) {
next(error);
}
}
}

View File

@@ -4,6 +4,7 @@ import CommandCashflowTransaction from './NewCashflowTransaction';
import DeleteCashflowTransaction from './DeleteCashflowTransaction';
import GetCashflowTransaction from './GetCashflowTransaction';
import GetCashflowAccounts from './GetCashflowAccounts';
import { ExcludeBankTransactionsController } from '../Banking/ExcludeBankTransactionsController';
@Service()
export default class CashflowController {
@@ -14,6 +15,7 @@ export default class CashflowController {
const router = Router();
router.use(Container.get(CommandCashflowTransaction).router());
router.use(Container.get(ExcludeBankTransactionsController).router());
router.use(Container.get(GetCashflowTransaction).router());
router.use(Container.get(GetCashflowAccounts).router());
router.use(Container.get(DeleteCashflowTransaction).router());

View File

@@ -31,7 +31,6 @@ export default class GetCashflowAccounts extends BaseController {
query('search_keyword').optional({ nullable: true }).isString().trim(),
],
this.asyncMiddleware(this.getCashflowAccounts),
this.catchServiceErrors
);
return router;
}
@@ -67,22 +66,4 @@ export default class GetCashflowAccounts extends BaseController {
next(error);
}
};
/**
* Catches the service errors.
* @param {Error} error - Error.
* @param {Request} req - Request.
* @param {Response} res - Response.
* @param {NextFunction} next -
*/
private catchServiceErrors(
error,
req: Request,
res: Response,
next: NextFunction
) {
if (error instanceof ServiceError) {
}
next(error);
}
}

View File

@@ -6,18 +6,27 @@ import { ServiceError } from '@/exceptions';
import CheckPolicies from '@/api/middleware/CheckPolicies';
import { AbilitySubject, CashflowAction } from '@/interfaces';
import { CashflowApplication } from '@/services/Cashflow/CashflowApplication';
import { GetMatchedTransactionsFilter } from '@/services/Banking/Matching/types';
import { MatchBankTransactionsApplication } from '@/services/Banking/Matching/MatchBankTransactionsApplication';
@Service()
export default class GetCashflowAccounts extends BaseController {
@Inject()
private cashflowApplication: CashflowApplication;
@Inject()
private bankTransactionsMatchingApp: MatchBankTransactionsApplication;
/**
* Controller router.
*/
public router() {
const router = Router();
router.get(
'/transactions/:transactionId/matches',
this.getMatchedTransactions.bind(this)
);
router.get(
'/transactions/:transactionId',
CheckPolicies(CashflowAction.View, AbilitySubject.Cashflow),
@@ -47,7 +56,6 @@ export default class GetCashflowAccounts extends BaseController {
tenantId,
transactionId
);
return res.status(200).send({
cashflow_transaction: this.transfromToResponse(cashflowTransaction),
});
@@ -56,6 +64,34 @@ export default class GetCashflowAccounts extends BaseController {
}
};
/**
* Retrieves the matched transactions.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
private async getMatchedTransactions(
req: Request<{ transactionId: number }>,
res: Response,
next: NextFunction
) {
const { tenantId } = req;
const { transactionId } = req.params;
const filter = this.matchedQueryData(req) as GetMatchedTransactionsFilter;
try {
const data =
await this.bankTransactionsMatchingApp.getMatchedTransactions(
tenantId,
transactionId,
filter
);
return res.status(200).send(data);
} catch (error) {
next(error);
}
}
/**
* Catches the service errors.
* @param {Error} error - Error.

View File

@@ -5,7 +5,7 @@ import DashboardService from '@/services/Dashboard/DashboardService';
@Service()
export default class DashboardMetaController {
@Inject()
dashboardService: DashboardService;
private dashboardService: DashboardService;
/**
* Constructor router.

View File

@@ -84,7 +84,7 @@ export class ExpensesController extends BaseController {
/**
* Expense DTO schema.
*/
get expenseDTOSchema() {
private get expenseDTOSchema() {
return [
check('reference_no')
.optional({ nullable: true })
@@ -130,6 +130,9 @@ export class ExpensesController extends BaseController {
.optional({ nullable: true })
.isInt({ max: DATATYPES_LENGTH.INT_10 })
.toInt(),
check('attachments').isArray().optional(),
check('attachments.*.key').exists().isString(),
];
}
@@ -183,6 +186,9 @@ export class ExpensesController extends BaseController {
.optional({ nullable: true })
.isInt({ max: DATATYPES_LENGTH.INT_10 })
.toInt(),
check('attachments').isArray().optional(),
check('attachments.*.key').exists().isString(),
];
}
@@ -269,7 +275,7 @@ export class ExpensesController extends BaseController {
* @param {Response} res
* @param {NextFunction} next
*/
async deleteExpense(req: Request, res: Response, next: NextFunction) {
private async deleteExpense(req: Request, res: Response, next: NextFunction) {
const { tenantId, user } = req;
const { id: expenseId } = req.params;
@@ -291,7 +297,11 @@ export class ExpensesController extends BaseController {
* @param {Response} res
* @param {NextFunction} next
*/
async publishExpense(req: Request, res: Response, next: NextFunction) {
private async publishExpense(
req: Request,
res: Response,
next: NextFunction
) {
const { tenantId, user } = req;
const { id: expenseId } = req.params;
@@ -313,7 +323,11 @@ export class ExpensesController extends BaseController {
* @param {Response} res
* @param {NextFunction} next
*/
async getExpensesList(req: Request, res: Response, next: NextFunction) {
private async getExpensesList(
req: Request,
res: Response,
next: NextFunction
) {
const { tenantId } = req;
const filter = {
sortOrder: 'desc',
@@ -343,7 +357,7 @@ export class ExpensesController extends BaseController {
* @param {Response} res
* @param {NextFunction} next
*/
async getExpense(req: Request, res: Response, next: NextFunction) {
private async getExpense(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req;
const { id: expenseId } = req.params;

View File

@@ -5,6 +5,7 @@ import BaseController from '@/api/controllers/BaseController';
import { ServiceError } from '@/exceptions';
import { ExportApplication } from '@/services/Export/ExportApplication';
import { ACCEPT_TYPE } from '@/interfaces/Http';
import { convertAcceptFormatToFormat } from './_utils';
@Service()
export class ExportController extends BaseController {
@@ -14,7 +15,7 @@ export class ExportController extends BaseController {
/**
* Router constructor method.
*/
router() {
public router() {
const router = Router();
router.get(
@@ -25,7 +26,6 @@ export class ExportController extends BaseController {
],
this.validationResult,
this.export.bind(this),
this.catchServiceErrors
);
return router;
}
@@ -48,11 +48,14 @@ export class ExportController extends BaseController {
ACCEPT_TYPE.APPLICATION_CSV,
ACCEPT_TYPE.APPLICATION_PDF,
]);
const applicationFormat = convertAcceptFormatToFormat(acceptType);
const data = await this.exportResourceApp.export(
tenantId,
query.resource,
acceptType === ACCEPT_TYPE.APPLICATION_XLSX ? 'xlsx' : 'csv'
applicationFormat
);
// Retrieves the csv format.
if (ACCEPT_TYPE.APPLICATION_CSV === acceptType) {
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
res.setHeader('Content-Type', 'text/csv');
@@ -69,31 +72,16 @@ export class ExportController extends BaseController {
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
);
return res.send(data);
//
} else if (ACCEPT_TYPE.APPLICATION_PDF === acceptType) {
res.set({
'Content-Type': 'application/pdf',
'Content-Length': data.length,
});
res.send(data);
}
} catch (error) {
next(error);
}
}
/**
* Transforms service errors to response.
* @param {Error}
* @param {Request} req
* @param {Response} res
* @param {ServiceError} error
*/
private catchServiceErrors(
error,
req: Request,
res: Response,
next: NextFunction
) {
if (error instanceof ServiceError) {
return res.status(400).send({
errors: [{ type: error.errorType }],
});
}
next(error);
}
}

View File

@@ -0,0 +1,13 @@
import { ACCEPT_TYPE } from '@/interfaces/Http';
import { ExportFormat } from '@/services/Export/common';
export const convertAcceptFormatToFormat = (accept: string): ExportFormat => {
switch (accept) {
case ACCEPT_TYPE.APPLICATION_CSV:
return ExportFormat.Csv;
case ACCEPT_TYPE.APPLICATION_PDF:
return ExportFormat.Pdf;
case ACCEPT_TYPE.APPLICATION_XLSX:
return ExportFormat.Xlsx;
}
};

View File

@@ -16,7 +16,7 @@ export class ImportController extends BaseController {
/**
* Router constructor method.
*/
router() {
public router() {
const router = Router();
router.post(
@@ -240,11 +240,7 @@ export class ImportController extends BaseController {
errors: [{ type: 'IMPORTED_FILE_EXTENSION_INVALID' }],
});
}
return res.status(400).send({
errors: [{ type: error.errorType }],
});
}
next(error);
}
}

View File

@@ -77,14 +77,14 @@ export default class ManualJournalsController extends BaseController {
/**
* Specific manual journal id param validation schema.
*/
get manualJournalParamSchema() {
private get manualJournalParamSchema() {
return [param('id').exists().isNumeric().toInt()];
}
/**
* Manual journal DTO schema.
*/
get manualJournalValidationSchema() {
private get manualJournalValidationSchema() {
return [
check('date').exists().isISO8601(),
check('currency_code').optional(),
@@ -148,13 +148,16 @@ export default class ManualJournalsController extends BaseController {
.optional({ nullable: true })
.isNumeric()
.toInt(),
check('attachments').isArray().optional(),
check('attachments.*.key').exists().isString(),
];
}
/**
* Manual journals list validation schema.
*/
get manualJournalsListSchema() {
private get manualJournalsListSchema() {
return [
query('page').optional().isNumeric().toInt(),
query('page_size').optional().isNumeric().toInt(),
@@ -320,7 +323,7 @@ export default class ManualJournalsController extends BaseController {
* @param {Response} res
* @param {NextFunction} next
*/
getManualJournalsList = async (
private getManualJournalsList = async (
req: Request,
res: Response,
next: NextFunction

View File

@@ -33,17 +33,17 @@ export default class OrganizationDashboardController extends BaseController {
}
/**
*
* @param req
* @param res
* @param next
* @returns
* Detarmines whether the current authed organization to able to change its currency/.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Response|void}
*/
private async baseCurrencyMutateAbility(
req: Request,
res: Response,
next: Function
) {
): Promise<Response|void> {
const { tenantId } = req;
try {

View File

@@ -29,8 +29,7 @@ export class ProjectsController extends BaseController {
check('cost_estimate').exists().isDecimal(),
],
this.validationResult,
asyncMiddleware(this.createProject.bind(this)),
this.catchServiceErrors
asyncMiddleware(this.createProject.bind(this))
);
router.post(
'/:id',
@@ -43,8 +42,7 @@ export class ProjectsController extends BaseController {
check('cost_estimate').exists().isDecimal(),
],
this.validationResult,
asyncMiddleware(this.editProject.bind(this)),
this.catchServiceErrors
asyncMiddleware(this.editProject.bind(this))
);
router.patch(
'/:projectId/status',
@@ -56,16 +54,14 @@ export class ProjectsController extends BaseController {
.isIn([IProjectStatus.InProgress, IProjectStatus.Closed]),
],
this.validationResult,
asyncMiddleware(this.editProject.bind(this)),
this.catchServiceErrors
asyncMiddleware(this.editProject.bind(this))
);
router.get(
'/:id',
CheckPolicies(ProjectAction.VIEW, AbilitySubject.Project),
[param('id').exists().isInt().toInt()],
this.validationResult,
asyncMiddleware(this.getProject.bind(this)),
this.catchServiceErrors
asyncMiddleware(this.getProject.bind(this))
);
router.get(
'/:projectId/billable/entries',
@@ -76,24 +72,21 @@ export class ProjectsController extends BaseController {
query('to_date').optional().isISO8601(),
],
this.validationResult,
asyncMiddleware(this.projectBillableEntries.bind(this)),
this.catchServiceErrors
asyncMiddleware(this.projectBillableEntries.bind(this))
);
router.get(
'/',
CheckPolicies(ProjectAction.VIEW, AbilitySubject.Project),
[],
this.validationResult,
asyncMiddleware(this.getProjects.bind(this)),
this.catchServiceErrors
asyncMiddleware(this.getProjects.bind(this))
);
router.delete(
'/:id',
CheckPolicies(ProjectAction.DELETE, AbilitySubject.Project),
[param('id').exists().isInt().toInt()],
this.validationResult,
asyncMiddleware(this.deleteProject.bind(this)),
this.catchServiceErrors
asyncMiddleware(this.deleteProject.bind(this))
);
return router;
}
@@ -252,22 +245,4 @@ export class ProjectsController extends BaseController {
next(error);
}
};
/**
* Transforms service errors to response.
* @param {Error}
* @param {Request} req
* @param {Response} res
* @param {ServiceError} error
*/
private catchServiceErrors(
error,
req: Request,
res: Response,
next: NextFunction
) {
if (error instanceof ServiceError) {
}
next(error);
}
}

View File

@@ -118,7 +118,6 @@ export default class BillsController extends BaseController {
check('is_inclusive_tax').default(false).isBoolean().toBoolean(),
check('entries').isArray({ min: 1 }),
check('entries.*.index').exists().isNumeric().toInt(),
check('entries.*.item_id').exists().isNumeric().toInt(),
check('entries.*.rate').exists().isNumeric().toFloat(),
@@ -148,6 +147,9 @@ export default class BillsController extends BaseController {
.optional({ nullable: true })
.isNumeric()
.toInt(),
check('attachments').isArray().optional(),
check('attachments.*.key').exists().isString(),
];
}
@@ -190,6 +192,9 @@ export default class BillsController extends BaseController {
.optional({ nullable: true })
.isBoolean()
.toBoolean(),
check('attachments').isArray().optional(),
check('attachments.*.key').exists().isString(),
];
}

View File

@@ -111,6 +111,7 @@ export default class BillsPayments extends BaseController {
check('vendor_id').exists().isNumeric().toInt(),
check('exchange_rate').optional().isFloat({ gt: 0 }).toFloat(),
check('amount').exists().isNumeric().toFloat(),
check('payment_account_id').exists().isNumeric().toInt(),
check('payment_number').optional({ nullable: true }).trim().escape(),
check('payment_date').exists(),
@@ -118,10 +119,13 @@ export default class BillsPayments extends BaseController {
check('reference').optional().trim().escape(),
check('branch_id').optional({ nullable: true }).isNumeric().toInt(),
check('entries').exists().isArray({ min: 1 }),
check('entries').exists().isArray(),
check('entries.*.index').optional().isNumeric().toInt(),
check('entries.*.bill_id').exists().isNumeric().toInt(),
check('entries.*.payment_amount').exists().isNumeric().toFloat(),
check('attachments').isArray().optional(),
check('attachments.*.key').exists().isString(),
];
}

View File

@@ -186,6 +186,9 @@ export default class VendorCreditController extends BaseController {
.optional({ nullable: true })
.isNumeric()
.toInt(),
check('attachments').isArray().optional(),
check('attachments.*.key').exists().isString(),
];
}
@@ -228,6 +231,9 @@ export default class VendorCreditController extends BaseController {
.optional({ nullable: true })
.isNumeric()
.toInt(),
check('attachments').isArray().optional(),
check('attachments.*.key').exists().isString(),
];
}

View File

@@ -236,6 +236,9 @@ export default class PaymentReceivesController extends BaseController {
.optional({ nullable: true })
.isNumeric()
.toInt(),
check('attachments').isArray().optional(),
check('attachments.*.key').exists().isString(),
];
}

View File

@@ -150,6 +150,7 @@ export default class PaymentReceivesController extends BaseController {
check('customer_id').exists().isNumeric().toInt(),
check('exchange_rate').optional().isFloat({ gt: 0 }).toFloat(),
check('amount').exists().isNumeric().toFloat(),
check('payment_date').exists(),
check('reference_no').optional(),
check('deposit_account_id').exists().isNumeric().toInt(),
@@ -158,12 +159,14 @@ export default class PaymentReceivesController extends BaseController {
check('branch_id').optional({ nullable: true }).isNumeric().toInt(),
check('entries').isArray({ min: 1 }),
check('entries').isArray({}),
check('entries.*.id').optional({ nullable: true }).isNumeric().toInt(),
check('entries.*.index').optional().isNumeric().toInt(),
check('entries.*.invoice_id').exists().isNumeric().toInt(),
check('entries.*.payment_amount').exists().isNumeric().toFloat(),
check('attachments').isArray().optional(),
check('attachments.*.key').exists().isString(),
];
}

View File

@@ -184,6 +184,9 @@ export default class SalesEstimatesController extends BaseController {
check('note').optional().trim().escape(),
check('terms_conditions').optional().trim().escape(),
check('send_to_email').optional().trim().escape(),
check('attachments').isArray().optional(),
check('attachments.*.key').exists().isString(),
];
}

View File

@@ -36,6 +36,8 @@ export default class SaleInvoicesController extends BaseController {
[
...this.saleInvoiceValidationSchema,
check('from_estimate_id').optional().isNumeric().toInt(),
check('attachments').isArray().optional(),
check('attachments.*.key').exists().isString(),
],
this.validationResult,
asyncMiddleware(this.newSaleInvoice.bind(this)),
@@ -98,6 +100,8 @@ export default class SaleInvoicesController extends BaseController {
[
...this.saleInvoiceValidationSchema,
...this.specificSaleInvoiceValidation,
check('attachments').isArray().optional(),
check('attachments.*.key').exists().isString(),
],
this.validationResult,
asyncMiddleware(this.editSaleInvoice.bind(this)),

View File

@@ -158,6 +158,8 @@ export default class SalesReceiptsController extends BaseController {
.toInt(),
check('receipt_message').optional().trim().escape(),
check('statement').optional().trim().escape(),
check('attachments').isArray().optional(),
check('attachments.*.key').exists().isString(),
];
}

View File

@@ -155,6 +155,7 @@ export default class UsersController extends BaseController {
try {
const user = await this.usersService.getUser(tenantId, userId);
return res.status(200).send({ user });
} catch (error) {
next(error);
@@ -229,7 +230,7 @@ export default class UsersController extends BaseController {
* @param {Response} res
* @param {NextFunction} next
*/
catchServiceErrors(
private catchServiceErrors(
error: Error,
req: Request,
res: Response,

View File

@@ -17,7 +17,7 @@ export class WarehousesController extends BaseController {
*
* @returns
*/
router() {
public router() {
const router = Router();
router.post(

View File

@@ -1,7 +1,6 @@
import { Router } from 'express';
import { PlaidApplication } from '@/services/Banking/Plaid/PlaidApplication';
import { Request, Response } from 'express';
import { NextFunction, Router, Request, Response } from 'express';
import { Inject, Service } from 'typedi';
import { PlaidApplication } from '@/services/Banking/Plaid/PlaidApplication';
import BaseController from '../BaseController';
import { LemonSqueezyWebhooks } from '@/services/Subscription/LemonSqueezyWebhooks';
import { PlaidWebhookTenantBootMiddleware } from '@/services/Banking/Plaid/PlaidWebhookTenantBootMiddleware';
@@ -34,14 +33,21 @@ export class Webhooks extends BaseController {
* @param {Response} res
* @returns {Response}
*/
public async lemonWebhooks(req: Request, res: Response) {
public async lemonWebhooks(req: Request, res: Response, next: NextFunction) {
const data = req.body;
const signature = req.headers['x-signature'] ?? '';
const rawBody = req.rawBody;
await this.lemonWebhooksService.handlePostWebhook(rawBody, data, signature);
return res.status(200).send();
try {
await this.lemonWebhooksService.handlePostWebhook(
rawBody,
data,
signature
);
return res.status(200).send();
} catch (error) {
next(error);
}
}
/**
@@ -50,20 +56,25 @@ export class Webhooks extends BaseController {
* @param {Response} res
* @returns {Response}
*/
public async plaidWebhooks(req: Request, res: Response) {
public async plaidWebhooks(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req;
const {
webhook_type: webhookType,
webhook_code: webhookCode,
item_id: plaidItemId,
} = req.body;
await this.plaidApp.webhooks(
tenantId,
plaidItemId,
webhookType,
webhookCode
);
return res.status(200).send({ code: 200, message: 'ok' });
try {
const {
webhook_type: webhookType,
webhook_code: webhookCode,
item_id: plaidItemId,
} = req.body;
await this.plaidApp.webhooks(
tenantId,
plaidItemId,
webhookType,
webhookCode
);
return res.status(200).send({ code: 200, message: 'ok' });
} catch (error) {
next(error);
}
}
}

View File

@@ -0,0 +1,20 @@
import { Request, Response, NextFunction } from 'express';
/**
* Global error handler.
* @param {Error} err
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
export function GlobalErrorException(
err: Error,
req: Request,
res: Response,
next: NextFunction
) {
console.error(err.stack);
res.status(500);
res.boom.badImplementation('', { stack: err.stack });
}

View File

@@ -10,8 +10,14 @@ import {
DataError,
} from 'objection';
// In this example `res` is an express response object.
export default function ObjectionErrorHandlerMiddleware(
/**
* Handles the Objection error exception.
* @param {Error} err
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
export function ObjectionErrorException(
err: Error,
req: Request,
res: Response,
@@ -108,6 +114,7 @@ export default function ObjectionErrorHandlerMiddleware(
type: 'UnknownDatabaseError',
data: {},
});
} else {
next(err);
}
next(err);
}

View File

@@ -0,0 +1,25 @@
import { NextFunction, Request, Response } from 'express';
import { ServiceError } from '@/exceptions';
/**
* Handles service error exception.
* @param {Error | ServiceError} err
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
export function ServiceErrorException(
err: Error | ServiceError,
req: Request,
res: Response,
next: NextFunction
) {
if (err instanceof ServiceError) {
res.boom.badRequest('', {
errors: [{ type: err.errorType, message: err.message }],
type: 'ServiceError',
});
} else {
next(err);
}
}

View File

@@ -62,6 +62,7 @@ import { ImportController } from './controllers/Import/ImportController';
import { BankingController } from './controllers/Banking/BankingController';
import { Webhooks } from './controllers/Webhooks/Webhooks';
import { ExportController } from './controllers/Export/ExportController';
import { AttachmentsController } from './controllers/Attachments/AttachmentsController';
export default () => {
const app = Router();
@@ -142,7 +143,8 @@ export default () => {
dashboard.use('/projects', Container.get(ProjectsController).router());
dashboard.use('/tax-rates', Container.get(TaxRatesController).router());
dashboard.use('/import', Container.get(ImportController).router());
dashboard.use('/export', Container.get(ExportController).router())
dashboard.use('/export', Container.get(ExportController).router());
dashboard.use('/attachments', Container.get(AttachmentsController).router());
dashboard.use('/', Container.get(ProjectTasksController).router());
dashboard.use('/', Container.get(ProjectTimesController).router());

View File

@@ -4,6 +4,7 @@ import color from 'colorette';
import argv from 'getopts';
import Knex from 'knex';
import { knexSnakeCaseMappers } from 'objection';
import { PromisePool } from '@supercharge/promise-pool';
import '../before';
import config from '../config';
@@ -28,7 +29,7 @@ function initSystemKnex() {
});
}
function initTenantKnex(organizationId) {
function initTenantKnex(organizationId: string = '') {
return Knex({
client: config.tenant.db_client,
connection: {
@@ -71,6 +72,12 @@ function getAllSystemTenants(knex) {
return knex('tenants');
}
function getAllInitializedTenants(knex) {
return knex('tenants').whereNotNull('initializedAt');
}
const MIGRATION_CONCURRENCY = 10;
// module.exports = {
// log,
// success,
@@ -87,6 +94,7 @@ function getAllSystemTenants(knex) {
// - bigcapital tenants:migrate:make
// - bigcapital system:migrate:make
// - bigcapital tenants:list
// - bigcapital tenants:list --all
commander
.command('system:migrate:rollback')
@@ -145,10 +153,13 @@ commander
commander
.command('tenants:list')
.description('Retrieve a list of all system tenants databases.')
.option('-a, --all', 'All tenants even are not initialized.')
.action(async (cmd) => {
try {
const sysKnex = await initSystemKnex();
const tenants = await getAllSystemTenants(sysKnex);
const tenants = cmd?.all
? await getAllSystemTenants(sysKnex)
: await getAllInitializedTenants(sysKnex);
tenants.forEach((tenant) => {
const dbName = `${config.tenant.db_name_prefix}${tenant.organizationId}`;
@@ -179,18 +190,20 @@ commander
commander
.command('tenants:migrate:latest')
.description('Migrate all tenants or the given tenant id.')
.option('-t, --tenant_id [tenant_id]', 'Which tenant id do you migrate.')
.option(
'-t, --tenant_id [tenant_id]',
'Which organization id do you migrate.'
)
.action(async (cmd) => {
try {
const sysKnex = await initSystemKnex();
const tenants = await getAllSystemTenants(sysKnex);
const tenants = await getAllInitializedTenants(sysKnex);
const tenantsOrgsIds = tenants.map((tenant) => tenant.organizationId);
if (cmd.tenant_id && tenantsOrgsIds.indexOf(cmd.tenant_id) === -1) {
exit(`The given tenant id ${cmd.tenant_id} is not exists.`);
}
// Validate the tenant id exist first of all.
const migrateOpers = [];
const migrateTenant = async (organizationId) => {
try {
const tenantKnex = await initTenantKnex(organizationId);
@@ -212,18 +225,17 @@ commander
}
};
if (!cmd.tenant_id) {
tenants.forEach((tenant) => {
const oper = migrateTenant(tenant.organizationId);
migrateOpers.push(oper);
});
await PromisePool.withConcurrency(MIGRATION_CONCURRENCY)
.for(tenants)
.process((tenant, index, pool) => {
return migrateTenant(tenant.organizationId);
})
.then(() => {
success('All tenants are migrated.');
});
} else {
const oper = migrateTenant(cmd.tenant_id);
migrateOpers.push(oper);
await migrateTenant(cmd.tenant_id);
}
Promise.all(migrateOpers).then(() => {
success('All tenants are migrated.');
});
} catch (error) {
exit(error);
}
@@ -232,19 +244,21 @@ commander
commander
.command('tenants:migrate:rollback')
.description('Rollback the last batch of tenants migrations.')
.option('-t, --tenant_id [tenant_id]', 'Which tenant id do you migrate.')
.option(
'-t, --tenant_id [tenant_id]',
'Which organization id do you migrate.'
)
.action(async (cmd) => {
try {
const sysKnex = await initSystemKnex();
const tenants = await getAllSystemTenants(sysKnex);
const tenants = await getAllInitializedTenants(sysKnex);
const tenantsOrgsIds = tenants.map((tenant) => tenant.organizationId);
if (cmd.tenant_id && tenantsOrgsIds.indexOf(cmd.tenant_id) === -1) {
exit(`The given tenant id ${cmd.tenant_id} is not exists.`);
}
const migrateOpers = [];
const migrateTenant = async (organizationId) => {
const migrateTenant = async (organizationId: string) => {
try {
const tenantKnex = await initTenantKnex(organizationId);
const [batchNo, _log] = await tenantKnex.migrate.rollback();
@@ -265,19 +279,18 @@ commander
};
if (!cmd.tenant_id) {
tenants.forEach((tenant) => {
const oper = migrateTenant(tenant.organizationId);
migrateOpers.push(oper);
});
await PromisePool.withConcurrency(MIGRATION_CONCURRENCY)
.for(tenants)
.process((tenant, index, pool) => {
return migrateTenant(tenant.organizationId);
})
.then(() => {
success('All tenants are rollbacked.');
});
} else {
const oper = migrateTenant(cmd.tenant_id);
migrateOpers.push(oper);
await migrateTenant(cmd.tenant_id);
}
Promise.all(migrateOpers).then(() => {
success('All tenants are rollbacked.');
});
} catch (error) {
exit(error);
}
});

View File

@@ -157,7 +157,10 @@ module.exports = {
* Sign-up email confirmation
*/
signupConfirmation: {
enabled: parseBoolean<boolean>(process.env.SIGNUP_EMAIL_CONFIRMATION, false),
enabled: parseBoolean<boolean>(
process.env.SIGNUP_EMAIL_CONFIRMATION,
false
),
},
/**
@@ -201,10 +204,7 @@ module.exports = {
plaid: {
env: process.env.PLAID_ENV || 'sandbox',
clientId: process.env.PLAID_CLIENT_ID,
secretDevelopment: process.env.PLAID_SECRET_DEVELOPMENT,
secretSandbox: process.env.PLAID_SECRET_SANDBOX,
redirectSandBox: process.env.PLAID_SANDBOX_REDIRECT_URI,
redirectDevelopment: process.env.PLAID_DEVELOPMENT_REDIRECT_URI,
secret: process.env.PLAID_SECRET,
linkWebhook: process.env.PLAID_LINK_WEBHOOK,
},
@@ -215,6 +215,7 @@ module.exports = {
key: process.env.LEMONSQUEEZY_API_KEY,
storeId: process.env.LEMONSQUEEZY_STORE_ID,
webhookSecret: process.env.LEMONSQUEEZY_WEBHOOK_SECRET,
redirectTo: `${process.env.BASE_URL}/setup`,
},
/**
@@ -225,4 +226,19 @@ module.exports = {
defaultTo(process.env.HOSTED_ON_BIGCAPITAL_CLOUD, false),
false
),
/**
* S3 for documents.
*/
s3: {
region: process.env.S3_REGION,
accessKeyId: process.env.S3_ACCESS_KEY_ID,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
endpoint: process.env.S3_ENDPOINT,
bucket: process.env.S3_BUCKET || 'bigcapital-documents',
},
loops: {
apiKey: process.env.LOOPS_API_KEY,
},
};

View File

@@ -1,7 +1,16 @@
export const CashflowTransactionTypes = {
OtherIncome: 'Other income',
OtherExpense: 'Other expense',
OwnerDrawing: 'Owner drawing',
OwnerContribution: 'Owner contribution',
TransferToAccount: 'Transfer to account',
TransferFromAccount: 'Transfer from account',
};
export const TransactionTypes = {
SaleInvoice: 'Sale invoice',
SaleReceipt: 'Sale receipt',
PaymentReceive: 'Payment receive',
PaymentReceive: 'Payment received',
Bill: 'Bill',
BillPayment: 'Payment made',
VendorOpeningBalance: 'Vendor opening balance',
@@ -17,12 +26,10 @@ export const TransactionTypes = {
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',
LandedCost: 'transaction_type.landed_cost',
CashflowTransaction: CashflowTransactionTypes,
};

View File

@@ -11,4 +11,4 @@ exports.up = function (knex) {
exports.down = function (knex) {
return knex.schema.dropTableIfExists('storage');
};
};

View File

@@ -0,0 +1,5 @@
exports.up = function (knex) {
return knex.schema.dropTableIfExists('storage');
};
exports.down = function (knex) {};

View File

@@ -0,0 +1,14 @@
exports.up = function (knex) {
return knex.schema.createTable('documents', (table) => {
table.increments('id').primary();
table.string('key').notNullable();
table.string('mime_type').notNullable();
table.integer('size').unsigned();
table.string('origin_name');
table.timestamps();
});
};
exports.down = function (knex) {
return knex.schema.dropTableIfExists('documents');
};

View File

@@ -0,0 +1,14 @@
exports.up = function (knex) {
return knex.schema.createTable('document_links', (table) => {
table.increments('id').primary();
table.string('model_ref').notNullable();
table.string('model_id').notNullable();
table.integer('document_id').unsigned();
table.datetime('expires_at').nullable();
table.timestamps();
});
};
exports.down = function (knex) {
return knex.schema.dropTableIfExists('document_links');
};

View File

@@ -0,0 +1,45 @@
exports.up = function (knex) {
return knex.schema
.createTable('bank_rules', (table) => {
table.increments('id').primary();
table.string('name');
table.integer('order').unsigned();
table
.integer('apply_if_account_id')
.unsigned()
.references('id')
.inTable('accounts');
table.string('apply_if_transaction_type');
table.string('assign_category');
table
.integer('assign_account_id')
.unsigned()
.references('id')
.inTable('accounts');
table.string('assign_payee');
table.string('assign_memo');
table.string('conditions_type');
table.timestamps();
})
.createTable('bank_rule_conditions', (table) => {
table.increments('id').primary();
table
.integer('rule_id')
.unsigned()
.references('id')
.inTable('bank_rules');
table.string('field');
table.string('comparator');
table.string('value');
});
};
exports.down = function (knex) {
return knex.schema
.dropTableIfExists('bank_rules')
.dropTableIfExists('bank_rule_conditions');
};

View File

@@ -0,0 +1,31 @@
exports.up = function (knex) {
return knex.schema.createTable('recognized_bank_transactions', (table) => {
table.increments('id');
table
.integer('uncategorized_transaction_id')
.unsigned()
.references('id')
.inTable('uncategorized_cashflow_transactions')
.withKeyName('recognizedBankTransactionsUncategorizedTransIdForeign');
table
.integer('bank_rule_id')
.unsigned()
.references('id')
.inTable('bank_rules');
table.string('assigned_category');
table
.integer('assigned_account_id')
.unsigned()
.references('id')
.inTable('accounts');
table.string('assigned_payee');
table.string('assigned_memo');
table.timestamps();
});
};
exports.down = function (knex) {
return knex.schema.dropTableIfExists('recognized_bank_transactions');
};

View File

@@ -0,0 +1,16 @@
exports.up = function (knex) {
return knex.schema.table('uncategorized_cashflow_transactions', (table) => {
table
.integer('recognized_transaction_id')
.unsigned()
.references('id')
.inTable('recognized_bank_transactions')
.withKeyName('uncategorizedCashflowTransRecognizedTranIdForeign');
});
};
exports.down = function (knex) {
return knex.schema.table('uncategorized_cashflow_transactions', (table) => {
table.dropColumn('recognized_transaction_id');
});
};

View File

@@ -0,0 +1,18 @@
exports.up = function (knex) {
return knex.schema.createTable('matched_bank_transactions', (table) => {
table.increments('id');
table
.integer('uncategorized_transaction_id')
.unsigned()
.references('id')
.inTable('uncategorized_cashflow_transactions');
table.string('reference_type');
table.integer('reference_id').unsigned();
table.decimal('amount');
table.timestamps();
});
};
exports.down = function (knex) {
return knex.schema.dropTableIfExists('matched_bank_transactions');
};

View File

@@ -0,0 +1,11 @@
exports.up = function (knex) {
return knex.schema.table('uncategorized_cashflow_transactions', (table) => {
table.datetime('excluded_at');
});
};
exports.down = function (knex) {
return knex.schema.table('uncategorized_cashflow_transactions', (table) => {
table.dropColumn('excluded_at');
});
};

View File

@@ -0,0 +1,11 @@
exports.up = function (knex) {
return knex.schema.table('uncategorized_cashflow_transactions', (table) => {
table.string('batch');
});
};
exports.down = function (knex) {
return knex.schema.table('uncategorized_cashflow_transactions', (table) => {
table.dropColumn('batch');
});
};

View File

@@ -0,0 +1,11 @@
exports.up = function (knex) {
return knex.schema.table('settings', (table) => {
table.text('value').alter();
});
};
exports.down = (knex) => {
return knex.schema.table('settings', (table) => {
table.string('value').alter();
});
};

View File

@@ -0,0 +1,60 @@
exports.up = function (knex) {
return knex('accounts_transactions')
.whereIn('referenceType', [
'OtherIncome',
'OtherExpense',
'OwnerDrawing',
'OwnerContribution',
'TransferToAccount',
'TransferFromAccount',
])
.update({
transactionType: knex.raw(`
CASE
WHEN REFERENCE_TYPE = 'OtherIncome' THEN 'OtherIncome'
WHEN REFERENCE_TYPE = 'OtherExpense' THEN 'OtherExpense'
WHEN REFERENCE_TYPE = 'OwnerDrawing' THEN 'OwnerDrawing'
WHEN REFERENCE_TYPE = 'OwnerContribution' THEN 'OwnerContribution'
WHEN REFERENCE_TYPE = 'TransferToAccount' THEN 'TransferToAccount'
WHEN REFERENCE_TYPE = 'TransferFromAccount' THEN 'TransferFromAccount'
END
`),
referenceType: knex.raw(`
CASE
WHEN REFERENCE_TYPE IN ('OtherIncome', 'OtherExpense', 'OwnerDrawing', 'OwnerContribution', 'TransferToAccount', 'TransferFromAccount') THEN 'CashflowTransaction'
ELSE REFERENCE_TYPE
END
`),
});
};
exports.down = function (knex) {
return knex('accounts_transactions')
.whereIn('transactionType', [
'OtherIncome',
'OtherExpense',
'OwnerDrawing',
'OwnerContribution',
'TransferToAccount',
'TransferFromAccount',
])
.update({
referenceType: knex.raw(`
CASE
WHEN TRANSACTION_TYPE = 'OtherIncome' THEN 'OtherIncome'
WHEN TRANSACTION_TYPE = 'OtherExpense' THEN 'OtherExpense'
WHEN TRANSACTION_TYPE = 'OwnerDrawing' THEN 'OwnerDrawing'
WHEN TRANSACTION_TYPE = 'OwnerContribution' THEN 'OwnerContribution'
WHEN TRANSACTION_TYPE = 'TransferToAccount' THEN 'TransferToAccount'
WHEN TRANSACTION_TYPE = 'TransferFromAccount' THEN 'TransferFromAccount'
ELSE REFERENCE_TYPE
END
`),
transactionType: knex.raw(`
CASE
WHEN TRANSACTION_TYPE IN ('OtherIncome', 'OtherExpense', 'OwnerDrawing', 'OwnerContribution', 'TransferToAccount', 'TransferFromAccount') THEN NULL
ELSE TRANSACTION_TYPE
END
`),
});
};

View File

@@ -12,8 +12,7 @@ export default class SeedAccounts extends TenantSeeder {
description: this.i18n.__(account.description),
currencyCode: this.tenant.metadata.baseCurrency,
seededAt: new Date(),
})
);
}));
return knex('accounts').then(async () => {
// Inserts seed entries.
return knex('accounts').insert(data);

View File

@@ -9,6 +9,28 @@ export const TaxPayableAccount = {
predefined: 1,
};
export const UnearnedRevenueAccount = {
name: 'Unearned Revenue',
slug: 'unearned-revenue',
account_type: 'other-current-liability',
parent_account_id: null,
code: '50005',
active: true,
index: 1,
predefined: true,
};
export const PrepardExpenses = {
name: 'Prepaid Expenses',
slug: 'prepaid-expenses',
account_type: 'other-current-asset',
parent_account_id: null,
code: '100010',
active: true,
index: 1,
predefined: true,
};
export default [
{
name: 'Bank Account',
@@ -323,4 +345,6 @@ export default [
index: 1,
predefined: 0,
},
UnearnedRevenueAccount,
PrepardExpenses,
];

View File

@@ -66,7 +66,9 @@ export interface IAccountTransaction {
referenceId: number;
referenceNumber?: string;
transactionNumber?: string;
transactionType?: string;
note?: string;
@@ -164,3 +166,7 @@ export enum TaxRateAction {
DELETE = 'Delete',
VIEW = 'View',
}
export interface CreateAccountParams {
ignoreUniqueName: boolean;
}

View File

@@ -0,0 +1,3 @@
export interface AttachmentLinkDTO {
key: string;
}

View File

@@ -2,6 +2,7 @@ import { Knex } from 'knex';
import { IDynamicListFilterDTO } from './DynamicFilter';
import { IItemEntry, IItemEntryDTO } from './ItemEntry';
import { IBillLandedCost } from './LandedCost';
import { AttachmentLinkDTO } from './Attachments';
export interface IBillDTO {
vendorId: number;
@@ -20,6 +21,7 @@ export interface IBillDTO {
warehouseId?: number;
projectId?: number;
isInclusiveTax?: boolean;
attachments?: AttachmentLinkDTO[];
}
export interface IBillEditDTO {
@@ -38,6 +40,7 @@ export interface IBillEditDTO {
branchId?: number;
warehouseId?: number;
projectId?: number;
attachments?: AttachmentLinkDTO[];
}
export interface IBill {
@@ -105,6 +108,7 @@ export interface IBillsService {
export interface IBillCreatedPayload {
tenantId: number;
bill: IBill;
billDTO: IBillDTO;
billId: number;
trx: Knex.Transaction;
}
@@ -126,6 +130,7 @@ export interface IBillEditedPayload {
billId: number;
oldBill: IBill;
bill: IBill;
billDTO: IBillDTO;
trx: Knex.Transaction;
}

View File

@@ -1,5 +1,6 @@
import { Knex } from 'knex';
import { IBill } from './Bill';
import { AttachmentLinkDTO } from './Attachments';
export interface IBillPaymentEntry {
id?: number;
@@ -45,6 +46,7 @@ export interface IBillPaymentDTO {
reference: string;
entries: IBillPaymentEntryDTO[];
branchId?: number;
attachments?: AttachmentLinkDTO[];
}
export interface IBillReceivePageEntry {
@@ -66,6 +68,7 @@ export interface IBillPaymentsService {
export interface IBillPaymentEventCreatedPayload {
tenantId: number;
billPayment: IBillPayment;
billPaymentDTO: IBillPaymentDTO;
billPaymentId: number;
trx: Knex.Transaction;
}
@@ -87,6 +90,7 @@ export interface IBillPaymentEventEditedPayload {
billPaymentId: number;
billPayment: IBillPayment;
oldBillPayment: IBillPayment;
billPaymentDTO: IBillPaymentDTO;
trx: Knex.Transaction;
}

View File

@@ -1,3 +1,4 @@
import { Knex } from 'knex';
import {
IFinancialSheetCommonMeta,
INumberFormatQuery,
@@ -257,7 +258,6 @@ export interface IUncategorizedCashflowTransaction {
categorized: boolean;
}
export interface CreateUncategorizedTransactionDTO {
date: Date | string;
accountId: number;
@@ -267,4 +267,18 @@ export interface CreateUncategorizedTransactionDTO {
description?: string;
referenceNo?: string | null;
plaidTransactionId?: string | null;
batch?: string;
}
export interface IUncategorizedTransactionCreatingEventPayload {
tenantId: number;
createUncategorizedTransactionDTO: CreateUncategorizedTransactionDTO;
trx: Knex.Transaction;
}
export interface IUncategorizedTransactionCreatedEventPayload {
tenantId: number;
uncategorizedTransaction: any;
createUncategorizedTransactionDTO: CreateUncategorizedTransactionDTO;
trx: Knex.Transaction;
}

View File

@@ -130,8 +130,9 @@ export interface ICommandCashflowDeletedPayload {
export interface ICashflowTransactionCategorizedPayload {
tenantId: number;
cashflowTransactionId: number;
uncategorizedTransaction: any;
cashflowTransaction: ICashflowTransaction;
categorizeDTO: any;
trx: Knex.Transaction;
}
export interface ICashflowTransactionUncategorizingPayload {
@@ -164,3 +165,10 @@ export interface IGetUncategorizedTransactionsQuery {
page?: number;
pageSize?: number;
}
export interface IGetRecognizedTransactionsQuery {
page?: number;
pageSize?: number;
accountId?: number;
}

View File

@@ -1,6 +1,7 @@
import { Knex } from 'knex';
import { IDynamicListFilter, IItemEntry, IVendorCredit } from '@/interfaces';
import { ILedgerEntry } from './Ledger';
import { AttachmentLinkDTO } from './Attachments';
export interface ICreditNoteEntryNewDTO {
index: number;
@@ -21,6 +22,7 @@ export interface ICreditNoteNewDTO {
entries: ICreditNoteEntryNewDTO[];
branchId?: number;
warehouseId?: number;
attachments?: AttachmentLinkDTO[]
}
export interface ICreditNoteEditDTO {
@@ -33,6 +35,7 @@ export interface ICreditNoteEditDTO {
entries: ICreditNoteEntryNewDTO[];
branchId?: number;
warehouseId?: number;
attachments?: AttachmentLinkDTO[]
}
export interface ICreditNoteEntry extends IItemEntry {}

View File

@@ -2,6 +2,7 @@ import { Knex } from 'knex';
import { ISystemUser } from './User';
import { IFilterRole } from './DynamicFilter';
import { IAccount } from './Account';
import { AttachmentLinkDTO } from './Attachments';
export interface IPaginationMeta {
total: number;
@@ -81,6 +82,7 @@ export interface IExpenseCommonDTO {
categories: IExpenseCategoryDTO[];
branchId?: number;
attachments?: AttachmentLinkDTO[];
}
export interface IExpenseCreateDTO extends IExpenseCommonDTO {}
@@ -152,6 +154,7 @@ export interface IExpenseCreatedPayload {
expenseId: number;
authorizedUser: ISystemUser;
expense: IExpense;
expenseDTO: IExpenseCreateDTO;
trx: Knex.Transaction;
}

View File

@@ -29,4 +29,9 @@ export interface ICashflowAccountTransaction {
date: Date;
formattedDate: string;
status: string;
formattedStatus: string;
uncategorizedTransactionId: number;
}

View File

@@ -56,6 +56,8 @@ export interface IGeneralLedgerSheetAccount {
transactions: IGeneralLedgerSheetAccountTransaction[];
openingBalance: IGeneralLedgerSheetAccountBalance;
closingBalance: IGeneralLedgerSheetAccountBalance;
closingBalanceSubaccounts?: IGeneralLedgerSheetAccountBalance;
children?: IGeneralLedgerSheetAccount[];
}
export type IGeneralLedgerSheetData = IGeneralLedgerSheetAccount[];

View File

@@ -0,0 +1,8 @@
import { ImportFilePreviewPOJO } from "@/services/Import/interfaces";
export interface IImportFileCommitedEventPayload {
tenantId: number;
importId: number;
meta: ImportFilePreviewPOJO;
}

View File

@@ -40,6 +40,8 @@ export interface ILedgerEntry {
date: Date | string;
transactionType: string;
transactionSubType?: string;
transactionId: number;
transactionNumber?: string;

View File

@@ -2,6 +2,7 @@ import { Knex } from 'knex';
import { IDynamicListFilterDTO } from './DynamicFilter';
import { ISystemUser } from './User';
import { IAccount } from './Account';
import { AttachmentLinkDTO } from './Attachments';
export interface IManualJournal {
id?: number;
@@ -56,6 +57,7 @@ export interface IManualJournalDTO {
publish?: boolean;
branchId?: number;
entries: IManualJournalEntryDTO[];
attachments?: AttachmentLinkDTO[];
}
export interface IManualJournalsFilter extends IDynamicListFilterDTO {
@@ -142,6 +144,7 @@ export interface IManualJournalEventEditedPayload {
tenantId: number;
manualJournal: IManualJournal;
oldManualJournal: IManualJournal;
manualJournalDTO: IManualJournalDTO;
trx: Knex.Transaction;
}
export interface IManualJournalEditingPayload {
@@ -161,6 +164,7 @@ export interface IManualJournalEventCreatedPayload {
tenantId: number;
manualJournal: IManualJournal;
manualJournalId: number;
manualJournalDTO: IManualJournalDTO;
trx: Knex.Transaction;
}

View File

@@ -122,6 +122,10 @@ export type IModelMetaCollectionField = IModelMetaCollectionFieldCommon &
export type IModelMetaRelationField = IModelMetaRelationFieldCommon &
IModelMetaRelationEnumerationField;
interface IModelPrintMeta{
pageTitle: string;
}
export interface IModelMeta {
defaultFilterField: string;
defaultSort: IModelMetaDefaultSort;
@@ -134,6 +138,8 @@ export interface IModelMeta {
importAggregateOn?: string;
importAggregateBy?: string;
print?: IModelPrintMeta;
fields: { [key: string]: IModelMetaField };
columns: { [key: string]: IModelMetaColumn };
}

View File

@@ -6,6 +6,7 @@ import {
} from '@/interfaces';
import { ILedgerEntry } from './Ledger';
import { ISaleInvoice } from './SaleInvoice';
import { AttachmentLinkDTO } from './Attachments';
export interface IPaymentReceive {
id?: number;
@@ -37,6 +38,7 @@ export interface IPaymentReceiveCreateDTO {
entries: IPaymentReceiveEntryDTO[];
branchId?: number;
attachments?: AttachmentLinkDTO[];
}
export interface IPaymentReceiveEditDTO {
@@ -50,6 +52,7 @@ export interface IPaymentReceiveEditDTO {
statement: string;
entries: IPaymentReceiveEntryDTO[];
branchId?: number;
attachments?: AttachmentLinkDTO[];
}
export interface IPaymentReceiveEntry {
@@ -114,6 +117,7 @@ export interface IPaymentReceiveCreatedPayload {
paymentReceive: IPaymentReceive;
paymentReceiveId: number;
authorizedUser: ISystemUser;
paymentReceiveDTO: IPaymentReceiveCreateDTO;
trx: Knex.Transaction;
}
@@ -122,6 +126,7 @@ export interface IPaymentReceiveEditedPayload {
paymentReceiveId: number;
paymentReceive: IPaymentReceive;
oldPaymentReceive: IPaymentReceive;
paymentReceiveDTO: IPaymentReceiveEditDTO;
authorizedUser: ISystemUser;
trx: Knex.Transaction;
}

View File

@@ -1,3 +1,5 @@
import { Knex } from "knex";
export interface IPlaidItemCreatedEventPayload {
tenantId: number;
plaidAccessToken: string;
@@ -54,3 +56,10 @@ export interface SyncAccountsTransactionsTask {
plaidAccountId: number;
plaidTransactions: PlaidTransaction[];
}
export interface IPlaidTransactionsSyncedEventPayload {
tenantId: number;
plaidAccountId: number;
batch: string;
trx?: Knex.Transaction
}

View File

@@ -2,6 +2,7 @@ import { Knex } from 'knex';
import { IItemEntry, IItemEntryDTO } from './ItemEntry';
import { IDynamicListFilterDTO } from '@/interfaces/DynamicFilter';
import { CommonMailOptions, CommonMailOptionsDTO } from './Mailable';
import { AttachmentLinkDTO } from './Attachments';
export interface ISaleEstimate {
id?: number;
@@ -38,6 +39,7 @@ export interface ISaleEstimateDTO {
branchId?: number;
warehouseId?: number;
attachments?: AttachmentLinkDTO[];
}
export interface ISalesEstimatesFilter extends IDynamicListFilterDTO {
@@ -70,6 +72,7 @@ export interface ISaleEstimateEditedPayload {
estimateId: number;
saleEstimate: ISaleEstimate;
oldSaleEstimate: ISaleEstimate;
estimateDTO: ISaleEstimateDTO;
trx: Knex.Transaction;
}

View File

@@ -3,6 +3,7 @@ import { ISystemUser, IAccount, ITaxTransaction } from '@/interfaces';
import { CommonMailOptions, CommonMailOptionsDTO } from './Mailable';
import { IDynamicListFilter } from '@/interfaces/DynamicFilter';
import { IItemEntry, IItemEntryDTO } from './ItemEntry';
import { AttachmentLinkDTO } from './Attachments';
export interface ISaleInvoice {
id: number;
@@ -64,6 +65,8 @@ export interface ISaleInvoiceDTO {
branchId?: number | null;
isInclusiveTax?: boolean;
attachments?: AttachmentLinkDTO[];
}
export interface ISaleInvoiceCreateDTO extends ISaleInvoiceDTO {

View File

@@ -1,6 +1,7 @@
import { Knex } from 'knex';
import { IItemEntry } from './ItemEntry';
import { CommonMailOptions, CommonMailOptionsDTO } from './Mailable';
import { AttachmentLinkDTO } from './Attachments';
export interface ISaleReceipt {
id?: number;
@@ -43,6 +44,7 @@ export interface ISaleReceiptDTO {
closed: boolean;
entries: any[];
branchId?: number;
attachments?: AttachmentLinkDTO[];
}
export interface ISalesReceiptsService {
@@ -85,6 +87,7 @@ export interface ISaleReceiptCreatedPayload {
tenantId: number;
saleReceipt: ISaleReceipt;
saleReceiptId: number;
saleReceiptDTO: ISaleReceiptDTO;
trx: Knex.Transaction;
}
@@ -93,6 +96,7 @@ export interface ISaleReceiptEditedPayload {
oldSaleReceipt: number;
saleReceipt: ISaleReceipt;
saleReceiptId: number;
saleReceiptDTO: ISaleReceiptDTO;
trx: Knex.Transaction;
}

View File

@@ -11,6 +11,9 @@ export interface ISystemUser extends Model {
password: string;
email: string;
verifyToken: string;
verified: boolean;
roleId: number;
tenantId: number;

View File

@@ -1,5 +1,6 @@
import { IDynamicListFilter, IItemEntry, IItemEntryDTO } from '@/interfaces';
import { Knex } from 'knex';
import { AttachmentLinkDTO } from './Attachments';
export enum VendorCreditAction {
Create = 'Create',
@@ -61,6 +62,7 @@ export interface IVendorCreditDTO {
branchId?: number;
warehouseId?: number;
attachments?: AttachmentLinkDTO[];
}
export interface IVendorCreditCreateDTO extends IVendorCreditDTO {}
@@ -118,6 +120,7 @@ export interface IVendorCreditEditedPayload {
oldVendorCredit: IVendorCredit;
vendorCredit: IVendorCredit;
vendorCreditId: number;
vendorCreditDTO: IVendorCreditEditDTO;
trx: Knex.Transaction;
}

View File

@@ -70,10 +70,7 @@ export class PlaidClientWrapper {
baseOptions: {
headers: {
'PLAID-CLIENT-ID': config.plaid.clientId,
'PLAID-SECRET':
config.plaid.env === 'development'
? config.plaid.secretDevelopment
: config.plaid.secretSandbox,
'PLAID-SECRET': config.plaid.secret,
'Plaid-Version': '2020-09-14',
},
},

View File

@@ -0,0 +1,11 @@
import { S3Client } from '@aws-sdk/client-s3';
import config from '@/config';
export const s3 = new S3Client({
region: config.s3.region,
credentials: {
accessKeyId: config.s3.accessKeyId,
secretAccessKey: config.s3.secretAccessKey,
},
endpoint: config.s3.endpoint,
});

View File

@@ -149,13 +149,19 @@ export class Transformer {
return this.excludeAttributes().length > 0;
};
private dateFormat = 'YYYY MMM DD';
setDateFormat(format: string) {
this.dateFormat = format;
}
/**
*
* @param date
* @returns
*/
protected formatDate(date) {
return date ? moment(date).format('YYYY/MM/DD') : '';
return date ? moment(date).format(this.dateFormat) : '';
}
/**
@@ -163,8 +169,8 @@ export class Transformer {
* @param number
* @returns
*/
protected formatNumber(number) {
return formatNumber(number, { money: false });
protected formatNumber(number, props?) {
return formatNumber(number, { money: false, ...props });
}
/**
@@ -193,6 +199,7 @@ export class Transformer {
) {
transformer.setOptions(options);
transformer.setContext(this.context);
transformer.setDateFormat(this.dateFormat);
return transformer.work(obj);
}

View File

@@ -24,6 +24,17 @@ export class TransformerInjectable {
};
}
/**
* Retrieves the given tenatn date format.
* @param {number} tenantId
* @returns {string}
*/
async getTenantDateFormat(tenantId: number) {
const metadata = await TenantMetadata.query().findOne('tenantId', tenantId);
return metadata.dateFormat;
}
/**
* Transformes the given transformer after inject the tenant context.
* @param {number} tenantId
@@ -41,7 +52,11 @@ export class TransformerInjectable {
if (!isNull(tenantId)) {
const context = await this.getApplicationContext(tenantId);
transformer.setContext(context);
const dateFormat = await this.getTenantDateFormat(tenantId);
transformer.setDateFormat(dateFormat);
}
transformer.setOptions(options);
return transformer.work(object);

View File

@@ -92,7 +92,28 @@ import { DeleteCashflowTransactionOnUncategorize } from '@/services/Cashflow/sub
import { PreventDeleteTransactionOnDelete } from '@/services/Cashflow/subscribers/PreventDeleteTransactionsOnDelete';
import { SubscribeFreeOnSignupCommunity } from '@/services/Subscription/events/SubscribeFreeOnSignupCommunity';
import { SendVerfiyMailOnSignUp } from '@/services/Authentication/events/SendVerfiyMailOnSignUp';
import { AttachmentsOnSaleInvoiceCreated } from '@/services/Attachments/events/AttachmentsOnSaleInvoice';
import { AttachmentsOnSaleReceipt } from '@/services/Attachments/events/AttachmentsOnSaleReceipts';
import { AttachmentsOnManualJournals } from '@/services/Attachments/events/AttachmentsOnManualJournals';
import { AttachmentsOnExpenses } from '@/services/Attachments/events/AttachmentsOnExpenses';
import { AttachmentsOnBills } from '@/services/Attachments/events/AttachmentsOnBills';
import { AttachmentsOnPaymentsReceived } from '@/services/Attachments/events/AttachmentsOnPaymentsReceived';
import { AttachmentsOnVendorCredits } from '@/services/Attachments/events/AttachmentsOnVendorCredits';
import { AttachmentsOnCreditNote } from '@/services/Attachments/events/AttachmentsOnCreditNote';
import { AttachmentsOnBillPayments } from '@/services/Attachments/events/AttachmentsOnPaymentsMade';
import { AttachmentsOnSaleEstimates } from '@/services/Attachments/events/AttachmentsOnSaleEstimates';
import { TriggerRecognizedTransactions } from '@/services/Banking/RegonizeTranasctions/events/TriggerRecognizedTransactions';
import { ValidateMatchingOnExpenseDelete } from '@/services/Banking/Matching/events/ValidateMatchingOnExpenseDelete';
import { ValidateMatchingOnManualJournalDelete } from '@/services/Banking/Matching/events/ValidateMatchingOnManualJournalDelete';
import { ValidateMatchingOnPaymentReceivedDelete } from '@/services/Banking/Matching/events/ValidateMatchingOnPaymentReceivedDelete';
import { ValidateMatchingOnPaymentMadeDelete } from '@/services/Banking/Matching/events/ValidateMatchingOnPaymentMadeDelete';
import { ValidateMatchingOnCashflowDelete } from '@/services/Banking/Matching/events/ValidateMatchingOnCashflowDelete';
import { RecognizeSyncedBankTranasctions } from '@/services/Banking/Plaid/subscribers/RecognizeSyncedBankTransactions';
import { UnlinkBankRuleOnDeleteBankRule } from '@/services/Banking/Rules/events/UnlinkBankRuleOnDeleteBankRule';
import { DecrementUncategorizedTransactionOnMatching } from '@/services/Banking/Matching/events/DecrementUncategorizedTransactionsOnMatch';
import { DecrementUncategorizedTransactionOnExclude } from '@/services/Banking/Exclude/events/DecrementUncategorizedTransactionOnExclude';
import { DecrementUncategorizedTransactionOnCategorize } from '@/services/Cashflow/subscribers/DecrementUncategorizedTransactionOnCategorize';
import { LoopsEventsSubscriber } from '@/services/Loops/LoopsEventsSubscriber';
export default () => {
return new EventPublisher();
@@ -224,6 +245,38 @@ export const susbcribers = () => {
PreventDeleteTransactionOnDelete,
SubscribeFreeOnSignupCommunity,
SendVerfiyMailOnSignUp
SendVerfiyMailOnSignUp,
// Attachments
AttachmentsOnSaleInvoiceCreated,
AttachmentsOnSaleEstimates,
AttachmentsOnSaleReceipt,
AttachmentsOnPaymentsReceived,
AttachmentsOnCreditNote,
AttachmentsOnVendorCredits,
AttachmentsOnBills,
AttachmentsOnBillPayments,
AttachmentsOnManualJournals,
AttachmentsOnExpenses,
// Bank Rules
TriggerRecognizedTransactions,
UnlinkBankRuleOnDeleteBankRule,
DecrementUncategorizedTransactionOnMatching,
DecrementUncategorizedTransactionOnExclude,
DecrementUncategorizedTransactionOnCategorize,
// Validate matching
ValidateMatchingOnCashflowDelete,
ValidateMatchingOnExpenseDelete,
ValidateMatchingOnManualJournalDelete,
ValidateMatchingOnPaymentReceivedDelete,
ValidateMatchingOnPaymentMadeDelete,
// Plaid
RecognizeSyncedBankTranasctions,
// Loops
LoopsEventsSubscriber
];
};

View File

@@ -17,7 +17,9 @@ import {
} from '@/api/middleware/JSONResponseTransformer';
import config from '@/config';
import path from 'path';
import ObjectionErrorHandlerMiddleware from '@/api/middleware/ObjectionErrorHandlerMiddleware';
import { ObjectionErrorException } from '@/api/exceptions/ObjectionErrorException';
import { ServiceErrorException } from '@/api/exceptions/ServiceErrorException';
import { GlobalErrorException } from '@/api/exceptions/GlobalErrorException';
export default ({ app }) => {
// Express configuration.
@@ -30,9 +32,6 @@ export default ({ app }) => {
// Helmet helps you secure your Express apps by setting various HTTP headers.
app.use(helmet());
// Allow to full error stack traces and internal details
app.use(errorHandler());
// Boom response objects.
app.use(boom());
@@ -65,8 +64,10 @@ export default ({ app }) => {
// Agendash application load.
app.use('/agendash', AgendashController.router());
// Handles objectionjs errors.
app.use(ObjectionErrorHandlerMiddleware);
// Handles errors.
app.use(ObjectionErrorException);
app.use(ServiceErrorException);
app.use(GlobalErrorException);
// catch 404 and forward to error handler
app.use((req: Request, res: Response, next: NextFunction) => {

View File

@@ -13,6 +13,7 @@ import { PaymentReceiveMailNotificationJob } from '@/services/Sales/PaymentRecei
import { PlaidFetchTransactionsJob } from '@/services/Banking/Plaid/PlaidFetchTransactionsJob';
import { ImportDeleteExpiredFilesJobs } from '@/services/Import/jobs/ImportDeleteExpiredFilesJob';
import { SendVerifyMailJob } from '@/services/Authentication/jobs/SendVerifyMailJob';
import { RegonizeTransactionsJob } from '@/services/Banking/RegonizeTranasctions/RecognizeTransactionsJob';
export default ({ agenda }: { agenda: Agenda }) => {
new ResetPasswordMailJob(agenda);
@@ -29,6 +30,7 @@ export default ({ agenda }: { agenda: Agenda }) => {
new PlaidFetchTransactionsJob(agenda);
new ImportDeleteExpiredFilesJobs(agenda);
new SendVerifyMailJob(agenda);
new RegonizeTransactionsJob(agenda);
agenda.start().then(() => {
agenda.every('1 hours', 'delete-expired-imported-files', {});

View File

@@ -60,9 +60,14 @@ import Time from 'models/Time';
import Task from 'models/Task';
import TaxRate from 'models/TaxRate';
import TaxRateTransaction from 'models/TaxRateTransaction';
import Attachment from 'models/Attachment';
import PlaidItem from 'models/PlaidItem';
import UncategorizedCashflowTransaction from 'models/UncategorizedCashflowTransaction';
import Document from '@/models/Document';
import DocumentLink from '@/models/DocumentLink';
import { BankRule } from '@/models/BankRule';
import { BankRuleCondition } from '@/models/BankRuleCondition';
import { RecognizedBankTransaction } from '@/models/RecognizedBankTransaction';
import { MatchedBankTransaction } from '@/models/MatchedBankTransaction';
export default (knex) => {
const models = {
@@ -126,9 +131,14 @@ export default (knex) => {
Task,
TaxRate,
TaxRateTransaction,
Attachment,
Document,
DocumentLink,
PlaidItem,
UncategorizedCashflowTransaction
UncategorizedCashflowTransaction,
BankRule,
BankRuleCondition,
RecognizedBankTransaction,
MatchedBankTransaction,
};
return mapValues(models, (model) => model.bindKnex(knex));
};

View File

@@ -8,6 +8,9 @@ export default {
},
importable: true,
exportable: true,
print: {
pageTitle: 'Chart of Accounts',
},
fields: {
name: {
name: 'account.field.name',
@@ -121,7 +124,7 @@ export default {
},
balance: {
name: 'account.field.balance',
accessor: 'amount',
accessor: 'formattedAmount',
},
description: {
name: 'account.field.description',
@@ -133,6 +136,7 @@ export default {
},
createdAt: {
name: 'account.field.created_at',
printable: false,
},
},
fields2: {

View File

@@ -10,6 +10,7 @@ export default class AccountTransaction extends TenantModel {
debit: number;
exchangeRate: number;
taxRate: number;
transactionType: string;
/**
* Table name
@@ -53,7 +54,7 @@ export default class AccountTransaction extends TenantModel {
* @return {string}
*/
get referenceTypeFormatted() {
return getTransactionTypeLabel(this.referenceType);
return getTransactionTypeLabel(this.referenceType, this.transactionType);
}
/**

View File

@@ -0,0 +1,70 @@
import TenantModel from 'models/TenantModel';
import { Model } from 'objection';
export class BankRule extends TenantModel {
id!: number;
name!: string;
order!: number;
applyIfAccountId!: number;
applyIfTransactionType!: string;
assignCategory!: string;
assignAccountId!: number;
assignPayee!: string;
assignMemo!: string;
conditionsType!: string;
/**
* Table name
*/
static get tableName() {
return 'bank_rules';
}
/**
* Timestamps columns.
*/
get timestamps() {
return ['created_at', 'updated_at'];
}
/**
* Virtual attributes.
*/
static get virtualAttributes() {
return [];
}
/**
* Relationship mapping.
*/
static get relationMappings() {
const { BankRuleCondition } = require('models/BankRuleCondition');
const Account = require('models/Account');
return {
/**
* Sale invoice associated entries.
*/
conditions: {
relation: Model.HasManyRelation,
modelClass: BankRuleCondition,
join: {
from: 'bank_rules.id',
to: 'bank_rule_conditions.ruleId',
},
},
/**
* Bank rule may associated to the assign account.
*/
assignAccount: {
relation: Model.BelongsToOneRelation,
modelClass: Account.default,
join: {
from: 'bank_rules.assignAccountId',
to: 'accounts.id',
},
},
};
}
}

View File

@@ -0,0 +1,24 @@
import TenantModel from 'models/TenantModel';
export class BankRuleCondition extends TenantModel {
/**
* Table name.
*/
static get tableName() {
return 'bank_rule_conditions';
}
/**
* Timestamps columns.
*/
get timestamps() {
return [];
}
/**
* Virtual attributes.
*/
static get virtualAttributes() {
return [];
}
}

View File

@@ -10,6 +10,9 @@ export default {
importAggregator: 'group',
importAggregateOn: 'entries',
importAggregateBy: 'billNumber',
print: {
pageTitle: 'Bills',
},
fields: {
vendor: {
name: 'bill.field.vendor',
@@ -83,6 +86,10 @@ export default {
},
},
columns: {
billDate: {
name: 'Date',
accessor: 'formattedBillDate',
},
billNumber: {
name: 'Bill No.',
type: 'text',
@@ -91,13 +98,10 @@ export default {
name: 'Reference No.',
type: 'text',
},
billDate: {
name: 'Date',
type: 'date',
},
dueDate: {
name: 'Due Date',
type: 'date',
accessor: 'formattedDueDate',
},
vendorId: {
name: 'Vendor',
@@ -111,10 +115,12 @@ export default {
exchangeRate: {
name: 'Exchange Rate',
type: 'number',
printable: false,
},
currencyCode: {
name: 'Currency Code',
type: 'text',
printable: false,
},
dueAmount: {
name: 'Due Amount',
@@ -127,10 +133,12 @@ export default {
note: {
name: 'Note',
type: 'text',
printable: false,
},
open: {
name: 'Open',
type: 'boolean',
printable: false,
},
entries: {
name: 'Entries',

View File

@@ -403,6 +403,8 @@ export default class Bill extends mixin(TenantModel, [
const BillLandedCost = require('models/BillLandedCost');
const Branch = require('models/Branch');
const TaxRateTransaction = require('models/TaxRateTransaction');
const Document = require('models/Document');
const { MatchedBankTransaction } = require('models/MatchedBankTransaction');
return {
vendor: {
@@ -465,6 +467,40 @@ export default class Bill extends mixin(TenantModel, [
builder.where('reference_type', 'Bill');
},
},
/**
* Bill may has many attached attachments.
*/
attachments: {
relation: Model.ManyToManyRelation,
modelClass: Document.default,
join: {
from: 'bills.id',
through: {
from: 'document_links.modelId',
to: 'document_links.documentId',
},
to: 'documents.id',
},
filter(query) {
query.where('model_ref', 'Bill');
},
},
/**
* Bill may belongs to matched bank transaction.
*/
matchedBankTransaction: {
relation: Model.HasManyRelation,
modelClass: MatchedBankTransaction,
join: {
from: 'bills.id',
to: 'matched_bank_transactions.referenceId',
},
filter(query) {
query.where('reference_type', 'Bill');
},
},
};
}
@@ -489,9 +525,9 @@ export default class Bill extends mixin(TenantModel, [
return notFoundBillsIds;
}
static changePaymentAmount(billId, amount) {
static changePaymentAmount(billId, amount, trx) {
const changeMethod = amount > 0 ? 'increment' : 'decrement';
return this.query()
return this.query(trx)
.where('id', billId)
[changeMethod]('payment_amount', Math.abs(amount));
}

Some files were not shown because too many files have changed in this diff Show More