Compare commits

...

92 Commits

Author SHA1 Message Date
transifex-integration[bot]
de319b5e6c Translate index.json in fr_FR
1% of minimum 1% reviewed source file: 'index.json'
on 'fr_FR'.

Sync of partially translated files: 
untranslated content is included with an empty translation 
or source language content depending on file format
2024-09-30 04:42:48 +00:00
transifex-integration[bot]
6c356d48d6 Translate index.json in fr_FR
1% of minimum 1% reviewed source file: 'index.json'
on 'fr_FR'.

Sync of partially translated files: 
untranslated content is included with an empty translation 
or source language content depending on file format
2023-11-05 19:13:08 +00:00
transifex-integration[bot]
92101b7876 Translate index.json in fr_FR
1% of minimum 1% reviewed source file: 'index.json'
on 'fr_FR'.

Sync of partially translated files: 
untranslated content is included with an empty translation 
or source language content depending on file format
2023-11-05 19:11:09 +00:00
transifex-integration[bot]
b9b91d5d62 Translate index.json in fr_FR
1% of minimum 1% reviewed source file: 'index.json'
on 'fr_FR'.

Sync of partially translated files: 
untranslated content is included with an empty translation 
or source language content depending on file format
2023-11-05 19:11:00 +00:00
Ahmed Bouhuolia
50164873ce chore: remove the duplicated keys in lang files 2023-11-05 20:11:27 +02:00
Ahmed Bouhuolia
a2cbab0bc3 chore: update README.md to add Gitpod 2023-11-05 03:28:04 +02:00
Ahmed Bouhuolia
5027f9fe5d chore: configure Gitpod 2023-11-05 02:58:48 +02:00
Ahmed Bouhuolia
eeb67d4005 chore: configure Gitpod 2023-11-05 02:22:26 +02:00
Ahmed Bouhuolia
a3d9e8ef2b chore: configure gitpod 2023-11-04 15:35:05 +02:00
Ahmed Bouhuolia
121d992b68 chore: updating CONTRIBUTING.md 2023-11-02 22:57:41 +02:00
Ahmed Bouhuolia
078a7ea51c fix: change Dockerfile files with new pnpm (#278) 2023-10-28 01:57:31 +02:00
Ahmed Bouhuolia
e070ac72dd feat: Computed Net Income under Equity in Balance Sheet report. (#271) 2023-10-26 18:59:09 +02:00
allcontributors[bot]
08ac5f4b01 docs: add kochie as a contributor for code (#277)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

---------

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2023-10-25 22:14:38 +02:00
Robert Koch
e4a7f09dbc feat: Add tax numbers to the organization details (#269) 2023-10-25 22:10:46 +02:00
Ahmed Bouhuolia
2c5537efad fix: Trial balance sheet adjusted balance (#273) 2023-10-25 13:18:13 +02:00
Ahmed Bouhuolia
017908600e feat: improve financial statements rows color (#276) 2023-10-24 22:40:54 +02:00
dependabot[bot]
6307ca8935 chore(deps-dev): bump @babel/traverse in /packages/server (#272)
Bumps [@babel/traverse](https://github.com/babel/babel/tree/HEAD/packages/babel-traverse) from 7.23.0 to 7.23.2.
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.23.2/packages/babel-traverse)

---
updated-dependencies:
- dependency-name: "@babel/traverse"
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-19 19:33:12 +02:00
Ahmed Bouhuolia
1ed1c9ea1d feat: assign default sell/purchase tax rates to items (#261) 2023-10-08 23:55:59 +02:00
Ahmed Bouhuolia
d40de4d22b feat: integrate tax rates to bills (#260) 2023-10-08 16:07:18 +02:00
Ahmed Bouhuolia
ee62e3e1c2 feat: migrate to pnpm (#253) 2023-10-04 12:17:27 +02:00
Ahmed Bouhuolia
5df454dd30 chore: bump packages version to v0.10.2 2023-10-02 23:29:21 +02:00
Ahmed Bouhuolia
07628ddc37 fix(server): add missing method in ItemEntry model. 2023-10-02 23:27:19 +02:00
Ahmed Bouhuolia
69afa07e3b fix(webapp): Disable tax rates from item entries editor table on services do not support tax rates 2023-10-02 23:27:05 +02:00
Ahmed Bouhuolia
b1a043f699 chore(server): add package-lock.json file 2023-09-27 19:16:02 +02:00
Ahmed Bouhuolia
9eaff0785b chore: update CHANGELOG.md file 2023-09-25 17:14:07 +02:00
Ahmed Bouhuolia
b3a97ed5d5 chore: dump packages versions 2023-09-25 15:34:10 +02:00
Ahmed Bouhuolia
1aaa65edd2 Merge pull request #242 from bigcapitalhq/abouhuolia/big-62-running-tenants-dbs-migration-on-migration-docker-container
fix: Running tenants migration on docker migration container
2023-09-25 15:31:54 +02:00
Ahmed Bouhuolia
efebf424d1 fix: running tenants migration on docker migration container 2023-09-25 15:31:09 +02:00
Ahmed Bouhuolia
597973d5d1 chore: update @blueprintjs-formik/select package. 2023-09-24 12:30:01 +02:00
Ahmed Bouhuolia
ee6bc822c9 Merge pull request #240 from bigcapitalhq/BIG-61-make-tables-header-sticy
fix: Table headers sticky for all reports.
2023-09-24 12:15:51 +02:00
ElforJani13
07e78ebd6a Sticky table header for all reports 2023-09-24 04:58:16 +02:00
Ahmed Bouhuolia
8c04a6205b Merge pull request #197 from bigcapitalhq/dependabot/npm_and_yarn/mongoose-5.13.20
chore(deps): bump mongoose from 5.13.15 to 5.13.20
2023-09-23 14:43:25 +02:00
Ahmed Bouhuolia
d54ea68d46 Merge pull request #199 from bigcapitalhq/dependabot/npm_and_yarn/packages/webapp/word-wrap-1.2.4
chore(deps): bump word-wrap from 1.2.3 to 1.2.4 in /packages/webapp
2023-09-23 14:43:12 +02:00
Ahmed Bouhuolia
f42c8031c2 Merge pull request #200 from bigcapitalhq/dependabot/npm_and_yarn/word-wrap-1.2.4
chore(deps): bump word-wrap from 1.2.3 to 1.2.4
2023-09-23 14:42:49 +02:00
Ahmed Bouhuolia
5261d332b7 Merge pull request #204 from bigcapitalhq/tax-compliance
feat: [wip] tax rates service
2023-09-23 14:41:32 +02:00
Ahmed Bouhuolia
f1e7d0fc44 fix(server): sales tax liability summary report 2023-09-23 14:40:21 +02:00
Ahmed Bouhuolia
1d1049043e fix(webapp): invoice total currency should be dynamic 2023-09-23 14:19:59 +02:00
Ahmed Bouhuolia
1148fef9ad fix(server): tax tracking on sale invoices 2023-09-23 14:19:42 +02:00
Ahmed Bouhuolia
92ac0dbd25 fix(webapp): code cleanup 2023-09-22 15:25:56 +02:00
Ahmed Bouhuolia
ce41845bd7 fix(server): pull-request nodes 2023-09-22 15:23:33 +02:00
Ahmed Bouhuolia
eaf72d1608 fix(server): tax percentage calculation of tax sales liability summary report 2023-09-20 19:25:37 +02:00
Ahmed Bouhuolia
ac336f9878 feat(webapp): add tax compund tag to tax rates 2023-09-20 19:25:07 +02:00
Ahmed Bouhuolia
746c80c564 fix(server): tax rate could be zero. 2023-09-20 17:22:58 +02:00
Ahmed Bouhuolia
601434b107 feat: avoid invoice writes GL entry with zero amount 2023-09-20 17:22:39 +02:00
Ahmed Bouhuolia
5aaa33e585 feat(webapp): add activate/inactivate tax rate buttons on details drawer 2023-09-20 15:06:27 +02:00
Ahmed Bouhuolia
d48d864a5f fix(sever): tax rates cell. 2023-09-20 00:43:55 +02:00
Ahmed Bouhuolia
453df2ac4e fix(server): Validation of activate/inacitvate tax rates 2023-09-20 00:42:34 +02:00
Ahmed Bouhuolia
73ceeaee46 fix(server): [Sales Tax Liability Report] filter non-transactions tax rates 2023-09-20 00:42:03 +02:00
Ahmed Bouhuolia
1b4b656419 feat(server): order tax rates by name 2023-09-18 18:57:54 +02:00
Ahmed Bouhuolia
df823c0bfe feat(webapp): tax rates empty state 2023-09-18 18:57:24 +02:00
Ahmed Bouhuolia
e91d7b0cff feat(webapp): tax rate form validation errors 2023-09-18 11:23:50 +02:00
Ahmed Bouhuolia
aa52e7d02c feat(server): soft deleting tax rates 2023-09-18 10:15:55 +02:00
Ahmed Bouhuolia
4e53d08497 feat(server): wip activate/inactivate tax rate 2023-09-18 01:38:38 +02:00
Ahmed Bouhuolia
2356921f27 feat(webapp): wip tax rate form dialog 2023-09-18 01:35:53 +02:00
Ahmed Bouhuolia
a0a5d00be3 chore: Add Patreon link for funding 2023-09-15 01:34:45 +02:00
Ahmed Bouhuolia
fbd74c559b feat(server): tweak the tax rate transformer 2023-09-14 23:36:15 +02:00
Ahmed Bouhuolia
8a64198433 feat(webapp): wip tax rates management 2023-09-14 23:35:54 +02:00
Ahmed Bouhuolia
b98b73ad98 feat(webapp): invoice tax rate 2023-09-11 23:17:27 +02:00
Ahmed Bouhuolia
6abae43c6f feat: tax rate transformer 2023-09-11 20:46:46 +02:00
Ahmed Bouhuolia
7657337c4f feat: sales tax report query 2023-09-08 19:49:46 +02:00
Ahmed Bouhuolia
983ceb5cc6 feat: sale invoice model tax attributes 2023-09-06 14:01:40 +02:00
Ahmed Bouhuolia
ac072d29fc feat(server): wip sale invoice tax rate GL entries 2023-09-04 18:39:49 +02:00
Ahmed Bouhuolia
17e055db5e chore: update README.md file 2023-09-03 01:35:10 +02:00
Ahmed Bouhuolia
b49a021506 feat: contact us section to README.md file 2023-09-03 01:32:06 +02:00
Ahmed Bouhuolia
b49b45fb43 feat: wip sales tax summry report 2023-09-02 01:52:07 +02:00
Ahmed Bouhuolia
bb7cf41e3e feat: add sales tax summary report to reports list 2023-09-02 01:51:28 +02:00
Ahmed Bouhuolia
801ea5dfdb feat: wip sales tax summary report 2023-09-02 01:50:24 +02:00
Ahmed Bouhuolia
eb03a38553 feat(webapp): wip sales tax summary report 2023-09-01 20:50:22 +02:00
Ahmed Bouhuolia
0852feecbf fix(server): avoid display total row if no tax rates on sales tax report 2023-09-01 20:48:23 +02:00
Ahmed Bouhuolia
54dcde657f feat(webapp): wip sales tax liability summary report 2023-09-01 01:39:16 +02:00
Ahmed Bouhuolia
5bb95eeb1a feat: wip sales tax liability summary report 2023-08-31 21:39:59 +02:00
Ahmed Bouhuolia
6baec8dd96 feat(server): wip sales tax liability summary report 2023-08-31 02:19:18 +02:00
Ahmed Bouhuolia
6535424d0f feat(server): wip sale invoice tax rates 2023-08-29 19:12:19 +02:00
Ahmed Bouhuolia
09d73db20f Merge branch 'develop' into tax-compliance 2023-08-29 15:09:52 +02:00
Ahmed Bouhuolia
7f746b96c8 chore: remove /data directory from git ignored dirs 2023-08-29 03:05:19 +02:00
Ahmed Bouhuolia
ed2bca6b74 chore: dump CHANGELOG for 0.9.12 2023-08-29 02:54:03 +02:00
Ahmed Bouhuolia
f9d5a3c69a Merge pull request #231 from bigcapitalhq/fix-filter-transactions-date-format
fix(server): date format of filtering transactions by date range
2023-08-29 02:42:35 +02:00
Ahmed Bouhuolia
84445d4bac fix(server): date format of filtering transactions by date range 2023-08-29 02:41:40 +02:00
Ahmed Bouhuolia
75d8864aae Merge remote-tracking branch 'refs/remotes/origin/develop' into develop 2023-08-28 21:03:23 +02:00
Ahmed Bouhuolia
cb6dab08d8 chore: remove un-used methods 2023-08-28 21:01:34 +02:00
Ahmed Bouhuolia
5112ef9b64 Merge pull request #230 from bigcapitalhq/abouhuolia/big-60-fromto-date-is-not-showing-up-on-inventory-items-details
fix: change the default from/date date value of reports
2023-08-28 20:59:02 +02:00
Ahmed Bouhuolia
a630e8a612 fix: change the default from/to dates of customers/vendors transactions 2023-08-28 20:53:52 +02:00
Ahmed Bouhuolia
4df63561cf fix(webapp): change the default from/to date values of reports 2023-08-27 16:00:54 +02:00
Ahmed Bouhuolia
c7a3bac44c fix(server): change the default from/date date value of reports 2023-08-27 15:50:52 +02:00
Ahmed Bouhuolia
251c54be60 Merge pull request #229 from bigcapitalhq/abouhuolia/big-45-receivablepayable-again-report-issue
fix AP/AR aging summary issue
2023-08-27 00:58:17 +02:00
Ahmed Bouhuolia
d1121f0b81 feat(server): wip tax rate on sale invoice service 2023-08-14 14:59:10 +02:00
Ahmed Bouhuolia
a7644e6481 feat: tax rates on sale invoice service 2023-08-11 21:08:30 +02:00
Ahmed Bouhuolia
d6f56568a3 feat: tax rates crud service 2023-08-11 16:00:39 +02:00
Ahmed Bouhuolia
04d134806b feat(server): wip tax rates service 2023-08-11 01:31:52 +02:00
dependabot[bot]
339559d830 chore(deps): bump word-wrap from 1.2.3 to 1.2.4
Bumps [word-wrap](https://github.com/jonschlinkert/word-wrap) from 1.2.3 to 1.2.4.
- [Release notes](https://github.com/jonschlinkert/word-wrap/releases)
- [Commits](https://github.com/jonschlinkert/word-wrap/compare/1.2.3...1.2.4)

---
updated-dependencies:
- dependency-name: word-wrap
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-20 06:12:05 +00:00
dependabot[bot]
22e4d757e4 chore(deps): bump word-wrap from 1.2.3 to 1.2.4 in /packages/webapp
Bumps [word-wrap](https://github.com/jonschlinkert/word-wrap) from 1.2.3 to 1.2.4.
- [Release notes](https://github.com/jonschlinkert/word-wrap/releases)
- [Commits](https://github.com/jonschlinkert/word-wrap/compare/1.2.3...1.2.4)

---
updated-dependencies:
- dependency-name: word-wrap
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-20 06:08:24 +00:00
dependabot[bot]
3b98e8de80 chore(deps): bump mongoose from 5.13.15 to 5.13.20
Bumps [mongoose](https://github.com/Automattic/mongoose) from 5.13.15 to 5.13.20.
- [Release notes](https://github.com/Automattic/mongoose/releases)
- [Changelog](https://github.com/Automattic/mongoose/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Automattic/mongoose/compare/5.13.15...5.13.20)

---
updated-dependencies:
- dependency-name: mongoose
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-18 21:00:25 +00:00
492 changed files with 51780 additions and 25606 deletions

View File

@@ -60,6 +60,15 @@
"contributions": [ "contributions": [
"bug" "bug"
] ]
},
{
"login": "kochie",
"name": "Robert Koch",
"avatar_url": "https://avatars.githubusercontent.com/u/10809884?v=4",
"profile": "https://me.kochie.io",
"contributions": [
"code"
]
} }
], ],
"contributorsPerLine": 7, "contributorsPerLine": 7,

View File

@@ -8,7 +8,7 @@ MAIL_FROM_NAME=
MAIL_FROM_ADDRESS= MAIL_FROM_ADDRESS=
# Database # Database
DB_HOST=mysql DB_HOST=localhost
DB_USER=bigcapital DB_USER=bigcapital
DB_PASSWORD=bigcapital DB_PASSWORD=bigcapital
DB_ROOT_PASSWORD=root DB_ROOT_PASSWORD=root

13
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,13 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: Bigcapital # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']

7
.gitignore vendored
View File

@@ -1,4 +1,9 @@
node_modules/ node_modules/
data
# Docker volumes data directory
/data
# Production env file
.env .env
test-results/ test-results/

22
.gitpod.yml Normal file
View File

@@ -0,0 +1,22 @@
tasks:
- name: Init
init: |
pnpm install &&
cp .env.example .env &&
docker-compose up -d &&
pnpm run build:server &&
node packages/server/build/commands.js system:migrate:latest
command: |
docker-compose up -d &&
pnpm run dev
ports:
- port: 4000
visibility: public
onOpen: open-preview
- port: 3000
visibility: public
onOpen: ignore
- port: 3306
visibility: public
onOpen: ignore

View File

@@ -2,6 +2,34 @@
All notable changes to Bigcapital server-side will be in this file. All notable changes to Bigcapital server-side will be in this file.
# [0.10.1] - 25-09-2023
* Fix: Running tenants migration on Docker migration container by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/242
# [0.10.0] - 24-09-2023
* Added: Tax rates service by @abouolia @elforjani13 in https://github.com/bigcapitalhq/bigcapital/pull/204
* Added: Sales Tax Liability Summary report by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/204
* Added: Tax rates tracking with sale invoices by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/204
* fix(webapp): Table headers sticky for all reports. by @elforjani13 in https://github.com/bigcapitalhq/bigcapital/pull/240
* chore(deps): bump word-wrap from 1.2.3 to 1.2.4 by @dependabot in https://github.com/bigcapitalhq/bigcapital/pull/200
* chore(deps): bump word-wrap from 1.2.3 to 1.2.4 in /packages/webapp by @dependabot in https://github.com/bigcapitalhq/bigcapital/pull/199
* chore(deps): bump mongoose from 5.13.15 to 5.13.20 by @dependabot in https://github.com/bigcapitalhq/bigcapital/pull/197
# [0.9.12] - 29-08-2023
* Refactor: split the services to multiple service classes. (by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/202)
* Fix: create quick customer/vendor by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/206
* Fix: typo in bill success message without bill number by @KalliopiPliogka in https://github.com/bigcapitalhq/bigcapital/pull/219
* Fix: AP/AR aging summary issue by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/229
* Fix: shouldn't write GL entries when save transaction as draft. by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/221
* Fix: Transaction type of credit note and vendor credit are not defined on account transactions by @abouolia in
* Fix: date format of filtering transactions by date range by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/231
* Fix: change the default from/date date value of reports by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/230
* Fix: typos in words start with `A` letter by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/227
* Fix: filter by customers, vendors and items in reports do not work by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/224
https://github.com/bigcapitalhq/bigcapital/pull/225
# [0.9.11] - 23-07-2023 # [0.9.11] - 23-07-2023
* added: Restart policy to docker compose files. by @suhaibaffan in https://github.com/bigcapitalhq/bigcapital/pull/198 * added: Restart policy to docker compose files. by @suhaibaffan in https://github.com/bigcapitalhq/bigcapital/pull/198

View File

@@ -33,7 +33,8 @@ Contributions via pull requests are much appreciated. Once the approach is agree
--- ---
## Local Setup Prerequisites ## Local Setup Prerequisites
- The application currently supports **Node.js v14.x**. Please ensure that you are using this version of Node.js when developing. (use [nvm](https://github.com/nvm-sh/nvm#installing-and-updating) to switch between node versions) - The application currently supports **Node.js v18.x**.
- `pnpm` packages manager, (from pnpm [guide](https://pnpm.io/installation) pick any installation method).
## Contribute to Backend ## Contribute to Backend
@@ -44,11 +45,10 @@ Contributions via pull requests are much appreciated. Once the approach is agree
cp .env.example .env cp .env.example .env
``` ```
- Install all npm dependencies of the monorepo, you don't have to change directory to the `backend` package. just hit these command on root directory and it will install dependencies of all packages. - Install all npm dependencies of the monorepo, you don't have to change directory to the `backend` package. just hit the command on root directory and it will install dependencies of all packages.
``` ```
npm install pnpm install
npm run bootstrap
``` ```
- Run all required docker containers in the development, we already configured all containers under `docker-compose.yml`. - Run all required docker containers in the development, we already configured all containers under `docker-compose.yml`.
@@ -69,7 +69,7 @@ cefa73fe2881 bigcapital-redis "docker-entrypoint.s…" 7 seconds ago Up
- There're some CLI commands we should run before running the server like databaase migration, so we need to build the `server` app first. - There're some CLI commands we should run before running the server like databaase migration, so we need to build the `server` app first.
``` ```
npm run build:server pnpm run build:server
``` ```
- Run the database migration for system database. - Run the database migration for system database.
@@ -87,7 +87,7 @@ Batch 1 run: 6 migrations
- Next, start the webapp application. - Next, start the webapp application.
``` ```
npm run dev:server pnpm run dev:server
``` ```
**[`^top^`](#)** **[`^top^`](#)**
@@ -105,14 +105,13 @@ git clone https://github.com/bigcapital/bigcapital.git && cd bigcaptial
- Install all npm dependencies of the monorepo, you don't have to change directory to the `frontend` package. just hit that command and will install all packages across all application. - Install all npm dependencies of the monorepo, you don't have to change directory to the `frontend` package. just hit that command and will install all packages across all application.
``` ```
npm install pnpm install
npm run bootstrap
``` ```
- Next, start the webapp application. - Next, start the webapp application.
``` ```
npm run dev:webapp pnpm run dev:webapp
``` ```
**[`^top^`](#)** **[`^top^`](#)**

View File

@@ -37,6 +37,31 @@ Bigcapital is a smart and open-source accounting and inventory software, Bigcapi
<img src="https://raw.githubusercontent.com/abouolia/blog/main/public/screenshot-3.png" width="270"> <img src="https://raw.githubusercontent.com/abouolia/blog/main/public/screenshot-3.png" width="270">
</p> </p>
# Getting Started
We've got serveral options on dev and prod depending on your need to get started quickly with Bigcapital.
## Self-hosted
Bigcapital is available open-source under AGPL license. You can host it on your own servers using Docker.
### Docker
To get started with self-hosted with Docker and Docker Compose, take a look at the [Docker guide](https://docs.bigcapital.ly/deployment/docker).
## Development
### Local Setup
To get started locally, we have a [guide to help you](https://github.com/bigcapitalhq/bigcapital/blob/develop/CONTRIBUTING.md).
### Gitpod
- Click the Gitpod button below to open this project in development mode.
- This will open and configure the workspace in your browser with all the necessary dependencies.
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/new/#https://github.com/bigcapitalhq/bigcapital)
# Resources # Resources
- [Documentation](https://docs.bigcapital.ly/) - Learn how to use. - [Documentation](https://docs.bigcapital.ly/) - Learn how to use.
@@ -48,6 +73,12 @@ Bigcapital is a smart and open-source accounting and inventory software, Bigcapi
Please see [Releases](https://github.com/bigcapitalhq/bigcapital/releases) for more information what has changed recently. Please see [Releases](https://github.com/bigcapitalhq/bigcapital/releases) for more information what has changed recently.
# Contact us
Meet our sales team for any commercial inquiries.
<a target="_blank" href="https://cal.com/ahmed-bouhuolia-ekk3ph/30min"><img src="https://cal.com/book-with-cal-dark.svg" alt="Book us with Cal.com"></a>
# Recognition # Recognition
<a href="https://news.ycombinator.com/item?id=36118990"> <a href="https://news.ycombinator.com/item?id=36118990">
@@ -74,6 +105,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
<td align="center" valign="top" width="14.28%"><a href="https://scheibling.se"><img src="https://avatars.githubusercontent.com/u/24367830?v=4?s=100" width="100px;" alt="Lars Scheibling"/><br /><sub><b>Lars Scheibling</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3Ascheibling" title="Bug reports">🐛</a></td> <td align="center" valign="top" width="14.28%"><a href="https://scheibling.se"><img src="https://avatars.githubusercontent.com/u/24367830?v=4?s=100" width="100px;" alt="Lars Scheibling"/><br /><sub><b>Lars Scheibling</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3Ascheibling" title="Bug reports">🐛</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/suhaibaffan"><img src="https://avatars.githubusercontent.com/u/18115937?v=4?s=100" width="100px;" alt="Suhaib Affan"/><br /><sub><b>Suhaib Affan</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/commits?author=suhaibaffan" title="Code">💻</a></td> <td align="center" valign="top" width="14.28%"><a href="https://github.com/suhaibaffan"><img src="https://avatars.githubusercontent.com/u/18115937?v=4?s=100" width="100px;" alt="Suhaib Affan"/><br /><sub><b>Suhaib Affan</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/commits?author=suhaibaffan" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/KalliopiPliogka"><img src="https://avatars.githubusercontent.com/u/81677549?v=4?s=100" width="100px;" alt="Kalliopi Pliogka"/><br /><sub><b>Kalliopi Pliogka</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3AKalliopiPliogka" title="Bug reports">🐛</a></td> <td align="center" valign="top" width="14.28%"><a href="https://github.com/KalliopiPliogka"><img src="https://avatars.githubusercontent.com/u/81677549?v=4?s=100" width="100px;" alt="Kalliopi Pliogka"/><br /><sub><b>Kalliopi Pliogka</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3AKalliopiPliogka" title="Bug reports">🐛</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://me.kochie.io"><img src="https://avatars.githubusercontent.com/u/10809884?v=4?s=100" width="100px;" alt="Robert Koch"/><br /><sub><b>Robert Koch</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/commits?author=kochie" title="Code">💻</a></td>
</tr> </tr>
</tbody> </tbody>
</table> </table>

View File

@@ -15,8 +15,8 @@ services:
- ./data/logs/nginx/:/var/log/nginx - ./data/logs/nginx/:/var/log/nginx
- ./docker/certbot/certs/:/var/certs - ./docker/certbot/certs/:/var/certs
ports: ports:
- "${PUBLIC_PROXY_PORT:-80}:80" - '${PUBLIC_PROXY_PORT:-80}:80'
- "${PUBLIC_PROXY_SSL_PORT:-443}:443" - '${PUBLIC_PROXY_SSL_PORT:-443}:443'
tty: true tty: true
depends_on: depends_on:
- server - server
@@ -71,7 +71,7 @@ services:
# Authentication # Authentication
- JWT_SECRET=${JWT_SECRET} - JWT_SECRET=${JWT_SECRET}
# MongoDB # MongoDB
- MONGODB_DATABASE_URL=mongodb://mongo/bigcapital - MONGODB_DATABASE_URL=mongodb://mongo/bigcapital
# Application # Application
@@ -92,11 +92,14 @@ services:
context: ./ context: ./
dockerfile: docker/migration/Dockerfile dockerfile: docker/migration/Dockerfile
environment: environment:
# Database
- DB_HOST=mysql - DB_HOST=mysql
- DB_USER=${DB_USER} - DB_USER=${DB_USER}
- DB_PASSWORD=${DB_PASSWORD} - DB_PASSWORD=${DB_PASSWORD}
- DB_CHARSET=${DB_CHARSET} - DB_CHARSET=${DB_CHARSET}
- SYSTEM_DB_NAME=${SYSTEM_DB_NAME} - SYSTEM_DB_NAME=${SYSTEM_DB_NAME}
# Tenants databases
- TENANT_DB_NAME_PERFIX=${TENANT_DB_NAME_PERFIX}
depends_on: depends_on:
- mysql - mysql
@@ -136,7 +139,7 @@ services:
build: build:
context: ./docker/redis context: ./docker/redis
expose: expose:
- "6379" - '6379'
volumes: volumes:
- redis:/data - redis:/data

View File

@@ -34,5 +34,7 @@ WORKDIR /app/packages/server
RUN git clone https://github.com/vishnubob/wait-for-it.git RUN git clone https://github.com/vishnubob/wait-for-it.git
# Once we listen the mysql port run the migration task. ADD docker/migration/start.sh /
CMD ["./wait-for-it/wait-for-it.sh", "mysql:3306", "--", "node", "./build/commands.js", "system:migrate:latest"] RUN chmod +x /start.sh
CMD ["/start.sh"]

View File

@@ -0,0 +1,5 @@
# Migrate the master system database.
./wait-for-it/wait-for-it.sh mysql:3306 -- node ./build/commands.js system:migrate:latest
# Migrate all tenants.
./wait-for-it/wait-for-it.sh mysql:3306 -- node ./build/commands.js tenants:migrate:latest

View File

@@ -1,6 +1,7 @@
{ {
"$schema": "node_modules/lerna/schemas/lerna-schema.json", "$schema": "node_modules/lerna/schemas/lerna-schema.json",
"version": "independent",
"npmClient": "pnpm",
"useWorkspaces": true, "useWorkspaces": true,
"version": "0.9.6", "packages": ["packages/*"]
"npmClient": "npm" }
}

5730
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -2,7 +2,6 @@
"name": "bigcapital-monorepo", "name": "bigcapital-monorepo",
"private": true, "private": true,
"scripts": { "scripts": {
"bootstrap": "lerna exec npm install",
"dev": "lerna run dev", "dev": "lerna run dev",
"build": "lerna run build", "build": "lerna run build",
"dev:webapp": "lerna run dev --scope \"@bigcapital/webapp\"", "dev:webapp": "lerna run dev --scope \"@bigcapital/webapp\"",
@@ -13,10 +12,6 @@
"test:e2e": "playwright test", "test:e2e": "playwright test",
"prepare": "husky install" "prepare": "husky install"
}, },
"workspaces": [
"packages/*",
"shared/*"
],
"devDependencies": { "devDependencies": {
"@commitlint/cli": "^17.4.2", "@commitlint/cli": "^17.4.2",
"@commitlint/config-conventional": "^17.4.2", "@commitlint/config-conventional": "^17.4.2",
@@ -27,7 +22,7 @@
"lerna": "^6.4.1" "lerna": "^6.4.1"
}, },
"engines": { "engines": {
"node": "14.x" "node": "16.x || 17.x || 18.x"
}, },
"husky": { "husky": {
"hooks": { "hooks": {

View File

@@ -1,7 +1,6 @@
/node_modules/ /node_modules/
/.env /.env
/storage /storage
package-lock.json
stdout.log stdout.log
/dist /dist
/build /build

View File

@@ -1,4 +1,4 @@
FROM node:14.20-alpine as build FROM node:18.16.0-alpine as build
USER root USER root
@@ -83,15 +83,25 @@ WORKDIR /app
RUN chown node:node / RUN chown node:node /
# Install pnpm
RUN npm install -g pnpm
# Copy application dependency manifests to the container image. # Copy application dependency manifests to the container image.
COPY ./package*.json ./ COPY ./package*.json ./
COPY ./pnpm-lock.yaml ./pnpm-lock.yaml
COPY ./pnpm-workspace.yaml ./pnpm-workspace.yaml
COPY ./lerna.json ./lerna.json
COPY ./packages/server/package*.json ./packages/server/ COPY ./packages/server/package*.json ./packages/server/
COPY ./lerna.json ./lerna.json # Install application dependencies
RUN apk update
RUN apk add python3 build-base chromium
# Install app dependencies for production. # Set PYHTON env
RUN npm install ENV PYTHON=/usr/bin/python3
RUN npm run bootstrap
# Install packages dependencies for production.
RUN pnpm install
COPY --chown=node:node ./packages/server ./packages/server COPY --chown=node:node ./packages/server ./packages/server

13698
packages/server/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "@bigcapital/server", "name": "@bigcapital/server",
"version": "0.9.5", "version": "0.10.2",
"description": "", "description": "",
"main": "src/server.ts", "main": "src/server.ts",
"scripts": { "scripts": {
@@ -35,6 +35,7 @@
"babel-loader": "^9.1.2", "babel-loader": "^9.1.2",
"bcryptjs": "^2.4.3", "bcryptjs": "^2.4.3",
"bluebird": "^3.7.2", "bluebird": "^3.7.2",
"body-parser": "^1.20.2",
"compression": "^1.7.4", "compression": "^1.7.4",
"country-codes-list": "^1.6.8", "country-codes-list": "^1.6.8",
"cpy": "^8.1.2", "cpy": "^8.1.2",
@@ -42,7 +43,7 @@
"crypto-random-string": "^3.2.0", "crypto-random-string": "^3.2.0",
"csurf": "^1.10.0", "csurf": "^1.10.0",
"deep-map": "^2.0.0", "deep-map": "^2.0.0",
"deepdash": "^5.3.7", "deepdash": "^5.3.9",
"dotenv": "^8.1.0", "dotenv": "^8.1.0",
"errorhandler": "^1.5.1", "errorhandler": "^1.5.1",
"es6-weak-map": "^2.0.3", "es6-weak-map": "^2.0.3",
@@ -72,6 +73,8 @@
"memory-cache": "^0.2.0", "memory-cache": "^0.2.0",
"moment": "^2.24.0", "moment": "^2.24.0",
"moment-range": "^4.0.2", "moment-range": "^4.0.2",
"moment-timezone": "^0.5.43",
"mongodb": "^6.1.0",
"mongoose": "^5.10.0", "mongoose": "^5.10.0",
"mustache": "^3.0.3", "mustache": "^3.0.3",
"mysql": "^2.17.1", "mysql": "^2.17.1",
@@ -92,6 +95,7 @@
"rate-limiter-flexible": "^2.1.14", "rate-limiter-flexible": "^2.1.14",
"reflect-metadata": "^0.1.13", "reflect-metadata": "^0.1.13",
"rtl-detect": "^1.0.4", "rtl-detect": "^1.0.4",
"source-map-loader": "^4.0.1",
"ts-transformer-keys": "^0.4.2", "ts-transformer-keys": "^0.4.2",
"tsyringe": "^4.3.0", "tsyringe": "^4.3.0",
"typedi": "^0.8.0", "typedi": "^0.8.0",
@@ -131,7 +135,7 @@
"rimraf": "^3.0.2", "rimraf": "^3.0.2",
"rtlcss": "^3.3.0", "rtlcss": "^3.3.0",
"run-script-webpack-plugin": "^0.1.1", "run-script-webpack-plugin": "^0.1.1",
"sass": "^1.37.5", "sass": "^1.58.0",
"sinon": "^7.4.2", "sinon": "^7.4.2",
"start-server-webpack-plugin": "^2.2.5", "start-server-webpack-plugin": "^2.2.5",
"ts-loader": "^9.4.2", "ts-loader": "^9.4.2",

View File

@@ -587,6 +587,7 @@
"balance_sheet.long_term_liabilities": "Long-Term Liabilities", "balance_sheet.long_term_liabilities": "Long-Term Liabilities",
"balance_sheet.non_current_liabilities": "Non-Current Liabilities", "balance_sheet.non_current_liabilities": "Non-Current Liabilities",
"balance_sheet.equity": "Equity", "balance_sheet.equity": "Equity",
"balance_sheet.net_income": "Net Income",
"balance_sheet.account_name": "Account name", "balance_sheet.account_name": "Account name",
"balance_sheet.total": "Total", "balance_sheet.total": "Total",

View File

@@ -20,6 +20,7 @@ import InventoryDetailsController from './FinancialStatements/InventoryDetails';
import TransactionsByReferenceController from './FinancialStatements/TransactionsByReference'; import TransactionsByReferenceController from './FinancialStatements/TransactionsByReference';
import CashflowAccountTransactions from './FinancialStatements/CashflowAccountTransactions'; import CashflowAccountTransactions from './FinancialStatements/CashflowAccountTransactions';
import ProjectProfitabilityController from './FinancialStatements/ProjectProfitabilitySummary'; import ProjectProfitabilityController from './FinancialStatements/ProjectProfitabilitySummary';
import SalesTaxLiabilitySummary from './FinancialStatements/SalesTaxLiabilitySummary';
@Service() @Service()
export default class FinancialStatementsService { export default class FinancialStatementsService {
@@ -68,40 +69,44 @@ export default class FinancialStatementsService {
); );
router.use( router.use(
'/customer-balance-summary', '/customer-balance-summary',
Container.get(CustomerBalanceSummaryController).router(), Container.get(CustomerBalanceSummaryController).router()
); );
router.use( router.use(
'/vendor-balance-summary', '/vendor-balance-summary',
Container.get(VendorBalanceSummaryController).router(), Container.get(VendorBalanceSummaryController).router()
); );
router.use( router.use(
'/transactions-by-customers', '/transactions-by-customers',
Container.get(TransactionsByCustomers).router(), Container.get(TransactionsByCustomers).router()
); );
router.use( router.use(
'/transactions-by-vendors', '/transactions-by-vendors',
Container.get(TransactionsByVendors).router(), Container.get(TransactionsByVendors).router()
); );
router.use( router.use(
'/cash-flow', '/cash-flow',
Container.get(CashFlowStatementController).router(), Container.get(CashFlowStatementController).router()
); );
router.use( router.use(
'/inventory-item-details', '/inventory-item-details',
Container.get(InventoryDetailsController).router(), Container.get(InventoryDetailsController).router()
); );
router.use( router.use(
'/transactions-by-reference', '/transactions-by-reference',
Container.get(TransactionsByReferenceController).router(), Container.get(TransactionsByReferenceController).router()
); );
router.use( router.use(
'/cashflow-account-transactions', '/cashflow-account-transactions',
Container.get(CashflowAccountTransactions).router(), Container.get(CashflowAccountTransactions).router()
); );
router.use( router.use(
'/project-profitability-summary', '/project-profitability-summary',
Container.get(ProjectProfitabilityController).router(), Container.get(ProjectProfitabilityController).router()
) );
router.use(
'/sales-tax-liability-summary',
Container.get(SalesTaxLiabilitySummary).router()
);
return router; return router;
} }
} }

View File

@@ -0,0 +1,90 @@
import { Router, Request, Response, NextFunction } from 'express';
import { query } from 'express-validator';
import { Inject } from 'typedi';
import asyncMiddleware from '@/api/middleware/asyncMiddleware';
import BaseFinancialReportController from '../BaseFinancialReportController';
import { AbilitySubject, ReportsAction } from '@/interfaces';
import CheckPolicies from '@/api/middleware/CheckPolicies';
import { SalesTaxLiabilitySummaryService } from '@/services/FinancialStatements/SalesTaxLiabilitySummary/SalesTaxLiabilitySummaryService';
export default class SalesTaxLiabilitySummary extends BaseFinancialReportController {
@Inject()
private salesTaxLiabilitySummaryService: SalesTaxLiabilitySummaryService;
/**
* Router constructor.
*/
router() {
const router = Router();
router.get(
'/',
CheckPolicies(
ReportsAction.READ_SALES_TAX_LIABILITY_SUMMARY,
AbilitySubject.Report
),
this.validationSchema,
asyncMiddleware(this.salesTaxLiabilitySummary.bind(this))
);
return router;
}
/**
* Validation schema.
*/
get validationSchema() {
return [
query('from_date').optional().isISO8601(),
query('to_date').optional().isISO8601(),
];
}
/*
* Retrieves the sales tax liability summary.
* @param {Request} req -
* @param {Response} res -
* @param {NextFunction} next -
*/
async salesTaxLiabilitySummary(
req: Request,
res: Response,
next: NextFunction
) {
const { tenantId } = req;
const filter = this.matchedQueryData(req);
try {
const accept = this.accepts(req);
const acceptType = accept.types(['json', 'application/json+table']);
switch (acceptType) {
case 'application/json+table':
const salesTaxLiabilityTable =
await this.salesTaxLiabilitySummaryService.salesTaxLiabilitySummaryTable(
tenantId,
filter
);
return res.status(200).send({
table: salesTaxLiabilityTable.table,
query: salesTaxLiabilityTable.query,
meta: salesTaxLiabilityTable.meta,
});
case 'json':
default:
const salesTaxLiability =
await this.salesTaxLiabilitySummaryService.salesTaxLiability(
tenantId,
filter
);
return res.status(200).send({
data: salesTaxLiability.data,
query: salesTaxLiability.query,
meta: salesTaxLiability.meta,
});
}
} catch (error) {
next(error);
}
}
}

View File

@@ -16,7 +16,7 @@ export default class TrialBalanceSheetController extends BaseFinancialReportCont
/** /**
* Router constructor. * Router constructor.
*/ */
router() { public router() {
const router = Router(); const router = Router();
router.get( router.get(
@@ -36,7 +36,7 @@ export default class TrialBalanceSheetController extends BaseFinancialReportCont
* Validation schema. * Validation schema.
* @return {ValidationChain[]} * @return {ValidationChain[]}
*/ */
get trialBalanceSheetValidationSchema(): ValidationChain[] { private get trialBalanceSheetValidationSchema(): ValidationChain[] {
return [ return [
...this.sheetNumberFormatValidationSchema, ...this.sheetNumberFormatValidationSchema,
query('basis').optional(), query('basis').optional(),
@@ -59,28 +59,37 @@ export default class TrialBalanceSheetController extends BaseFinancialReportCont
/** /**
* Retrieve the trial balance sheet. * Retrieve the trial balance sheet.
*/ */
public async trialBalanceSheet( private async trialBalanceSheet(
req: Request, req: Request,
res: Response, res: Response,
next: NextFunction next: NextFunction
) { ) {
const { tenantId, settings } = req; const { tenantId } = req;
let filter = this.matchedQueryData(req); let filter = this.matchedQueryData(req);
filter = { filter = {
...filter, ...filter,
accountsIds: castArray(filter.accountsIds), accountsIds: castArray(filter.accountsIds),
}; };
try { try {
const { data, query, meta } = const accept = this.accepts(req);
await this.trialBalanceSheetService.trialBalanceSheet(tenantId, filter); const acceptType = accept.types(['json', 'application/json+table']);
return res.status(200).send({ if (acceptType === 'application/json+table') {
data: this.transfromToResponse(data), const { table, meta, query } =
query: this.transfromToResponse(query), await this.trialBalanceSheetService.trialBalanceSheetTable(
meta: this.transfromToResponse(meta), tenantId,
}); filter
);
return res.status(200).send({ table, meta, query });
} else {
const { data, query, meta } =
await this.trialBalanceSheetService.trialBalanceSheet(
tenantId,
filter
);
return res.status(200).send({ data, query, meta });
}
} catch (error) { } catch (error) {
next(error); next(error);
} }

View File

@@ -149,6 +149,11 @@ export default class ItemsController extends BaseController {
.trim() .trim()
.escape() .escape()
.isLength({ max: DATATYPES_LENGTH.TEXT }), .isLength({ max: DATATYPES_LENGTH.TEXT }),
check('sell_tax_rate_id').optional({ nullable: true }).isInt().toInt(),
check('purchase_tax_rate_id')
.optional({ nullable: true })
.isInt()
.toInt(),
check('category_id') check('category_id')
.optional({ nullable: true }) .optional({ nullable: true })
.isInt({ min: 0, max: DATATYPES_LENGTH.INT_10 }) .isInt({ min: 0, max: DATATYPES_LENGTH.INT_10 })
@@ -508,6 +513,28 @@ export default class ItemsController extends BaseController {
], ],
}); });
} }
if (error.errorType === 'PURCHASE_TAX_RATE_NOT_FOUND') {
return res.status(400).send({
errors: [
{
type: 'PURCHASE_TAX_RATE_NOT_FOUND',
message: 'Purchase tax rate has not found.',
code: 410,
},
],
});
}
if (error.errorType === 'SELL_TAX_RATE_NOT_FOUND') {
return res.status(400).send({
errors: [
{
type: 'SELL_TAX_RATE_NOT_FOUND',
message: 'Sell tax rate is not found.',
code: 420,
},
],
});
}
} }
next(error); next(error);
} }

View File

@@ -31,14 +31,14 @@ export default class OrganizationController extends BaseController {
router.post( router.post(
'/build', '/build',
this.organizationValidationSchema, this.buildOrganizationValidationSchema,
this.validationResult, this.validationResult,
asyncMiddleware(this.build.bind(this)), asyncMiddleware(this.build.bind(this)),
this.handleServiceErrors.bind(this) this.handleServiceErrors.bind(this)
); );
router.put( router.put(
'/', '/',
this.organizationValidationSchema, this.updateOrganizationValidationSchema,
this.validationResult, this.validationResult,
this.asyncMiddleware(this.updateOrganization.bind(this)), this.asyncMiddleware(this.updateOrganization.bind(this)),
this.handleServiceErrors.bind(this) this.handleServiceErrors.bind(this)
@@ -55,7 +55,7 @@ export default class OrganizationController extends BaseController {
* Organization setup schema. * Organization setup schema.
* @return {ValidationChain[]} * @return {ValidationChain[]}
*/ */
private get organizationValidationSchema(): ValidationChain[] { private get commonOrganizationValidationSchema(): ValidationChain[] {
return [ return [
check('name').exists().trim(), check('name').exists().trim(),
check('industry').optional({ nullable: true }).isString().trim().escape(), check('industry').optional({ nullable: true }).isString().trim().escape(),
@@ -68,6 +68,29 @@ export default class OrganizationController extends BaseController {
]; ];
} }
/**
* Build organization validation schema.
* @returns {ValidationChain[]}
*/
private get buildOrganizationValidationSchema(): ValidationChain[] {
return [...this.commonOrganizationValidationSchema];
}
/**
* Update organization validation schema.
* @returns {ValidationChain[]}
*/
private get updateOrganizationValidationSchema(): ValidationChain[] {
return [
...this.commonOrganizationValidationSchema,
check('tax_number')
.optional({ nullable: true })
.isString()
.trim()
.escape(),
];
}
/** /**
* Builds tenant database and migrate database schema. * Builds tenant database and migrate database schema.
* @param {Request} req - Express request. * @param {Request} req - Express request.

View File

@@ -115,6 +115,8 @@ export default class BillsController extends BaseController {
check('note').optional().trim().escape(), check('note').optional().trim().escape(),
check('open').default(false).isBoolean().toBoolean(), check('open').default(false).isBoolean().toBoolean(),
check('is_inclusive_tax').default(false).isBoolean().toBoolean(),
check('entries').isArray({ min: 1 }), check('entries').isArray({ min: 1 }),
check('entries.*.index').exists().isNumeric().toInt(), check('entries.*.index').exists().isNumeric().toInt(),
@@ -137,6 +139,15 @@ export default class BillsController extends BaseController {
.optional({ nullable: true }) .optional({ nullable: true })
.isNumeric() .isNumeric()
.toInt(), .toInt(),
check('entries.*.tax_code')
.optional({ nullable: true })
.trim()
.escape()
.isString(),
check('entries.*.tax_rate_id')
.optional({ nullable: true })
.isNumeric()
.toInt(),
]; ];
} }
@@ -542,6 +553,16 @@ export default class BillsController extends BaseController {
], ],
}); });
} }
if (error.errorType === 'ITEM_ENTRY_TAX_RATE_CODE_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'ITEM_ENTRY_TAX_RATE_CODE_NOT_FOUND', code: 1800 }],
});
}
if (error.errorType === 'ITEM_ENTRY_TAX_RATE_ID_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'ITEM_ENTRY_TAX_RATE_ID_NOT_FOUND', code: 1900 }],
});
}
} }
next(error); next(error);
} }

View File

@@ -169,8 +169,9 @@ export default class SaleInvoicesController extends BaseController {
check('branch_id').optional({ nullable: true }).isNumeric().toInt(), check('branch_id').optional({ nullable: true }).isNumeric().toInt(),
check('project_id').optional({ nullable: true }).isNumeric().toInt(), check('project_id').optional({ nullable: true }).isNumeric().toInt(),
check('entries').exists().isArray({ min: 1 }), check('is_inclusive_tax').optional().isBoolean().toBoolean(),
check('entries').exists().isArray({ min: 1 }),
check('entries.*.index').exists().isNumeric().toInt(), check('entries.*.index').exists().isNumeric().toInt(),
check('entries.*.item_id').exists().isNumeric().toInt(), check('entries.*.item_id').exists().isNumeric().toInt(),
check('entries.*.rate').exists().isNumeric().toFloat(), check('entries.*.rate').exists().isNumeric().toFloat(),
@@ -183,6 +184,15 @@ export default class SaleInvoicesController extends BaseController {
.optional({ nullable: true }) .optional({ nullable: true })
.trim() .trim()
.escape(), .escape(),
check('entries.*.tax_code')
.optional({ nullable: true })
.trim()
.escape()
.isString(),
check('entries.*.tax_rate_id')
.optional({ nullable: true })
.isNumeric()
.toInt(),
check('entries.*.warehouse_id') check('entries.*.warehouse_id')
.optional({ nullable: true }) .optional({ nullable: true })
.isNumeric() .isNumeric()
@@ -756,6 +766,16 @@ export default class SaleInvoicesController extends BaseController {
], ],
}); });
} }
if (error.errorType === 'ITEM_ENTRY_TAX_RATE_CODE_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'ITEM_ENTRY_TAX_RATE_CODE_NOT_FOUND', code: 5000 }],
});
}
if (error.errorType === 'ITEM_ENTRY_TAX_RATE_ID_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'ITEM_ENTRY_TAX_RATE_ID_NOT_FOUND', code: 5100 }],
});
}
} }
next(error); next(error);
} }

View File

@@ -0,0 +1,278 @@
import { Inject, Service } from 'typedi';
import { Router, Request, Response } from 'express';
import { body, param } from 'express-validator';
import BaseController from '@/api/controllers/BaseController';
import asyncMiddleware from '@/api/middleware/asyncMiddleware';
import { TaxRatesApplication } from '@/services/TaxRates/TaxRatesApplication';
import CheckAbilities from '@/api/middleware/CheckPolicies';
import { ServiceError } from '@/exceptions';
import { ERRORS } from '@/services/TaxRates/constants';
import { AbilitySubject, TaxRateAction } from '@/interfaces';
@Service()
export class TaxRatesController extends BaseController {
@Inject()
private taxRatesApplication: TaxRatesApplication;
/**
* Router constructor.
*/
public router() {
const router = Router();
router.post(
'/',
CheckAbilities(TaxRateAction.CREATE, AbilitySubject.TaxRate),
this.taxRateValidationSchema,
this.validationResult,
asyncMiddleware(this.createTaxRate.bind(this)),
this.handleServiceErrors
);
router.post(
'/:id',
CheckAbilities(TaxRateAction.EDIT, AbilitySubject.TaxRate),
[param('id').exists().toInt(), ...this.taxRateValidationSchema],
this.validationResult,
asyncMiddleware(this.editTaxRate.bind(this)),
this.handleServiceErrors
);
router.post(
'/:id/active',
CheckAbilities(TaxRateAction.EDIT, AbilitySubject.TaxRate),
[param('id').exists().toInt()],
this.validationResult,
asyncMiddleware(this.activateTaxRate.bind(this)),
this.handleServiceErrors
);
router.post(
'/:id/inactive',
CheckAbilities(TaxRateAction.EDIT, AbilitySubject.TaxRate),
[param('id').exists().toInt()],
this.validationResult,
asyncMiddleware(this.inactivateTaxRate.bind(this)),
this.handleServiceErrors
);
router.delete(
'/:id',
CheckAbilities(TaxRateAction.DELETE, AbilitySubject.TaxRate),
[param('id').exists().toInt()],
this.validationResult,
asyncMiddleware(this.deleteTaxRate.bind(this)),
this.handleServiceErrors
);
router.get(
'/:id',
CheckAbilities(TaxRateAction.VIEW, AbilitySubject.TaxRate),
[param('id').exists().toInt()],
this.validationResult,
asyncMiddleware(this.getTaxRate.bind(this)),
this.handleServiceErrors
);
router.get(
'/',
CheckAbilities(TaxRateAction.VIEW, AbilitySubject.TaxRate),
this.validationResult,
asyncMiddleware(this.getTaxRates.bind(this)),
this.handleServiceErrors
);
return router;
}
/**
* Tax rate validation schema.
*/
private get taxRateValidationSchema() {
return [
body('name').exists(),
body('code').exists().isString(),
body('rate').exists().isNumeric().toFloat(),
body('description').optional().trim().isString(),
body('is_non_recoverable').optional().isBoolean().default(false),
body('is_compound').optional().isBoolean().default(false),
body('active').optional().isBoolean().default(false),
];
}
/**
* Creates a new tax rate.
* @param {Request} req -
* @param {Response} res -
*/
public async createTaxRate(req: Request, res: Response, next) {
const { tenantId } = req;
const createTaxRateDTO = this.matchedBodyData(req);
try {
const taxRate = await this.taxRatesApplication.createTaxRate(
tenantId,
createTaxRateDTO
);
return res.status(200).send({
data: taxRate,
});
} catch (error) {
next(error);
}
}
/**
* Edits the given tax rate.
* @param {Request} req -
* @param {Response} res -
*/
public async editTaxRate(req: Request, res: Response, next) {
const { tenantId } = req;
const editTaxRateDTO = this.matchedBodyData(req);
const { id: taxRateId } = req.params;
try {
const taxRate = await this.taxRatesApplication.editTaxRate(
tenantId,
taxRateId,
editTaxRateDTO
);
return res.status(200).send({
data: taxRate,
});
} catch (error) {
next(error);
}
}
/**
* Deletes the given tax rate.
* @param {Request} req -
* @param {Response} res -
*/
public async deleteTaxRate(req: Request, res: Response, next) {
const { tenantId } = req;
const { id: taxRateId } = req.params;
try {
await this.taxRatesApplication.deleteTaxRate(tenantId, taxRateId);
return res.status(200).send({
code: 200,
message: 'The tax rate has been deleted successfully.',
});
} catch (error) {
next(error);
}
}
/**
* Retrieves the given tax rate.
* @param {Request} req -
* @param {Response} res -
*/
public async getTaxRate(req: Request, res: Response, next) {
const { tenantId } = req;
const { id: taxRateId } = req.params;
try {
const taxRate = await this.taxRatesApplication.getTaxRate(
tenantId,
taxRateId
);
return res.status(200).send({ data: taxRate });
} catch (error) {
next(error);
}
}
/**
* Retrieves the tax rates list.
* @param {Request} req -
* @param {Response} res -
*/
public async getTaxRates(req: Request, res: Response, next) {
const { tenantId } = req;
try {
const taxRates = await this.taxRatesApplication.getTaxRates(tenantId);
return res.status(200).send({ data: taxRates });
} catch (error) {
next(error);
}
}
/**
* Inactivates the given tax rate.
* @param req
* @param res
* @param next
* @returns
*/
public async inactivateTaxRate(req: Request, res: Response, next) {
const { tenantId } = req;
const { id: taxRateId } = req.params;
try {
await this.taxRatesApplication.inactivateTaxRate(tenantId, taxRateId);
return res.status(200).send({
id: taxRateId,
message: 'The given tax rate has been inactivated successfully.',
});
} catch (error) {
next(error);
}
}
/**
* Inactivates the given tax rate.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns
*/
public async activateTaxRate(req: Request, res: Response, next) {
const { tenantId } = req;
const { id: taxRateId } = req.params;
try {
await this.taxRatesApplication.activateTaxRate(tenantId, taxRateId);
return res.status(200).send({
id: taxRateId,
message: 'The given tax rate has been activated successfully.',
});
} catch (error) {
next(error);
}
}
/**
* Handles service errors.
* @param {Error} error
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
private handleServiceErrors(error: Error, req: Request, res: Response, next) {
if (error instanceof ServiceError) {
if (error.errorType === ERRORS.TAX_CODE_NOT_UNIQUE) {
return res.boom.badRequest(null, {
errors: [{ type: ERRORS.TAX_CODE_NOT_UNIQUE, code: 100 }],
});
}
if (error.errorType === ERRORS.TAX_RATE_NOT_FOUND) {
return res.boom.badRequest(null, {
errors: [{ type: ERRORS.TAX_RATE_NOT_FOUND, code: 200 }],
});
}
if (error.errorType === ERRORS.TAX_RATE_ALREADY_INACTIVE) {
return res.boom.badRequest(null, {
errors: [{ type: ERRORS.TAX_RATE_ALREADY_INACTIVE, code: 300 }],
});
}
if (error.errorType === ERRORS.TAX_RATE_ALREADY_ACTIVE) {
return res.boom.badRequest(null, {
errors: [{ type: ERRORS.TAX_RATE_ALREADY_ACTIVE, code: 400 }],
});
}
}
next(error);
}
}

View File

@@ -55,6 +55,7 @@ import { InventoryItemsCostController } from './controllers/Inventory/Inventorty
import { ProjectsController } from './controllers/Projects/Projects'; import { ProjectsController } from './controllers/Projects/Projects';
import { ProjectTasksController } from './controllers/Projects/Tasks'; import { ProjectTasksController } from './controllers/Projects/Tasks';
import { ProjectTimesController } from './controllers/Projects/Times'; import { ProjectTimesController } from './controllers/Projects/Times';
import { TaxRatesController } from './controllers/TaxRates/TaxRates';
export default () => { export default () => {
const app = Router(); const app = Router();
@@ -129,6 +130,7 @@ export default () => {
); );
dashboard.use('/warehouses', Container.get(WarehousesController).router()); dashboard.use('/warehouses', Container.get(WarehousesController).router());
dashboard.use('/projects', Container.get(ProjectsController).router()); dashboard.use('/projects', Container.get(ProjectsController).router());
dashboard.use('/tax-rates', Container.get(TaxRatesController).router());
dashboard.use('/', Container.get(ProjectTasksController).router()); dashboard.use('/', Container.get(ProjectTasksController).router());
dashboard.use('/', Container.get(ProjectTimesController).router()); dashboard.use('/', Container.get(ProjectTimesController).router());

View File

@@ -0,0 +1,28 @@
export const TransactionTypes = {
SaleInvoice: 'Sale invoice',
SaleReceipt: 'Sale receipt',
PaymentReceive: 'Payment receive',
Bill: 'Bill',
BillPayment: 'Payment made',
VendorOpeningBalance: 'Vendor opening balance',
CustomerOpeningBalance: 'Customer opening balance',
InventoryAdjustment: 'Inventory adjustment',
ManualJournal: 'Manual journal',
Journal: 'Manual journal',
Expense: 'Expense',
OwnerContribution: 'Owner contribution',
TransferToAccount: 'Transfer to account',
TransferFromAccount: 'Transfer from account',
OtherIncome: 'Other income',
OtherExpense: 'Other expense',
OwnerDrawing: 'Owner drawing',
InvoiceWriteOff: 'Invoice write-off',
CreditNote: 'transaction_type.credit_note',
VendorCredit: 'transaction_type.vendor_credit',
RefundCreditNote: 'transaction_type.refund_credit_note',
RefundVendorCredit: 'transaction_type.refund_vendor_credit',
LandedCost: 'transaction_type.landed_cost',
};

View File

@@ -0,0 +1,52 @@
exports.up = (knex) => {
return knex.schema
.createTable('tax_rates', (table) => {
table.increments();
table.string('name');
table.string('code');
table.decimal('rate');
table.string('description');
table.boolean('is_non_recoverable').defaultTo(false);
table.boolean('is_compound').defaultTo(false);
table.boolean('active').defaultTo(false);
table.date('deleted_at');
table.timestamps();
})
.table('items_entries', (table) => {
table.boolean('is_inclusive_tax').defaultTo(false);
table
.integer('tax_rate_id')
.unsigned()
.references('id')
.inTable('tax_rates');
table.decimal('tax_rate').unsigned();
})
.table('sales_invoices', (table) => {
table.boolean('is_inclusive_tax').defaultTo(false);
table.decimal('tax_amount_withheld');
})
.createTable('tax_rate_transactions', (table) => {
table.increments('id');
table
.integer('tax_rate_id')
.unsigned()
.references('id')
.inTable('tax_rates');
table.string('reference_type');
table.integer('reference_id');
table.decimal('rate').unsigned();
table.integer('tax_account_id').unsigned();
})
.table('accounts_transactions', (table) => {
table
.integer('tax_rate_id')
.unsigned()
.references('id')
.inTable('tax_rates');
table.decimal('tax_rate').unsigned();
});
};
exports.down = (knex) => {
return knex.schema.dropTableIfExists('tax_rates');
};

View File

@@ -0,0 +1,10 @@
exports.up = (knex) => {
return knex.schema.table('bills', (table) => {
table.boolean('is_inclusive_tax').defaultTo(false);
table.decimal('tax_amount_withheld');
});
};
exports.down = (knex) => {
return knex.schema.table('bills', () => {});
};

View File

@@ -0,0 +1,18 @@
exports.up = (knex) => {
return knex.schema.table('items', (table) => {
table
.integer('sell_tax_rate_id')
.unsigned()
.references('id')
.inTable('tax_rates');
table
.integer('purchase_tax_rate_id')
.unsigned()
.references('id')
.inTable('tax_rates');
});
};
exports.down = (knex) => {
return knex.schema.dropTableIfExists('tax_rates');
};

View File

@@ -0,0 +1,14 @@
import { TenantSeeder } from '@/lib/Seeder/TenantSeeder';
import { InitialTaxRates } from '../data/TaxRates';
export default class SeedTaxRates extends TenantSeeder {
/**
* Seeds initial tax rates to the organization.
*/
up(knex) {
return knex('tax_rates').then(async () => {
// Inserts seed entries.
return knex('tax_rates').insert(InitialTaxRates);
});
}
}

View File

@@ -0,0 +1,16 @@
import { TenantSeeder } from '@/lib/Seeder/TenantSeeder';
import { InitialTaxRates } from '../data/TaxRates';
export default class UpdateTaxPayableAccount extends TenantSeeder {
/**
* Seeds initial tax rates to the organization.
*/
up(knex) {
return knex('accounts').then(async () => {
// Inserts seed entries.
return knex('accounts').where('slug', 'tax-payable').update({
account_type: 'tax-payable',
});
});
}
}

View File

@@ -0,0 +1,30 @@
export const InitialTaxRates = [
{
name: 'Tax Exempt',
code: 'TAX-EXEMPT',
description: 'Exempts goods or services from taxes.',
rate: 0,
active: 1,
},
{
name: 'Tax on Purchases',
code: 'TAX-PURCHASES',
description: 'Fee added to the cost when you buy items.',
rate: 0,
active: 1,
},
{
name: 'Tax on Sales',
code: 'TAX-SALES',
description: 'Fee added to the cost when you sell items.',
rate: 0,
active: 1,
},
{
name: 'Sales Tax on Imports',
code: 'TAX-IMPORTS',
description: 'Fee added to the cost when you sale to another country.',
rate: 0,
active: 1,
},
];

View File

@@ -1,7 +1,17 @@
export const TaxPayableAccount = {
name: 'Tax Payable',
slug: 'tax-payable',
account_type: 'tax-payable',
code: '20006',
description: '',
active: 1,
index: 1,
predefined: 1,
};
export default [ export default [
{ {
name:'Bank Account', name: 'Bank Account',
slug: 'bank-account', slug: 'bank-account',
account_type: 'bank', account_type: 'bank',
code: '10001', code: '10001',
@@ -11,7 +21,7 @@ export default [
predefined: 1, predefined: 1,
}, },
{ {
name:'Saving Bank Account', name: 'Saving Bank Account',
slug: 'saving-bank-account', slug: 'saving-bank-account',
account_type: 'bank', account_type: 'bank',
code: '10002', code: '10002',
@@ -21,7 +31,7 @@ export default [
predefined: 0, predefined: 0,
}, },
{ {
name:'Undeposited Funds', name: 'Undeposited Funds',
slug: 'undeposited-funds', slug: 'undeposited-funds',
account_type: 'cash', account_type: 'cash',
code: '10003', code: '10003',
@@ -31,7 +41,7 @@ export default [
predefined: 1, predefined: 1,
}, },
{ {
name:'Petty Cash', name: 'Petty Cash',
slug: 'petty-cash', slug: 'petty-cash',
account_type: 'cash', account_type: 'cash',
code: '10004', code: '10004',
@@ -41,7 +51,7 @@ export default [
predefined: 1, predefined: 1,
}, },
{ {
name:'Computer Equipment', name: 'Computer Equipment',
slug: 'computer-equipment', slug: 'computer-equipment',
code: '10005', code: '10005',
account_type: 'fixed-asset', account_type: 'fixed-asset',
@@ -52,7 +62,7 @@ export default [
description: '', description: '',
}, },
{ {
name:'Office Equipment', name: 'Office Equipment',
slug: 'office-equipment', slug: 'office-equipment',
code: '10006', code: '10006',
account_type: 'fixed-asset', account_type: 'fixed-asset',
@@ -63,7 +73,7 @@ export default [
description: '', description: '',
}, },
{ {
name:'Accounts Receivable (A/R)', name: 'Accounts Receivable (A/R)',
slug: 'accounts-receivable', slug: 'accounts-receivable',
account_type: 'accounts-receivable', account_type: 'accounts-receivable',
code: '10007', code: '10007',
@@ -73,7 +83,7 @@ export default [
predefined: 1, predefined: 1,
}, },
{ {
name:'Inventory Asset', name: 'Inventory Asset',
slug: 'inventory-asset', slug: 'inventory-asset',
code: '10008', code: '10008',
account_type: 'inventory', account_type: 'inventory',
@@ -81,12 +91,13 @@ export default [
parent_account_id: null, parent_account_id: null,
index: 1, index: 1,
active: 1, active: 1,
description:'An account that holds valuation of products or goods that available for sale.', description:
'An account that holds valuation of products or goods that available for sale.',
}, },
// Libilities // Libilities
{ {
name:'Accounts Payable (A/P)', name: 'Accounts Payable (A/P)',
slug: 'accounts-payable', slug: 'accounts-payable',
account_type: 'accounts-payable', account_type: 'accounts-payable',
parent_account_id: null, parent_account_id: null,
@@ -97,38 +108,39 @@ export default [
predefined: 1, predefined: 1,
}, },
{ {
name:'Owner A Drawings', name: 'Owner A Drawings',
slug: 'owner-drawings', slug: 'owner-drawings',
account_type: 'other-current-liability', account_type: 'other-current-liability',
parent_account_id: null, parent_account_id: null,
code: '20002', code: '20002',
description:'Withdrawals by the owners.', description: 'Withdrawals by the owners.',
active: 1, active: 1,
index: 1, index: 1,
predefined: 0, predefined: 0,
}, },
{ {
name:'Loan', name: 'Loan',
slug: 'owner-drawings', slug: 'owner-drawings',
account_type: 'other-current-liability', account_type: 'other-current-liability',
code: '20003', code: '20003',
description:'Money that has been borrowed from a creditor.', description: 'Money that has been borrowed from a creditor.',
active: 1, active: 1,
index: 1, index: 1,
predefined: 0, predefined: 0,
}, },
{ {
name:'Opening Balance Liabilities', name: 'Opening Balance Liabilities',
slug: 'opening-balance-liabilities', slug: 'opening-balance-liabilities',
account_type: 'other-current-liability', account_type: 'other-current-liability',
code: '20004', code: '20004',
description:'This account will hold the difference in the debits and credits entered during the opening balance..', description:
'This account will hold the difference in the debits and credits entered during the opening balance..',
active: 1, active: 1,
index: 1, index: 1,
predefined: 0, predefined: 0,
}, },
{ {
name:'Revenue Received in Advance', name: 'Revenue Received in Advance',
slug: 'revenue-received-in-advance', slug: 'revenue-received-in-advance',
account_type: 'other-current-liability', account_type: 'other-current-liability',
parent_account_id: null, parent_account_id: null,
@@ -138,34 +150,27 @@ export default [
index: 1, index: 1,
predefined: 0, predefined: 0,
}, },
{ TaxPayableAccount,
name:'Sales Tax Payable',
slug: 'owner-drawings',
account_type: 'other-current-liability',
code: '20006',
description: '',
active: 1,
index: 1,
predefined: 1,
},
// Equity // Equity
{ {
name:'Retained Earnings', name: 'Retained Earnings',
slug: 'retained-earnings', slug: 'retained-earnings',
account_type: 'equity', account_type: 'equity',
code: '30001', code: '30001',
description:'Retained earnings tracks net income from previous fiscal years.', description:
'Retained earnings tracks net income from previous fiscal years.',
active: 1, active: 1,
index: 1, index: 1,
predefined: 1, predefined: 1,
}, },
{ {
name:'Opening Balance Equity', name: 'Opening Balance Equity',
slug: 'opening-balance-equity', slug: 'opening-balance-equity',
account_type: 'equity', account_type: 'equity',
code: '30002', code: '30002',
description:'When you enter opening balances to the accounts, the amounts enter in Opening balance equity. This ensures that you have a correct trial balance sheet for your company, without even specific the second credit or debit entry.', description:
'When you enter opening balances to the accounts, the amounts enter in Opening balance equity. This ensures that you have a correct trial balance sheet for your company, without even specific the second credit or debit entry.',
active: 1, active: 1,
index: 1, index: 1,
predefined: 1, predefined: 1,
@@ -181,11 +186,12 @@ export default [
predefined: 1, predefined: 1,
}, },
{ {
name:`Drawings`, name: `Drawings`,
slug: 'drawings', slug: 'drawings',
account_type: 'equity', account_type: 'equity',
code: '30003', code: '30003',
description:'Goods purchased with the intention of selling these to customers', description:
'Goods purchased with the intention of selling these to customers',
active: 1, active: 1,
index: 1, index: 1,
predefined: 1, predefined: 1,
@@ -193,7 +199,7 @@ export default [
// Expenses // Expenses
{ {
name:'Other Expenses', name: 'Other Expenses',
slug: 'other-expenses', slug: 'other-expenses',
account_type: 'other-expense', account_type: 'other-expense',
parent_account_id: null, parent_account_id: null,
@@ -204,18 +210,18 @@ export default [
predefined: 1, predefined: 1,
}, },
{ {
name:'Cost of Goods Sold', name: 'Cost of Goods Sold',
slug: 'cost-of-goods-sold', slug: 'cost-of-goods-sold',
account_type: 'cost-of-goods-sold', account_type: 'cost-of-goods-sold',
parent_account_id: null, parent_account_id: null,
code: '40002', code: '40002',
description:'Tracks the direct cost of the goods sold.', description: 'Tracks the direct cost of the goods sold.',
active: 1, active: 1,
index: 1, index: 1,
predefined: 1, predefined: 1,
}, },
{ {
name:'Office expenses', name: 'Office expenses',
slug: 'office-expenses', slug: 'office-expenses',
account_type: 'expense', account_type: 'expense',
parent_account_id: null, parent_account_id: null,
@@ -226,7 +232,7 @@ export default [
predefined: 0, predefined: 0,
}, },
{ {
name:'Rent', name: 'Rent',
slug: 'rent', slug: 'rent',
account_type: 'expense', account_type: 'expense',
parent_account_id: null, parent_account_id: null,
@@ -237,29 +243,30 @@ export default [
predefined: 0, predefined: 0,
}, },
{ {
name:'Exchange Gain or Loss', name: 'Exchange Gain or Loss',
slug: 'exchange-grain-loss', slug: 'exchange-grain-loss',
account_type: 'other-expense', account_type: 'other-expense',
parent_account_id: null, parent_account_id: null,
code: '40005', code: '40005',
description:'Tracks the gain and losses of the exchange differences.', description: 'Tracks the gain and losses of the exchange differences.',
active: 1, active: 1,
index: 1, index: 1,
predefined: 1, predefined: 1,
}, },
{ {
name:'Bank Fees and Charges', name: 'Bank Fees and Charges',
slug: 'bank-fees-and-charges', slug: 'bank-fees-and-charges',
account_type: 'expense', account_type: 'expense',
parent_account_id: null, parent_account_id: null,
code: '40006', code: '40006',
description: 'Any bank fees levied is recorded into the bank fees and charges account. A bank account maintenance fee, transaction charges, a late payment fee are some examples.', description:
'Any bank fees levied is recorded into the bank fees and charges account. A bank account maintenance fee, transaction charges, a late payment fee are some examples.',
active: 1, active: 1,
index: 1, index: 1,
predefined: 0, predefined: 0,
}, },
{ {
name:'Depreciation Expense', name: 'Depreciation Expense',
slug: 'depreciation-expense', slug: 'depreciation-expense',
account_type: 'expense', account_type: 'expense',
parent_account_id: null, parent_account_id: null,
@@ -272,7 +279,7 @@ export default [
// Income // Income
{ {
name:'Sales of Product Income', name: 'Sales of Product Income',
slug: 'sales-of-product-income', slug: 'sales-of-product-income',
account_type: 'income', account_type: 'income',
predefined: 1, predefined: 1,
@@ -283,7 +290,7 @@ export default [
description: '', description: '',
}, },
{ {
name:'Sales of Service Income', name: 'Sales of Service Income',
slug: 'sales-of-service-income', slug: 'sales-of-service-income',
account_type: 'income', account_type: 'income',
predefined: 0, predefined: 0,
@@ -294,7 +301,7 @@ export default [
description: '', description: '',
}, },
{ {
name:'Uncategorized Income', name: 'Uncategorized Income',
slug: 'uncategorized-income', slug: 'uncategorized-income',
account_type: 'income', account_type: 'income',
parent_account_id: null, parent_account_id: null,
@@ -305,14 +312,15 @@ export default [
predefined: 1, predefined: 1,
}, },
{ {
name:'Other Income', name: 'Other Income',
slug: 'other-income', slug: 'other-income',
account_type: 'other-income', account_type: 'other-income',
parent_account_id: null, parent_account_id: null,
code: '50004', code: '50004',
description:'The income activities are not associated to the core business.', description:
'The income activities are not associated to the core business.',
active: 1, active: 1,
index: 1, index: 1,
predefined: 0, predefined: 0,
} },
]; ];

View File

@@ -77,6 +77,9 @@ export interface IAccountTransaction {
projectId?: number; projectId?: number;
account?: IAccount; account?: IAccount;
taxRateId?: number;
taxRate?: number;
} }
export interface IAccountResponse extends IAccount {} export interface IAccountResponse extends IAccount {}
@@ -150,3 +153,11 @@ export enum AccountAction {
VIEW = 'View', VIEW = 'View',
TransactionsLocking = 'TransactionsLocking', TransactionsLocking = 'TransactionsLocking',
} }
export enum TaxRateAction {
CREATE = 'Create',
EDIT = 'Edit',
DELETE = 'Delete',
VIEW = 'View',
}

View File

@@ -9,6 +9,7 @@ export enum BALANCE_SHEET_SCHEMA_NODE_TYPE {
AGGREGATE = 'AGGREGATE', AGGREGATE = 'AGGREGATE',
ACCOUNTS = 'ACCOUNTS', ACCOUNTS = 'ACCOUNTS',
ACCOUNT = 'ACCOUNT', ACCOUNT = 'ACCOUNT',
NET_INCOME = 'NET_INCOME',
} }
export enum BALANCE_SHEET_NODE_TYPE { export enum BALANCE_SHEET_NODE_TYPE {
@@ -33,6 +34,7 @@ export enum BALANCE_SHEET_SCHEMA_NODE_ID {
LOGN_TERM_LIABILITY = 'LOGN_TERM_LIABILITY', LOGN_TERM_LIABILITY = 'LOGN_TERM_LIABILITY',
NON_CURRENT_LIABILITY = 'NON_CURRENT_LIABILITY', NON_CURRENT_LIABILITY = 'NON_CURRENT_LIABILITY',
EQUITY = 'EQUITY', EQUITY = 'EQUITY',
NET_INCOME = 'NET_INCOME',
} }
// Balance sheet query. // Balance sheet query.
@@ -87,7 +89,6 @@ export interface IBalanceSheetDOO {
meta: IBalanceSheetMeta; meta: IBalanceSheetMeta;
} }
export interface IBalanceSheetCommonNode { export interface IBalanceSheetCommonNode {
total: IBalanceSheetTotal; total: IBalanceSheetTotal;
horizontalTotals?: IBalanceSheetTotal[]; horizontalTotals?: IBalanceSheetTotal[];
@@ -108,7 +109,7 @@ export interface IBalanceSheetAggregateNode extends IBalanceSheetCommonNode {
id: string; id: string;
name: string; name: string;
nodeType: BALANCE_SHEET_SCHEMA_NODE_TYPE.AGGREGATE; nodeType: BALANCE_SHEET_SCHEMA_NODE_TYPE.AGGREGATE;
children?: (IBalanceSheetAggregateNode | IBalanceSheetAccountNode)[]; children?: IBalanceSheetDataNode[];
} }
export interface IBalanceSheetTotal { export interface IBalanceSheetTotal {
@@ -118,6 +119,13 @@ export interface IBalanceSheetTotal {
date?: string | Date; date?: string | Date;
} }
export interface IBalanceSheetAccountsNode extends IBalanceSheetCommonNode {
id: number | string;
name: string;
nodeType: BALANCE_SHEET_SCHEMA_NODE_TYPE.ACCOUNTS;
children: IBalanceSheetAccountNode[];
}
export interface IBalanceSheetAccountNode extends IBalanceSheetCommonNode { export interface IBalanceSheetAccountNode extends IBalanceSheetCommonNode {
id: number; id: number;
index: number; index: number;
@@ -128,7 +136,17 @@ export interface IBalanceSheetAccountNode extends IBalanceSheetCommonNode {
children?: IBalanceSheetAccountNode[]; children?: IBalanceSheetAccountNode[];
} }
export type IBalanceSheetDataNode = IBalanceSheetAggregateNode; export interface IBalanceSheetNetIncomeNode extends IBalanceSheetCommonNode {
id: number;
name: string;
nodeType: BALANCE_SHEET_SCHEMA_NODE_TYPE.NET_INCOME;
}
export type IBalanceSheetDataNode =
| IBalanceSheetAggregateNode
| IBalanceSheetAccountNode
| IBalanceSheetAccountsNode
| IBalanceSheetNetIncomeNode;
export interface IBalanceSheetPercentageAmount { export interface IBalanceSheetPercentageAmount {
amount: number; amount: number;
@@ -150,9 +168,16 @@ export interface IBalanceSheetSchemaAccountNode {
accountsTypes: string[]; accountsTypes: string[];
} }
export interface IBalanceSheetSchemaNetIncomeNode {
id: string;
name: string;
type: BALANCE_SHEET_SCHEMA_NODE_TYPE;
}
export type IBalanceSheetSchemaNode = export type IBalanceSheetSchemaNode =
| IBalanceSheetSchemaAccountNode | IBalanceSheetSchemaAccountNode
| IBalanceSheetSchemaAggregateNode; | IBalanceSheetSchemaAggregateNode
| IBalanceSheetSchemaNetIncomeNode;
export interface IBalanceSheetDatePeriods { export interface IBalanceSheetDatePeriods {
assocAccountNodeDatePeriods(node): any; assocAccountNodeDatePeriods(node): any;

View File

@@ -2,6 +2,7 @@ import { Knex } from 'knex';
import { IDynamicListFilterDTO } from './DynamicFilter'; import { IDynamicListFilterDTO } from './DynamicFilter';
import { IItemEntry, IItemEntryDTO } from './ItemEntry'; import { IItemEntry, IItemEntryDTO } from './ItemEntry';
import { IBillLandedCost } from './LandedCost'; import { IBillLandedCost } from './LandedCost';
export interface IBillDTO { export interface IBillDTO {
vendorId: number; vendorId: number;
billNumber: string; billNumber: string;
@@ -15,10 +16,10 @@ export interface IBillDTO {
exchangeRate?: number; exchangeRate?: number;
open: boolean; open: boolean;
entries: IItemEntryDTO[]; entries: IItemEntryDTO[];
branchId?: number; branchId?: number;
warehouseId?: number; warehouseId?: number;
projectId?: number; projectId?: number;
isInclusiveTax?: boolean;
} }
export interface IBillEditDTO { export interface IBillEditDTO {
@@ -80,6 +81,15 @@ export interface IBill {
localAmount?: number; localAmount?: number;
locatedLandedCosts?: IBillLandedCost[]; locatedLandedCosts?: IBillLandedCost[];
amountLocal: number;
subtotal: number;
subtotalLocal: number;
subtotalExcludingTax: number;
taxAmountWithheld: number;
taxAmountWithheldLocal: number;
total: number;
totalLocal: number;
} }
export interface IBillsFilter extends IDynamicListFilterDTO { export interface IBillsFilter extends IDynamicListFilterDTO {

View File

@@ -37,6 +37,7 @@ export enum ReportsAction {
READ_INVENTORY_ITEM_DETAILS = 'read-inventory-item-details', READ_INVENTORY_ITEM_DETAILS = 'read-inventory-item-details',
READ_CASHFLOW_ACCOUNT_TRANSACTION = 'read-cashflow-account-transactions', READ_CASHFLOW_ACCOUNT_TRANSACTION = 'read-cashflow-account-transactions',
READ_PROJECT_PROFITABILITY_SUMMARY = 'read-project-profitability-summary', READ_PROJECT_PROFITABILITY_SUMMARY = 'read-project-profitability-summary',
READ_SALES_TAX_LIABILITY_SUMMARY = 'read-sales-tax-liability-summary',
} }
export interface IFinancialSheetBranchesQuery { export interface IFinancialSheetBranchesQuery {

View File

@@ -22,6 +22,9 @@ export interface IItem {
sellDescription: string; sellDescription: string;
purchaseDescription: string; purchaseDescription: string;
sellTaxRateId: number;
purchaseTaxRateId: number;
quantityOnHand: number; quantityOnHand: number;
note: string; note: string;
@@ -54,6 +57,9 @@ export interface IItemDTO {
sellDescription: string; sellDescription: string;
purchaseDescription: string; purchaseDescription: string;
sellTaxRateId: number;
purchaseTaxRateId: number;
quantityOnHand: number; quantityOnHand: number;
note: string; note: string;

View File

@@ -18,6 +18,11 @@ export interface IItemEntry {
rate: number; rate: number;
amount: number; amount: number;
total: number;
amountInclusingTax: number;
amountExludingTax: number;
discountAmount: number;
landedCost: number; landedCost: number;
allocatedCostAmount: number; allocatedCostAmount: number;
unallocatedCostAmount: number; unallocatedCostAmount: number;
@@ -32,6 +37,10 @@ export interface IItemEntry {
projectRefType?: ProjectLinkRefType; projectRefType?: ProjectLinkRefType;
projectRefInvoicedAmount?: number; projectRefInvoicedAmount?: number;
taxRateId: number | null;
taxRate: number;
taxAmount: number;
item?: IItem; item?: IItem;
allocatedCostEntries?: IBillLandedCostEntry[]; allocatedCostEntries?: IBillLandedCostEntry[];
@@ -46,6 +55,9 @@ export interface IItemEntryDTO {
projectRefId?: number; projectRefId?: number;
projectRefType?: ProjectLinkRefType; projectRefType?: ProjectLinkRefType;
projectRefInvoicedAmount?: number; projectRefInvoicedAmount?: number;
taxRateId?: number;
taxCode?: string;
} }
export enum ProjectLinkRefType { export enum ProjectLinkRefType {

View File

@@ -7,18 +7,25 @@ export interface ILedger {
filter(cb: (entry: ILedgerEntry) => boolean): ILedger; filter(cb: (entry: ILedgerEntry) => boolean): ILedger;
whereAccountId(accountId: number): ILedger; whereAccountId(accountId: number): ILedger;
whereAccountsIds(accountsIds: number[]): ILedger;
whereContactId(contactId: number): ILedger; whereContactId(contactId: number): ILedger;
whereFromDate(fromDate: Date | string): ILedger; whereFromDate(fromDate: Date | string): ILedger;
whereToDate(toDate: Date | string): ILedger; whereToDate(toDate: Date | string): ILedger;
whereCurrencyCode(currencyCode: string): ILedger; whereCurrencyCode(currencyCode: string): ILedger;
whereBranch(branchId: number): ILedger; whereBranch(branchId: number): ILedger;
whereItem(itemId: number): ILedger; whereItem(itemId: number): ILedger;
whereProject(projectId: number): ILedger;
getClosingBalance(): number; getClosingBalance(): number;
getForeignClosingBalance(): number; getForeignClosingBalance(): number;
getClosingDebit(): number;
getClosingCredit(): number;
getContactsIds(): number[]; getContactsIds(): number[];
getAccountsIds(): number[]; getAccountsIds(): number[];
reverse(): ILedger;
isEmpty(): boolean;
} }
export interface ILedgerEntry { export interface ILedgerEntry {
@@ -48,6 +55,9 @@ export interface ILedgerEntry {
branchId?: number; branchId?: number;
projectId?: number; projectId?: number;
taxRateId?: number;
taxRate?: number;
entryId?: number; entryId?: number;
createdAt?: Date; createdAt?: Date;

View File

@@ -1,5 +1,5 @@
import { Knex } from 'knex'; import { Knex } from 'knex';
import { IItemEntry } from './ItemEntry'; import { IItemEntry, IItemEntryDTO } from './ItemEntry';
import { IDynamicListFilterDTO } from '@/interfaces/DynamicFilter'; import { IDynamicListFilterDTO } from '@/interfaces/DynamicFilter';
export interface ISaleEstimate { export interface ISaleEstimate {
@@ -29,7 +29,7 @@ export interface ISaleEstimateDTO {
estimateDate?: Date; estimateDate?: Date;
reference?: string; reference?: string;
estimateNumber?: string; estimateNumber?: string;
entries: IItemEntry[]; entries: IItemEntryDTO[];
note: string; note: string;
termsConditions: string; termsConditions: string;
sendToEmail: string; sendToEmail: string;

View File

@@ -1,11 +1,12 @@
import { Knex } from 'knex'; import { Knex } from 'knex';
import { ISystemUser, IAccount } from '@/interfaces'; import { ISystemUser, IAccount, ITaxTransaction } from '@/interfaces';
import { IDynamicListFilter } from '@/interfaces/DynamicFilter'; import { IDynamicListFilter } from '@/interfaces/DynamicFilter';
import { IItemEntry, IItemEntryDTO } from './ItemEntry'; import { IItemEntry, IItemEntryDTO } from './ItemEntry';
export interface ISaleInvoice { export interface ISaleInvoice {
id: number; id: number;
balance: number; amount: number;
amountLocal?: number;
paymentAmount: number; paymentAmount: number;
currencyCode: string; currencyCode: string;
exchangeRate?: number; exchangeRate?: number;
@@ -27,12 +28,21 @@ export interface ISaleInvoice {
branchId?: number; branchId?: number;
projectId?: number; projectId?: number;
localAmount?: number; writtenoffAmount?: number;
writtenoffAmountLocal?: number;
localWrittenoffAmount?: number;
writtenoffExpenseAccountId?: number; writtenoffExpenseAccountId?: number;
writtenoffExpenseAccount?: IAccount; writtenoffExpenseAccount?: IAccount;
taxAmountWithheld: number;
taxAmountWithheldLocal: number;
taxes: ITaxTransaction[];
total: number;
totalLocal: number;
subtotal: number;
subtotalLocal: number;
subtotalExludingTax: number;
} }
export interface ISaleInvoiceDTO { export interface ISaleInvoiceDTO {
@@ -44,12 +54,15 @@ export interface ISaleInvoiceDTO {
exchangeRate?: number; exchangeRate?: number;
invoiceMessage: string; invoiceMessage: string;
termsConditions: string; termsConditions: string;
isTaxExclusive: boolean;
entries: IItemEntryDTO[]; entries: IItemEntryDTO[];
delivered: boolean; delivered: boolean;
warehouseId?: number | null; warehouseId?: number | null;
projectId?: number; projectId?: number;
branchId?: number | null; branchId?: number | null;
isInclusiveTax?: boolean;
} }
export interface ISaleInvoiceCreateDTO extends ISaleInvoiceDTO { export interface ISaleInvoiceCreateDTO extends ISaleInvoiceDTO {

View File

@@ -0,0 +1,51 @@
export interface SalesTaxLiabilitySummaryQuery {
fromDate: Date;
toDate: Date;
basis: 'cash' | 'accrual';
}
export interface SalesTaxLiabilitySummaryAmount {
amount: number;
formattedAmount: string;
currencyCode: string;
}
export interface SalesTaxLiabilitySummaryTotal {
taxableAmount: SalesTaxLiabilitySummaryAmount;
taxAmount: SalesTaxLiabilitySummaryAmount;
collectedTaxAmount: SalesTaxLiabilitySummaryAmount;
}
export interface SalesTaxLiabilitySummaryRate {
id: number;
taxName: string;
taxableAmount: SalesTaxLiabilitySummaryAmount;
taxAmount: SalesTaxLiabilitySummaryAmount;
taxPercentage: any;
collectedTaxAmount: SalesTaxLiabilitySummaryAmount;
}
export enum SalesTaxLiabilitySummaryTableRowType {
TaxRate = 'TaxRate',
Total = 'Total',
}
export interface SalesTaxLiabilitySummaryReportData {
taxRates: SalesTaxLiabilitySummaryRate[];
total: SalesTaxLiabilitySummaryTotal;
}
export type SalesTaxLiabilitySummaryPayableById = Record<
string,
{ taxRateId: number; credit: number; debit: number }
>;
export type SalesTaxLiabilitySummarySalesById = Record<
string,
{ taxRateId: number; credit: number; debit: number }
>;
export interface SalesTaxLiabilitySummaryMeta {
organizationName: string;
baseCurrency: string;
}

View File

@@ -25,6 +25,7 @@ export interface IOrganizationUpdateDTO {
timezone: string; timezone: string;
fiscalYear: string; fiscalYear: string;
industry: string; industry: string;
taxNumber: string;
} }
export interface IOrganizationBuildEventPayload { export interface IOrganizationBuildEventPayload {

View File

@@ -0,0 +1,89 @@
import { Knex } from 'knex';
export interface ITaxRate {
id?: number;
name: string;
code: string;
rate: number;
description: string;
IsNonRecoverable: boolean;
IsCompound: boolean;
active: boolean;
}
export interface ICommonTaxRateDTO {
name: string;
code: string;
rate: number;
description: string;
IsNonRecoverable: boolean;
IsCompound: boolean;
active: boolean;
}
export interface ICreateTaxRateDTO extends ICommonTaxRateDTO {}
export interface IEditTaxRateDTO extends ICommonTaxRateDTO {}
export interface ITaxRateCreatingPayload {
createTaxRateDTO: ICreateTaxRateDTO;
tenantId: number;
trx: Knex.Transaction;
}
export interface ITaxRateCreatedPayload {
createTaxRateDTO: ICreateTaxRateDTO;
taxRate: ITaxRate;
tenantId: number;
trx: Knex.Transaction;
}
export interface ITaxRateEditingPayload {
oldTaxRate: ITaxRate;
editTaxRateDTO: IEditTaxRateDTO;
tenantId: number;
trx: Knex.Transaction;
}
export interface ITaxRateEditedPayload {
editTaxRateDTO: IEditTaxRateDTO;
oldTaxRate: ITaxRate;
taxRate: ITaxRate;
tenantId: number;
trx: Knex.Transaction;
}
export interface ITaxRateDeletingPayload {
oldTaxRate: ITaxRate;
tenantId: number;
trx: Knex.Transaction;
}
export interface ITaxRateActivatingPayload {
taxRateId: number;
tenantId: number;
trx: Knex.Transaction;
}
export interface ITaxRateActivatedPayload {
taxRateId: number;
tenantId: number;
trx: Knex.Transaction;
}
export interface ITaxRateDeletedPayload {
oldTaxRate: ITaxRate;
tenantId: number;
trx: Knex.Transaction;
}
export interface ITaxTransaction {
id?: number;
taxRateId: number;
referenceType: string;
referenceId: number;
rate: number;
taxAccountId: number;
}
export enum TaxRateAction {
CREATE = 'Create',
EDIT = 'Edit',
DELETE = 'Delete',
VIEW = 'View',
}

View File

@@ -33,6 +33,7 @@ export interface ITrialBalanceAccount extends ITrialBalanceTotal {
id: number; id: number;
parentAccountId: number; parentAccountId: number;
name: string; name: string;
formattedName: string;
code: string; code: string;
accountNormal: string; accountNormal: string;
} }

View File

@@ -73,6 +73,7 @@ export * from './Project';
export * from './Tasks'; export * from './Tasks';
export * from './Times'; export * from './Times';
export * from './ProjectProfitabilitySummary'; export * from './ProjectProfitabilitySummary';
export * from './TaxRate';
export interface I18nService { export interface I18nService {
__: (input: string) => string; __: (input: string) => string;

View File

@@ -1,8 +1,7 @@
import moment from 'moment'; import moment from 'moment';
import * as R from 'ramda'; import * as R from 'ramda';
import { includes, isFunction, isObject, isUndefined, omit } from 'lodash'; import { includes, isFunction, isObject, isUndefined, omit } from 'lodash';
import { formatNumber } from 'utils'; import { formatNumber, sortObjectKeysAlphabetically } from 'utils';
import { isArrayLikeObject } from 'lodash/fp';
export class Transformer { export class Transformer {
public context: any; public context: any;
@@ -82,6 +81,7 @@ export class Transformer {
const normlizedItem = this.normalizeModelItem(item); const normlizedItem = this.normalizeModelItem(item);
return R.compose( return R.compose(
sortObjectKeysAlphabetically,
this.transform, this.transform,
R.when(this.hasExcludeAttributes, this.excludeAttributesTransformed), R.when(this.hasExcludeAttributes, this.excludeAttributesTransformed),
this.includeAttributesTransformed this.includeAttributesTransformed

View File

@@ -79,6 +79,11 @@ import { ProjectBillableTasksSubscriber } from '@/services/Projects/Projects/Pro
import { ProjectBillableExpensesSubscriber } from '@/services/Projects/Projects/ProjectBillableExpenseSubscriber'; import { ProjectBillableExpensesSubscriber } from '@/services/Projects/Projects/ProjectBillableExpenseSubscriber';
import { ProjectBillableBillSubscriber } from '@/services/Projects/Projects/ProjectBillableBillSubscriber'; import { ProjectBillableBillSubscriber } from '@/services/Projects/Projects/ProjectBillableBillSubscriber';
import { SyncActualTimeTaskSubscriber } from '@/services/Projects/Times/SyncActualTimeTaskSubscriber'; import { SyncActualTimeTaskSubscriber } from '@/services/Projects/Times/SyncActualTimeTaskSubscriber';
import { SaleInvoiceTaxRateValidateSubscriber } from '@/services/TaxRates/subscribers/SaleInvoiceTaxRateValidateSubscriber';
import { WriteInvoiceTaxTransactionsSubscriber } from '@/services/TaxRates/subscribers/WriteInvoiceTaxTransactionsSubscriber';
import { BillTaxRateValidateSubscriber } from '@/services/TaxRates/subscribers/BillTaxRateValidateSubscriber';
import { WriteBillTaxTransactionsSubscriber } from '@/services/TaxRates/subscribers/WriteBillTaxTransactionsSubscriber';
import { SyncItemTaxRateOnEditTaxSubscriber } from '@/services/TaxRates/SyncItemTaxRateOnEditTaxSubscriber';
export default () => { export default () => {
return new EventPublisher(); return new EventPublisher();
@@ -185,5 +190,15 @@ export const susbcribers = () => {
ProjectBillableTasksSubscriber, ProjectBillableTasksSubscriber,
ProjectBillableExpensesSubscriber, ProjectBillableExpensesSubscriber,
ProjectBillableBillSubscriber, ProjectBillableBillSubscriber,
// Tax Rates - Sale Invoice
SaleInvoiceTaxRateValidateSubscriber,
WriteInvoiceTaxTransactionsSubscriber,
// Tax Rates - Bills
BillTaxRateValidateSubscriber,
WriteBillTaxTransactionsSubscriber,
SyncItemTaxRateOnEditTaxSubscriber
]; ];
}; };

View File

@@ -58,6 +58,8 @@ import ItemWarehouseQuantity from 'models/ItemWarehouseQuantity';
import Project from 'models/Project'; import Project from 'models/Project';
import Time from 'models/Time'; import Time from 'models/Time';
import Task from 'models/Task'; import Task from 'models/Task';
import TaxRate from 'models/TaxRate';
import TaxRateTransaction from 'models/TaxRateTransaction';
export default (knex) => { export default (knex) => {
const models = { const models = {
@@ -119,6 +121,8 @@ export default (knex) => {
Project, Project,
Time, Time,
Task, Task,
TaxRate,
TaxRateTransaction,
}; };
return mapValues(models, (model) => model.bindKnex(knex)); return mapValues(models, (model) => model.bindKnex(knex));
}; };

View File

@@ -587,6 +587,7 @@
"balance_sheet.long_term_liabilities": "Long-Term Liabilities", "balance_sheet.long_term_liabilities": "Long-Term Liabilities",
"balance_sheet.non_current_liabilities": "Non-Current Liabilities", "balance_sheet.non_current_liabilities": "Non-Current Liabilities",
"balance_sheet.equity": "Equity", "balance_sheet.equity": "Equity",
"balance_sheet.net_income": "Net Income",
"balance_sheet.account_name": "Account name", "balance_sheet.account_name": "Account name",
"balance_sheet.total": "Total", "balance_sheet.total": "Total",

View File

@@ -6,6 +6,10 @@ import { getTransactionTypeLabel } from '@/utils/transactions-types';
export default class AccountTransaction extends TenantModel { export default class AccountTransaction extends TenantModel {
referenceType: string; referenceType: string;
credit: number;
debit: number;
exchangeRate: number;
taxRate: number;
/** /**
* Table name * Table name
@@ -25,7 +29,23 @@ export default class AccountTransaction extends TenantModel {
* Virtual attributes. * Virtual attributes.
*/ */
static get virtualAttributes() { static get virtualAttributes() {
return ['referenceTypeFormatted']; return ['referenceTypeFormatted', 'creditLocal', 'debitLocal'];
}
/**
* Retrieves the credit amount in base currency.
* @return {number}
*/
get creditLocal() {
return this.credit * this.exchangeRate;
}
/**
* Retrieves the debit amount in base currency.
* @return {number}
*/
get debitLocal() {
return this.debit * this.exchangeRate;
} }
/** /**
@@ -59,15 +79,9 @@ export default class AccountTransaction extends TenantModel {
} }
}, },
filterDateRange(query, startDate, endDate, type = 'day') { filterDateRange(query, startDate, endDate, type = 'day') {
const dateFormat = 'YYYY-MM-DD HH:mm:ss'; const dateFormat = 'YYYY-MM-DD';
const fromDate = moment(startDate) const fromDate = moment(startDate).startOf(type).format(dateFormat);
.utcOffset(0) const toDate = moment(endDate).endOf(type).format(dateFormat);
.startOf(type)
.format(dateFormat);
const toDate = moment(endDate)
.utcOffset(0)
.endOf(type)
.format(dateFormat);
if (startDate) { if (startDate) {
query.where('date', '>=', fromDate); query.where('date', '>=', fromDate);
@@ -111,7 +125,6 @@ export default class AccountTransaction extends TenantModel {
query.modify('filterDateRange', null, toDate); query.modify('filterDateRange', null, toDate);
query.modify('sumationCreditDebit'); query.modify('sumationCreditDebit');
}, },
contactsOpeningBalance( contactsOpeningBalance(
query, query,
openingDate, openingDate,

View File

@@ -13,6 +13,109 @@ export default class Bill extends mixin(TenantModel, [
CustomViewBaseModel, CustomViewBaseModel,
ModelSearchable, ModelSearchable,
]) { ]) {
public amount: number;
public paymentAmount: number;
public landedCostAmount: number;
public allocatedCostAmount: number;
public isInclusiveTax: boolean;
public taxAmountWithheld: number;
public exchangeRate: number;
/**
* Timestamps columns.
*/
get timestamps() {
return ['createdAt', 'updatedAt'];
}
/**
* Virtual attributes.
*/
static get virtualAttributes() {
return [
'balance',
'dueAmount',
'isOpen',
'isPartiallyPaid',
'isFullyPaid',
'isPaid',
'remainingDays',
'overdueDays',
'isOverdue',
'unallocatedCostAmount',
'localAmount',
'localAllocatedCostAmount',
'billableAmount',
'amountLocal',
'subtotal',
'subtotalLocal',
'subtotalExludingTax',
'taxAmountWithheldLocal',
'total',
'totalLocal',
];
}
/**
* Invoice amount in base currency.
* @returns {number}
*/
get amountLocal() {
return this.amount * this.exchangeRate;
}
/**
* Subtotal. (Tax inclusive) if the tax inclusive is enabled.
* @returns {number}
*/
get subtotal() {
return this.amount;
}
/**
* Subtotal in base currency. (Tax inclusive) if the tax inclusive is enabled.
* @returns {number}
*/
get subtotalLocal() {
return this.amountLocal;
}
/**
* Sale invoice amount excluding tax.
* @returns {number}
*/
get subtotalExcludingTax() {
return this.isInclusiveTax
? this.subtotal - this.taxAmountWithheld
: this.subtotal;
}
/**
* Tax amount withheld in base currency.
* @returns {number}
*/
get taxAmountWithheldLocal() {
return this.taxAmountWithheld * this.exchangeRate;
}
/**
* Invoice total. (Tax included)
* @returns {number}
*/
get total() {
return this.isInclusiveTax
? this.subtotal
: this.subtotal + this.taxAmountWithheld;
}
/**
* Invoice total in local currency. (Tax included)
* @returns {number}
*/
get totalLocal() {
return this.total * this.exchangeRate;
}
/** /**
* Table name * Table name
*/ */
@@ -158,40 +261,13 @@ export default class Bill extends mixin(TenantModel, [
}; };
} }
/**
* Timestamps columns.
*/
get timestamps() {
return ['createdAt', 'updatedAt'];
}
/**
* Virtual attributes.
*/
static get virtualAttributes() {
return [
'balance',
'dueAmount',
'isOpen',
'isPartiallyPaid',
'isFullyPaid',
'isPaid',
'remainingDays',
'overdueDays',
'isOverdue',
'unallocatedCostAmount',
'localAmount',
'localAllocatedCostAmount',
'billableAmount',
];
}
/** /**
* Invoice amount in organization base currency. * Invoice amount in organization base currency.
* @deprecated
* @returns {number} * @returns {number}
*/ */
get localAmount() { get localAmount() {
return this.amount * this.exchangeRate; return this.amountLocal;
} }
/** /**
@@ -231,7 +307,7 @@ export default class Bill extends mixin(TenantModel, [
* @return {number} * @return {number}
*/ */
get dueAmount() { get dueAmount() {
return Math.max(this.amount - this.balance, 0); return Math.max(this.total - this.balance, 0);
} }
/** /**
@@ -247,7 +323,7 @@ export default class Bill extends mixin(TenantModel, [
* @return {boolean} * @return {boolean}
*/ */
get isPartiallyPaid() { get isPartiallyPaid() {
return this.dueAmount !== this.amount && this.dueAmount > 0; return this.dueAmount !== this.total && this.dueAmount > 0;
} }
/** /**
@@ -308,7 +384,7 @@ export default class Bill extends mixin(TenantModel, [
* Retrieves the calculated amount which have not been invoiced. * Retrieves the calculated amount which have not been invoiced.
*/ */
get billableAmount() { get billableAmount() {
return Math.max(this.amount - this.invoicedAmount, 0); return Math.max(this.total - this.invoicedAmount, 0);
} }
/** /**
@@ -326,6 +402,7 @@ export default class Bill extends mixin(TenantModel, [
const ItemEntry = require('models/ItemEntry'); const ItemEntry = require('models/ItemEntry');
const BillLandedCost = require('models/BillLandedCost'); const BillLandedCost = require('models/BillLandedCost');
const Branch = require('models/Branch'); const Branch = require('models/Branch');
const TaxRateTransaction = require('models/TaxRateTransaction');
return { return {
vendor: { vendor: {
@@ -373,6 +450,21 @@ export default class Bill extends mixin(TenantModel, [
to: 'branches.id', to: 'branches.id',
}, },
}, },
/**
* Bill may has associated tax rate transactions.
*/
taxes: {
relation: Model.HasManyRelation,
modelClass: TaxRateTransaction.default,
join: {
from: 'bills.id',
to: 'tax_rate_transactions.referenceId',
},
filter(builder) {
builder.where('reference_type', 'Bill');
},
},
}; };
} }

View File

@@ -33,7 +33,7 @@ export default class InventoryCostLotTracker extends TenantModel {
query.groupBy('item_id'); query.groupBy('item_id');
}, },
filterDateRange(query, startDate, endDate, type = 'day') { filterDateRange(query, startDate, endDate, type = 'day') {
const dateFormat = 'YYYY-MM-DD HH:mm:ss'; const dateFormat = 'YYYY-MM-DD';
const fromDate = moment(startDate).startOf(type).format(dateFormat); const fromDate = moment(startDate).startOf(type).format(dateFormat);
const toDate = moment(endDate).endOf(type).format(dateFormat); const toDate = moment(endDate).endOf(type).format(dateFormat);

View File

@@ -36,7 +36,7 @@ export default class InventoryTransaction extends TenantModel {
static get modifiers() { static get modifiers() {
return { return {
filterDateRange(query, startDate, endDate, type = 'day') { filterDateRange(query, startDate, endDate, type = 'day') {
const dateFormat = 'YYYY-MM-DD HH:mm:ss'; const dateFormat = 'YYYY-MM-DD';
const fromDate = moment(startDate).startOf(type).format(dateFormat); const fromDate = moment(startDate).startOf(type).format(dateFormat);
const toDate = moment(endDate).endOf(type).format(dateFormat); const toDate = moment(endDate).endOf(type).format(dateFormat);

View File

@@ -65,6 +65,7 @@ export default class Item extends mixin(TenantModel, [
const ItemEntry = require('models/ItemEntry'); const ItemEntry = require('models/ItemEntry');
const WarehouseTransferEntry = require('models/WarehouseTransferEntry'); const WarehouseTransferEntry = require('models/WarehouseTransferEntry');
const InventoryAdjustmentEntry = require('models/InventoryAdjustmentEntry'); const InventoryAdjustmentEntry = require('models/InventoryAdjustmentEntry');
const TaxRate = require('models/TaxRate');
return { return {
/** /**
@@ -178,11 +179,35 @@ export default class Item extends mixin(TenantModel, [
to: 'media.id', to: 'media.id',
}, },
}, },
/**
* Item may has sell tax rate.
*/
sellTaxRate: {
relation: Model.BelongsToOneRelation,
modelClass: TaxRate.default,
join: {
from: 'items.sellTaxRateId',
to: 'tax_rates.id',
},
},
/**
* Item may has purchase tax rate.
*/
purchaseTaxRate: {
relation: Model.BelongsToOneRelation,
modelClass: TaxRate.default,
join: {
from: 'items.purchaseTaxRateId',
to: 'tax_rates.id',
},
},
}; };
} }
/** /**
* *
*/ */
static get secureDeleteRelations() { static get secureDeleteRelations() {
return [ return [

View File

@@ -1,9 +1,17 @@
import { Model } from 'objection'; import { Model } from 'objection';
import TenantModel from 'models/TenantModel'; import TenantModel from 'models/TenantModel';
import { getExlusiveTaxAmount, getInclusiveTaxAmount } from '@/utils/taxRate';
export default class ItemEntry extends TenantModel { export default class ItemEntry extends TenantModel {
public taxRate: number;
public discount: number;
public quantity: number;
public rate: number;
public isInclusiveTax: number;
/** /**
* Table name. * Table name.
* @returns {string}
*/ */
static get tableName() { static get tableName() {
return 'items_entries'; return 'items_entries';
@@ -11,17 +19,84 @@ export default class ItemEntry extends TenantModel {
/** /**
* Timestamps columns. * Timestamps columns.
* @returns {string[]}
*/ */
get timestamps() { get timestamps() {
return ['created_at', 'updated_at']; return ['created_at', 'updated_at'];
} }
/**
* Virtual attributes.
* @returns {string[]}
*/
static get virtualAttributes() { static get virtualAttributes() {
return ['amount']; return [
'amount',
'taxAmount',
'amountExludingTax',
'amountInclusingTax',
'total',
];
} }
/**
* Item entry total.
* Amount of item entry includes tax and subtracted discount amount.
* @returns {number}
*/
get total() {
return this.amountInclusingTax;
}
/**
* Item entry amount.
* Amount of item entry that may include or exclude tax.
* @returns {number}
*/
get amount() { get amount() {
return ItemEntry.calcAmount(this); return this.quantity * this.rate;
}
/**
* Item entry amount including tax.
* @returns {number}
*/
get amountInclusingTax() {
return this.isInclusiveTax ? this.amount : this.amount + this.taxAmount;
}
/**
* Item entry amount excluding tax.
* @returns {number}
*/
get amountExludingTax() {
return this.isInclusiveTax ? this.amount - this.taxAmount : this.amount;
}
/**
* Discount amount.
* @returns {number}
*/
get discountAmount() {
return this.amount * (this.discount / 100);
}
/**
* Tag rate fraction.
* @returns {number}
*/
get tagRateFraction() {
return this.taxRate / 100;
}
/**
* Tax amount withheld.
* @returns {number}
*/
get taxAmount() {
return this.isInclusiveTax
? getInclusiveTaxAmount(this.amount, this.taxRate)
: getExlusiveTaxAmount(this.amount, this.taxRate);
} }
static calcAmount(itemEntry) { static calcAmount(itemEntry) {
@@ -31,6 +106,9 @@ export default class ItemEntry extends TenantModel {
return discount ? total - total * discount * 0.01 : total; return discount ? total - total * discount * 0.01 : total;
} }
/**
* Item entry relations.
*/
static get relationMappings() { static get relationMappings() {
const Item = require('models/Item'); const Item = require('models/Item');
const BillLandedCostEntry = require('models/BillLandedCostEntry'); const BillLandedCostEntry = require('models/BillLandedCostEntry');
@@ -40,6 +118,7 @@ export default class ItemEntry extends TenantModel {
const SaleEstimate = require('models/SaleEstimate'); const SaleEstimate = require('models/SaleEstimate');
const ProjectTask = require('models/Task'); const ProjectTask = require('models/Task');
const Expense = require('models/Expense'); const Expense = require('models/Expense');
const TaxRate = require('models/TaxRate');
return { return {
item: { item: {
@@ -86,6 +165,9 @@ export default class ItemEntry extends TenantModel {
}, },
}, },
/**
* Sale receipt reference.
*/
receipt: { receipt: {
relation: Model.BelongsToOneRelation, relation: Model.BelongsToOneRelation,
modelClass: SaleReceipt.default, modelClass: SaleReceipt.default,
@@ -96,7 +178,7 @@ export default class ItemEntry extends TenantModel {
}, },
/** /**
* * Project task reference.
*/ */
projectTaskRef: { projectTaskRef: {
relation: Model.HasManyRelation, relation: Model.HasManyRelation,
@@ -108,7 +190,7 @@ export default class ItemEntry extends TenantModel {
}, },
/** /**
* * Project expense reference.
*/ */
projectExpenseRef: { projectExpenseRef: {
relation: Model.HasManyRelation, relation: Model.HasManyRelation,
@@ -120,7 +202,7 @@ export default class ItemEntry extends TenantModel {
}, },
/** /**
* * Project bill reference.
*/ */
projectBillRef: { projectBillRef: {
relation: Model.HasManyRelation, relation: Model.HasManyRelation,
@@ -130,6 +212,18 @@ export default class ItemEntry extends TenantModel {
to: 'bills.id', to: 'bills.id',
}, },
}, },
/**
* Tax rate reference.
*/
tax: {
relation: Model.HasOneRelation,
modelClass: TaxRate.default,
join: {
from: 'items_entries.taxRateId',
to: 'tax_rates.id',
},
},
}; };
} }
} }

View File

@@ -1,5 +1,5 @@
import { mixin, Model, raw } from 'objection'; import { mixin, Model, raw } from 'objection';
import { castArray } from 'lodash'; import { castArray, takeWhile } from 'lodash';
import moment from 'moment'; import moment from 'moment';
import TenantModel from 'models/TenantModel'; import TenantModel from 'models/TenantModel';
import ModelSetting from './ModelSetting'; import ModelSetting from './ModelSetting';
@@ -13,6 +13,17 @@ export default class SaleInvoice extends mixin(TenantModel, [
CustomViewBaseModel, CustomViewBaseModel,
ModelSearchable, ModelSearchable,
]) { ]) {
public taxAmountWithheld: number;
public balance: number;
public paymentAmount: number;
public exchangeRate: number;
public writtenoffAmount: number;
public creditedAmount: number;
public isInclusiveTax: boolean;
public writtenoffAt: Date;
public dueDate: Date;
public deliveredAt: Date;
/** /**
* Table name * Table name
*/ */
@@ -27,6 +38,9 @@ export default class SaleInvoice extends mixin(TenantModel, [
return ['created_at', 'updated_at']; return ['created_at', 'updated_at'];
} }
/**
*
*/
get pluralName() { get pluralName() {
return 'asdfsdf'; return 'asdfsdf';
} }
@@ -36,35 +50,97 @@ export default class SaleInvoice extends mixin(TenantModel, [
*/ */
static get virtualAttributes() { static get virtualAttributes() {
return [ return [
'localAmount',
'dueAmount',
'balanceAmount',
'isDelivered', 'isDelivered',
'isOverdue', 'isOverdue',
'isPartiallyPaid', 'isPartiallyPaid',
'isFullyPaid', 'isFullyPaid',
'isPaid',
'isWrittenoff', 'isWrittenoff',
'isPaid',
'dueAmount',
'balanceAmount',
'remainingDays', 'remainingDays',
'overdueDays', 'overdueDays',
'filterByBranches',
'subtotal',
'subtotalLocal',
'subtotalExludingTax',
'taxAmountWithheldLocal',
'total',
'totalLocal',
'writtenoffAmountLocal',
]; ];
} }
/** /**
* Invoice amount in local currency. * Invoice amount.
* @todo Sugger attribute to balance, we need to rename the balance to amount.
* @returns {number} * @returns {number}
*/ */
get localAmount() { get amount() {
return this.balance * this.exchangeRate; return this.balance;
} }
/** /**
* Invoice local written-off amount. * Invoice amount in base currency.
* @returns {number} * @returns {number}
*/ */
get localWrittenoffAmount() { get amountLocal() {
return this.writtenoffAmount * this.exchangeRate; return this.amount * this.exchangeRate;
}
/**
* Subtotal. (Tax inclusive) if the tax inclusive is enabled.
* @returns {number}
*/
get subtotal() {
return this.amount;
}
/**
* Subtotal in base currency. (Tax inclusive) if the tax inclusive is enabled.
* @returns {number}
*/
get subtotalLocal() {
return this.amountLocal;
}
/**
* Sale invoice amount excluding tax.
* @returns {number}
*/
get subtotalExludingTax() {
return this.isInclusiveTax
? this.subtotal - this.taxAmountWithheld
: this.subtotal;
}
/**
* Tax amount withheld in base currency.
* @returns {number}
*/
get taxAmountWithheldLocal() {
return this.taxAmountWithheld * this.exchangeRate;
}
/**
* Invoice total. (Tax included)
* @returns {number}
*/
get total() {
return this.isInclusiveTax
? this.subtotal
: this.subtotal + this.taxAmountWithheld;
}
/**
* Invoice total in local currency. (Tax included)
* @returns {number}
*/
get totalLocal() {
return this.total * this.exchangeRate;
} }
/** /**
@@ -97,7 +173,7 @@ export default class SaleInvoice extends mixin(TenantModel, [
* @return {boolean} * @return {boolean}
*/ */
get dueAmount() { get dueAmount() {
return Math.max(this.balance - this.balanceAmount, 0); return Math.max(this.total - this.balanceAmount, 0);
} }
/** /**
@@ -105,7 +181,7 @@ export default class SaleInvoice extends mixin(TenantModel, [
* @return {boolean} * @return {boolean}
*/ */
get isPartiallyPaid() { get isPartiallyPaid() {
return this.dueAmount !== this.balance && this.dueAmount > 0; return this.dueAmount !== this.total && this.dueAmount > 0;
} }
/** /**
@@ -176,7 +252,7 @@ export default class SaleInvoice extends mixin(TenantModel, [
* Filters the invoices between the given date range. * Filters the invoices between the given date range.
*/ */
filterDateRange(query, startDate, endDate, type = 'day') { filterDateRange(query, startDate, endDate, type = 'day') {
const dateFormat = 'YYYY-MM-DD HH:mm:ss'; const dateFormat = 'YYYY-MM-DD';
const fromDate = moment(startDate).startOf(type).format(dateFormat); const fromDate = moment(startDate).startOf(type).format(dateFormat);
const toDate = moment(endDate).endOf(type).format(dateFormat); const toDate = moment(endDate).endOf(type).format(dateFormat);
@@ -333,6 +409,7 @@ export default class SaleInvoice extends mixin(TenantModel, [
const PaymentReceiveEntry = require('models/PaymentReceiveEntry'); const PaymentReceiveEntry = require('models/PaymentReceiveEntry');
const Branch = require('models/Branch'); const Branch = require('models/Branch');
const Account = require('models/Account'); const Account = require('models/Account');
const TaxRateTransaction = require('models/TaxRateTransaction');
return { return {
/** /**
@@ -382,7 +459,7 @@ export default class SaleInvoice extends mixin(TenantModel, [
}, },
/** /**
* * Invoice may has associated cost transactions.
*/ */
costTransactions: { costTransactions: {
relation: Model.HasManyRelation, relation: Model.HasManyRelation,
@@ -397,7 +474,7 @@ export default class SaleInvoice extends mixin(TenantModel, [
}, },
/** /**
* * Invoice may has associated payment entries.
*/ */
paymentEntries: { paymentEntries: {
relation: Model.HasManyRelation, relation: Model.HasManyRelation,
@@ -420,6 +497,9 @@ export default class SaleInvoice extends mixin(TenantModel, [
}, },
}, },
/**
* Invoice may has associated written-off expense account.
*/
writtenoffExpenseAccount: { writtenoffExpenseAccount: {
relation: Model.BelongsToOneRelation, relation: Model.BelongsToOneRelation,
modelClass: Account.default, modelClass: Account.default,
@@ -428,6 +508,21 @@ export default class SaleInvoice extends mixin(TenantModel, [
to: 'accounts.id', to: 'accounts.id',
}, },
}, },
/**
* Invoice may has associated tax rate transactions.
*/
taxes: {
relation: Model.HasManyRelation,
modelClass: TaxRateTransaction.default,
join: {
from: 'sales_invoices.id',
to: 'tax_rate_transactions.referenceId',
},
filter(builder) {
builder.where('reference_type', 'SaleInvoice');
},
},
}; };
} }

View File

@@ -0,0 +1,48 @@
import { mixin, Model, raw } from 'objection';
import TenantModel from 'models/TenantModel';
import ModelSearchable from './ModelSearchable';
import SoftDeleteQueryBuilder from '@/collection/SoftDeleteQueryBuilder';
export default class TaxRate extends mixin(TenantModel, [ModelSearchable]) {
/**
* Table name
*/
static get tableName() {
return 'tax_rates';
}
/**
* Soft delete query builder.
*/
static get QueryBuilder() {
return SoftDeleteQueryBuilder;
}
/**
* Timestamps columns.
*/
get timestamps() {
return ['createdAt', 'updatedAt'];
}
/**
* Virtual attributes.
*/
static get virtualAttributes() {
return [];
}
/**
* Model modifiers.
*/
static get modifiers() {
return {};
}
/**
* Relationship mapping.
*/
static get relationMappings() {
return {};
}
}

View File

@@ -0,0 +1,56 @@
import { mixin, Model, raw } from 'objection';
import TenantModel from 'models/TenantModel';
import ModelSearchable from './ModelSearchable';
export default class TaxRateTransaction extends mixin(TenantModel, [
ModelSearchable,
]) {
/**
* Table name
*/
static get tableName() {
return 'tax_rate_transactions';
}
/**
* Timestamps columns.
*/
get timestamps() {
return [];
}
/**
* Virtual attributes.
*/
static get virtualAttributes() {
return [];
}
/**
* Model modifiers.
*/
static get modifiers() {
return {};
}
/**
* Relationship mapping.
*/
static get relationMappings() {
const TaxRate = require('models/TaxRate');
return {
/**
* Belongs to the tax rate.
*/
taxRate: {
relation: Model.BelongsToOneRelation,
modelClass: TaxRate.default,
join: {
from: 'tax_rate_transactions.taxRateId',
to: 'tax_rates.id',
},
},
};
}
}

View File

@@ -2,6 +2,7 @@ import { Account } from 'models';
import TenantRepository from '@/repositories/TenantRepository'; import TenantRepository from '@/repositories/TenantRepository';
import { IAccount } from '@/interfaces'; import { IAccount } from '@/interfaces';
import { Knex } from 'knex'; import { Knex } from 'knex';
import { TaxPayableAccount } from '@/database/seeds/data/accounts';
export default class AccountRepository extends TenantRepository { export default class AccountRepository extends TenantRepository {
/** /**
@@ -116,7 +117,7 @@ export default class AccountRepository extends TenantRepository {
if (!result) { if (!result) {
result = await this.model.query(trx).insertAndFetch({ result = await this.model.query(trx).insertAndFetch({
name: this.i18n.__('account.accounts_receivable.currency', { name: this.i18n.__('account.accounts_receivable.currency', {
currency: currencyCode currency: currencyCode,
}), }),
accountType: 'accounts-receivable', accountType: 'accounts-receivable',
currencyCode, currencyCode,
@@ -127,6 +128,29 @@ export default class AccountRepository extends TenantRepository {
return result; return result;
}; };
/**
* Find or create tax payable account.
* @param {Record<string, string>}extraAttrs
* @param {Knex.Transaction} trx
* @returns
*/
async findOrCreateTaxPayable(
extraAttrs: Record<string, string> = {},
trx?: Knex.Transaction
) {
let result = await this.model
.query(trx)
.findOne({ slug: TaxPayableAccount.slug, ...extraAttrs });
if (!result) {
result = await this.model.query(trx).insertAndFetch({
...TaxPayableAccount,
...extraAttrs,
});
}
return result;
}
findOrCreateAccountsPayable = async ( findOrCreateAccountsPayable = async (
currencyCode: string = '', currencyCode: string = '',
extraAttrs = {}, extraAttrs = {},

View File

@@ -1,10 +1,6 @@
import moment from 'moment'; import { castArray } from 'lodash';
import { castArray, sumBy, toArray } from 'lodash';
import { IBill, ISystemUser, IAccount } from '@/interfaces';
import JournalPoster from './JournalPoster'; import JournalPoster from './JournalPoster';
import JournalEntry from './JournalEntry';
import { IExpense, IExpenseCategory } from '@/interfaces';
import { increment } from 'utils';
export default class JournalCommands { export default class JournalCommands {
journal: JournalPoster; journal: JournalPoster;
models: any; models: any;
@@ -16,7 +12,6 @@ export default class JournalCommands {
*/ */
constructor(journal: JournalPoster) { constructor(journal: JournalPoster) {
this.journal = journal; this.journal = journal;
this.repositories = this.journal.repositories; this.repositories = this.journal.repositories;
this.models = this.journal.models; this.models = this.journal.models;
} }

View File

@@ -1,5 +1,5 @@
import moment from 'moment'; import moment from 'moment';
import { defaultTo, uniqBy } from 'lodash'; import { defaultTo, sumBy, uniqBy } from 'lodash';
import { IAccountTransaction, ILedger, ILedgerEntry } from '@/interfaces'; import { IAccountTransaction, ILedger, ILedgerEntry } from '@/interfaces';
export default class Ledger implements ILedger { export default class Ledger implements ILedger {
@@ -49,6 +49,15 @@ export default class Ledger implements ILedger {
return this.filter((entry) => entry.accountId === accountId); return this.filter((entry) => entry.accountId === accountId);
} }
/**
* Filters entries by the given accounts ids then returns a new ledger.
* @param {number[]} accountIds
* @returns {ILedger}
*/
public whereAccountsIds(accountIds: number[]): ILedger {
return this.filter((entry) => accountIds.indexOf(entry.accountId) !== -1);
}
/** /**
* Filters entries that before or same the given date and returns a new ledger. * Filters entries that before or same the given date and returns a new ledger.
* @param {Date|string} fromDate * @param {Date|string} fromDate
@@ -130,6 +139,22 @@ export default class Ledger implements ILedger {
return closingBalance; return closingBalance;
} }
/**
* Retrieves the closing credit of the entries.
* @returns {number}
*/
public getClosingCredit(): number {
return sumBy(this.entries, 'credit');
}
/**
* Retrieves the closing debit of the entries.
* @returns {number}
*/
public getClosingDebit(): number {
return sumBy(this.entries, 'debit');
}
/** /**
* Retrieve the closing balance of the entries. * Retrieve the closing balance of the entries.
* @returns {number} * @returns {number}
@@ -234,6 +259,9 @@ export default class Ledger implements ILedger {
entryId: entry.id, entryId: entry.id,
branchId: entry.branchId, branchId: entry.branchId,
projectId: entry.projectId, projectId: entry.projectId,
taxRateId: entry.taxRateId,
taxRate: entry.taxRate,
}; };
} }

View File

@@ -32,5 +32,8 @@ export const transformLedgerEntryToTransaction = (
projectId: entry.projectId, projectId: entry.projectId,
costable: entry.costable, costable: entry.costable,
taxRateId: entry.taxRateId,
taxRate: entry.taxRate,
}; };
}; };

View File

@@ -1,17 +1,12 @@
import { Service, Inject } from 'typedi'; import { Service } from 'typedi';
import { includes, difference, camelCase, upperFirst } from 'lodash'; import { includes, camelCase, upperFirst } from 'lodash';
import { ACCOUNT_TYPE } from '@/data/AccountTypes'; import { IAccount } from '@/interfaces';
import { IAccount, ICashflowTransactionLine } from '@/interfaces';
import { getCashflowTransactionType } from './utils'; import { getCashflowTransactionType } from './utils';
import { ServiceError } from '@/exceptions'; import { ServiceError } from '@/exceptions';
import { CASHFLOW_TRANSACTION_TYPE, ERRORS } from './constants'; import { CASHFLOW_TRANSACTION_TYPE, ERRORS } from './constants';
import HasTenancyService from '@/services/Tenancy/TenancyService';
@Service() @Service()
export class CommandCashflowValidator { export class CommandCashflowValidator {
@Inject()
private tenancy: HasTenancyService;
/** /**
* Validates the lines accounts type should be cash or bank account. * Validates the lines accounts type should be cash or bank account.
* @param {IAccount} accounts - * @param {IAccount} accounts -

View File

@@ -1,14 +0,0 @@
import { difference, includes } from 'lodash';
import { ICashflowTransactionLine } from '@/interfaces';
import { ServiceError } from '@/exceptions';
import { Inject, Service } from 'typedi';
import { CASHFLOW_TRANSACTION_TYPE, ERRORS } from './constants';
import { IAccount } from '@/interfaces';
import HasTenancyService from '@/services/Tenancy/TenancyService';
@Service()
export default class CommandCashflowTransaction {
@Inject()
private tenancy: HasTenancyService;
}

View File

@@ -1,18 +1,10 @@
import * as R from 'ramda'; import * as R from 'ramda';
import { defaultTo, isEmpty, sumBy } from 'lodash';
import FinancialSheet from '../FinancialSheet'; import FinancialSheet from '../FinancialSheet';
import { import {
IBalanceSheetAggregateNode,
IBalanceSheetAccountNode,
BALANCE_SHEET_SCHEMA_NODE_TYPE,
IBalanceSheetQuery, IBalanceSheetQuery,
INumberFormatQuery, INumberFormatQuery,
IAccount,
IBalanceSheetSchemaNode, IBalanceSheetSchemaNode,
IBalanceSheetSchemaAggregateNode,
IBalanceSheetDataNode, IBalanceSheetDataNode,
IBalanceSheetSchemaAccountNode,
IBalanceSheetCommonNode,
} from '../../../interfaces'; } from '../../../interfaces';
import { BalanceSheetSchema } from './BalanceSheetSchema'; import { BalanceSheetSchema } from './BalanceSheetSchema';
import { BalanceSheetPercentage } from './BalanceSheetPercentage'; import { BalanceSheetPercentage } from './BalanceSheetPercentage';
@@ -24,8 +16,14 @@ import { FinancialSheetStructure } from '../FinancialSheetStructure';
import BalanceSheetRepository from './BalanceSheetRepository'; import BalanceSheetRepository from './BalanceSheetRepository';
import { BalanceSheetQuery } from './BalanceSheetQuery'; import { BalanceSheetQuery } from './BalanceSheetQuery';
import { BalanceSheetFiltering } from './BalanceSheetFiltering'; import { BalanceSheetFiltering } from './BalanceSheetFiltering';
import { BalanceSheetNetIncome } from './BalanceSheetNetIncome';
import { BalanceSheetAggregators } from './BalanceSheetAggregators';
import { BalanceSheetAccounts } from './BalanceSheetAccounts';
export default class BalanceSheet extends R.compose( export default class BalanceSheet extends R.compose(
BalanceSheetAggregators,
BalanceSheetAccounts,
BalanceSheetNetIncome,
BalanceSheetFiltering, BalanceSheetFiltering,
BalanceSheetDatePeriods, BalanceSheetDatePeriods,
BalanceSheetComparsionPreviousPeriod, BalanceSheetComparsionPreviousPeriod,
@@ -53,6 +51,9 @@ export default class BalanceSheet extends R.compose(
*/ */
readonly baseCurrency: string; readonly baseCurrency: string;
/**
* Localization.
*/
readonly i18n: any; readonly i18n: any;
/** /**
@@ -77,216 +78,18 @@ export default class BalanceSheet extends R.compose(
} }
/** /**
* Retrieve the accounts node of accounts types. * Parses report schema nodes.
* @param {string} accountsTypes * @param {IBalanceSheetSchemaNode[]} schema
* @returns {IAccount[]} * @returns {IBalanceSheetDataNode[]}
*/ */
private getAccountsByAccountTypes = (accountsTypes: string[]): IAccount[] => { public parseSchemaNodes = (
const mapAccountsByTypes = R.map((accountType) => schema: IBalanceSheetSchemaNode[]
defaultTo(this.repository.accountsByType.get(accountType), [])
);
return R.compose(R.flatten, mapAccountsByTypes)(accountsTypes);
};
/**
* Mappes the aggregate schema node type.
* @param {IBalanceSheetSchemaAggregateNode} node - Schema node.
* @return {IBalanceSheetAggregateNode}
*/
private reportSchemaAggregateNodeMapper = (
node: IBalanceSheetSchemaAggregateNode
): IBalanceSheetAggregateNode => {
const total = this.getTotalOfNodes(node.children);
return {
name: this.i18n.__(node.name),
id: node.id,
nodeType: BALANCE_SHEET_SCHEMA_NODE_TYPE.AGGREGATE,
total: this.getTotalAmountMeta(total),
children: node.children,
};
};
/**
* Compose shema aggregate node of balance sheet schema.
* @param {IBalanceSheetSchemaAggregateNode} node
* @returns {IBalanceSheetSchemaAggregateNode}
*/
private schemaAggregateNodeCompose = (
node: IBalanceSheetSchemaAggregateNode
) => {
return R.compose(
this.aggregateNodeTotalMapper,
this.reportSchemaAggregateNodeMapper
)(node);
};
/**
* Mappes the account model to report account node.
* @param {IAccount} account
* @returns {IBalanceSheetAccountNode}
*/
private reportSchemaAccountNodeMapper = (
account: IAccount
): IBalanceSheetAccountNode => {
const total = this.repository.totalAccountsLedger
.whereAccountId(account.id)
.getClosingBalance();
return {
id: account.id,
index: account.index,
name: account.name,
code: account.code,
total: this.getAmountMeta(total),
nodeType: BALANCE_SHEET_SCHEMA_NODE_TYPE.ACCOUNT,
};
};
/**
*
* @param {IAccount} account
* @returns {IBalanceSheetAccountNode}
*/
private reportSchemaAccountNodeComposer = (
account: IAccount
): IBalanceSheetAccountNode => {
return R.compose(
R.when(
this.query.isPreviousYearActive,
this.previousYearAccountNodeComposer
),
R.when(
this.query.isPreviousPeriodActive,
this.previousPeriodAccountNodeComposer
),
R.when(
this.query.isDatePeriodsColumnsType,
this.assocAccountNodeDatePeriods
),
this.reportSchemaAccountNodeMapper
)(account);
};
/**
* Retrieve the total of the given nodes.
* @param {IBalanceSheetCommonNode[]} nodes
* @returns {number}
*/
private getTotalOfNodes = (nodes: IBalanceSheetCommonNode[]) => {
return sumBy(nodes, 'total.amount');
};
/**
* Retrieve the report accounts node by the given accounts types.
* @param {string[]} accountsTypes
* @returns {}
*/
private getAccountsNodesByAccountTypes = (accountsTypes: string[]) => {
const accounts = this.getAccountsByAccountTypes(accountsTypes);
return R.compose(R.map(this.reportSchemaAccountNodeComposer))(accounts);
};
/**
* Mappes the accounts schema node type.
* @param {IBalanceSheetSchemaNode} node - Schema node.
* @returns {IBalanceSheetAccountNode}
*/
private reportSchemaAccountsNodeMapper = (
node: IBalanceSheetSchemaAccountNode
): IBalanceSheetAccountNode => {
const accounts = this.getAccountsNodesByAccountTypes(node.accountsTypes);
const total = this.getTotalOfNodes(accounts);
return {
id: node.id,
name: this.i18n.__(node.name),
type: node.type,
nodeType: BALANCE_SHEET_SCHEMA_NODE_TYPE.ACCOUNTS,
children: accounts,
total: this.getTotalAmountMeta(total),
};
};
/**
* Compose account schema node to report node.
* @param {IBalanceSheetSchemaAccountNode} node
* @returns {IBalanceSheetAccountNode}
*/
private reportSchemaAccountsNodeComposer = (
node: IBalanceSheetSchemaAccountNode
): IBalanceSheetAccountNode => {
return R.compose(
R.when(
this.query.isPreviousYearActive,
this.previousYearAggregateNodeComposer
),
R.when(
this.query.isPreviousPeriodActive,
this.previousPeriodAggregateNodeComposer
),
R.when(
this.query.isDatePeriodsColumnsType,
this.assocAccountsNodeDatePeriods
),
this.reportSchemaAccountsNodeMapper
)(node);
};
/**
* Mappes the given report schema node.
* @param {IBalanceSheetSchemaNode} node - Schema node.
* @return {IBalanceSheetDataNode}
*/
private reportSchemaNodeMapper = (
schemaNode: IBalanceSheetSchemaNode
): IBalanceSheetDataNode => {
return R.compose(
R.when(
this.isSchemaNodeType(BALANCE_SHEET_SCHEMA_NODE_TYPE.AGGREGATE),
this.schemaAggregateNodeCompose
),
R.when(
this.isSchemaNodeType(BALANCE_SHEET_SCHEMA_NODE_TYPE.ACCOUNTS),
this.reportSchemaAccountsNodeComposer
)
)(schemaNode);
};
/**
* Mappes the report schema nodes.
* @param {IBalanceSheetSchemaNode[]} nodes -
* @return {IBalanceSheetStructureSection[]}
*/
private reportSchemaAccountNodesMapper = (
schemaNodes: IBalanceSheetSchemaNode[]
): IBalanceSheetDataNode[] => { ): IBalanceSheetDataNode[] => {
return this.mapNodesDeepReverse(schemaNodes, this.reportSchemaNodeMapper);
};
/**
* Sets total amount that calculated from node children.
* @param {IBalanceSheetSection} node
* @returns {IBalanceSheetDataNode}
*/
private aggregateNodeTotalMapper = (
node: IBalanceSheetDataNode
): IBalanceSheetDataNode => {
return R.compose( return R.compose(
R.when( this.aggregatesSchemaParser,
this.query.isPreviousYearActive, this.netIncomeSchemaParser,
this.previousYearAggregateNodeComposer this.accountsSchemaParser
), )(schema) as IBalanceSheetDataNode[];
R.when(
this.query.isPreviousPeriodActive,
this.previousPeriodAggregateNodeComposer
),
R.when(
this.query.isDatePeriodsColumnsType,
this.assocAggregateNodeDatePeriods
)
)(node);
}; };
/** /**
@@ -299,7 +102,7 @@ export default class BalanceSheet extends R.compose(
return R.compose( return R.compose(
this.reportFilterPlugin, this.reportFilterPlugin,
this.reportPercentageCompose, this.reportPercentageCompose,
this.reportSchemaAccountNodesMapper this.parseSchemaNodes
)(balanceSheetSchema); )(balanceSheetSchema);
}; };
} }

View File

@@ -0,0 +1,182 @@
import * as R from 'ramda';
import { defaultTo, toArray } from 'lodash';
import { FinancialSheetStructure } from '../FinancialSheetStructure';
import {
BALANCE_SHEET_SCHEMA_NODE_TYPE,
IAccount,
IBalanceSheetAccountNode,
IBalanceSheetAccountsNode,
IBalanceSheetDataNode,
IBalanceSheetSchemaAccountNode,
IBalanceSheetSchemaNode,
INumberFormatQuery,
} from '@/interfaces';
import { BalanceSheetNetIncome } from './BalanceSheetNetIncome';
import { BalanceSheetFiltering } from './BalanceSheetFiltering';
import { BalanceSheetDatePeriods } from './BalanceSheetDatePeriods';
import { BalanceSheetComparsionPreviousPeriod } from './BalanceSheetComparsionPreviousPeriod';
import { BalanceSheetComparsionPreviousYear } from './BalanceSheetComparsionPreviousYear';
import { BalanceSheetPercentage } from './BalanceSheetPercentage';
import { BalanceSheetSchema } from './BalanceSheetSchema';
import { BalanceSheetBase } from './BalanceSheetBase';
import { BalanceSheetQuery } from './BalanceSheetQuery';
export const BalanceSheetAccounts = (Base: any) =>
class extends R.compose(
BalanceSheetNetIncome,
BalanceSheetFiltering,
BalanceSheetDatePeriods,
BalanceSheetComparsionPreviousPeriod,
BalanceSheetComparsionPreviousYear,
BalanceSheetPercentage,
BalanceSheetSchema,
BalanceSheetBase,
FinancialSheetStructure
)(Base) {
/**
* Balance sheet query.
* @param {BalanceSheetQuery}
*/
readonly query: BalanceSheetQuery;
/**
* Balance sheet number format query.
* @param {INumberFormatQuery}
*/
readonly numberFormat: INumberFormatQuery;
/**
* Base currency of the organization.
* @param {string}
*/
readonly baseCurrency: string;
/**
* Localization.
*/
readonly i18n: any;
/**
* Retrieve the accounts node of accounts types.
* @param {string} accountsTypes
* @returns {IAccount[]}
*/
private getAccountsByAccountTypes = (
accountsTypes: string[]
): IAccount[] => {
const mapAccountsByTypes = R.map((accountType) =>
defaultTo(this.repository.accountsByType.get(accountType), [])
);
return R.compose(R.flatten, mapAccountsByTypes)(accountsTypes);
};
/**
* Mappes the account model to report account node.
* @param {IAccount} account
* @returns {IBalanceSheetAccountNode}
*/
private reportSchemaAccountNodeMapper = (
account: IAccount
): IBalanceSheetAccountNode => {
const total = this.repository.totalAccountsLedger
.whereAccountId(account.id)
.getClosingBalance();
return {
id: account.id,
index: account.index,
name: account.name,
code: account.code,
total: this.getAmountMeta(total),
nodeType: BALANCE_SHEET_SCHEMA_NODE_TYPE.ACCOUNT,
};
};
/**
* Mappes the given account model to the balance sheet account node.
* @param {IAccount} account
* @returns {IBalanceSheetAccountNode}
*/
private reportSchemaAccountNodeComposer = (
account: IAccount
): IBalanceSheetAccountNode => {
return R.compose(
R.when(
this.query.isPreviousYearActive,
this.previousYearAccountNodeComposer
),
R.when(
this.query.isPreviousPeriodActive,
this.previousPeriodAccountNodeComposer
),
R.when(
this.query.isDatePeriodsColumnsType,
this.assocAccountNodeDatePeriods
),
this.reportSchemaAccountNodeMapper
)(account);
};
// -----------------------------
// - Accounts Node Praser
// -----------------------------
/**
* Retrieve the report accounts node by the given accounts types.
* @param {string[]} accountsTypes
* @returns {IBalanceSheetAccountNode[]}
*/
private getAccountsNodesByAccountTypes = (
accountsTypes: string[]
): IBalanceSheetAccountNode[] => {
const accounts = this.getAccountsByAccountTypes(accountsTypes);
return R.map(this.reportSchemaAccountNodeComposer, accounts);
};
/**
* Mappes the accounts schema node type.
* @param {IBalanceSheetSchemaNode} node - Schema node.
* @returns {IBalanceSheetAccountNode}
*/
private reportSchemaAccountsNodeMapper = (
node: IBalanceSheetSchemaAccountNode
): IBalanceSheetAccountsNode => {
const accounts = this.getAccountsNodesByAccountTypes(node.accountsTypes);
const children = toArray(node?.children);
return {
id: node.id,
name: this.i18n.__(node.name),
nodeType: BALANCE_SHEET_SCHEMA_NODE_TYPE.ACCOUNTS,
type: BALANCE_SHEET_SCHEMA_NODE_TYPE.ACCOUNTS,
children: [...accounts, ...children],
total: this.getTotalAmountMeta(0),
};
};
/**
* Mappes the given report schema node.
* @param {IBalanceSheetSchemaNode | IBalanceSheetDataNode} node - Schema node.
* @return {IBalanceSheetSchemaNode | IBalanceSheetDataNode}
*/
private reportAccountSchemaParser = (
node: IBalanceSheetSchemaNode | IBalanceSheetDataNode
): IBalanceSheetSchemaNode | IBalanceSheetDataNode => {
return R.compose(
R.when(
this.isSchemaNodeType(BALANCE_SHEET_SCHEMA_NODE_TYPE.ACCOUNTS),
this.reportSchemaAccountsNodeMapper
)
)(node);
};
/**
* Parses the report accounts schema nodes.
* @param {IBalanceSheetSchemaNode[]} nodes -
* @return {IBalanceSheetStructureSection[]}
*/
public accountsSchemaParser = (
nodes: (IBalanceSheetSchemaNode | IBalanceSheetDataNode)[]
): (IBalanceSheetDataNode | IBalanceSheetSchemaNode)[] => {
return this.mapNodesDeepReverse(nodes, this.reportAccountSchemaParser);
};
};

View File

@@ -0,0 +1,142 @@
import * as R from 'ramda';
import { FinancialPreviousPeriod } from '../FinancialPreviousPeriod';
import { FinancialHorizTotals } from '../FinancialHorizTotals';
import { FinancialSheetStructure } from '../FinancialSheetStructure';
import {
BALANCE_SHEET_SCHEMA_NODE_TYPE,
IBalanceSheetAggregateNode,
IBalanceSheetDataNode,
IBalanceSheetSchemaAggregateNode,
IBalanceSheetSchemaNode,
INumberFormatQuery,
} from '@/interfaces';
import { BalanceSheetDatePeriods } from './BalanceSheetDatePeriods';
import { BalanceSheetComparsionPreviousPeriod } from './BalanceSheetComparsionPreviousPeriod';
import { BalanceSheetComparsionPreviousYear } from './BalanceSheetComparsionPreviousYear';
import { BalanceSheetPercentage } from './BalanceSheetPercentage';
import { BalanceSheetSchema } from './BalanceSheetSchema';
import { BalanceSheetBase } from './BalanceSheetBase';
import { BalanceSheetQuery } from './BalanceSheetQuery';
export const BalanceSheetAggregators = (Base: any) =>
class extends R.compose(
BalanceSheetDatePeriods,
BalanceSheetComparsionPreviousPeriod,
BalanceSheetComparsionPreviousYear,
BalanceSheetPercentage,
BalanceSheetSchema,
BalanceSheetBase,
FinancialSheetStructure
)(Base) {
/**
* Balance sheet query.
* @param {BalanceSheetQuery}
*/
readonly query: BalanceSheetQuery;
/**
* Balance sheet number format query.
* @param {INumberFormatQuery}
*/
readonly numberFormat: INumberFormatQuery;
/**
* Base currency of the organization.
* @param {string}
*/
readonly baseCurrency: string;
/**
* Localization.
*/
readonly i18n: any;
/**
* Sets total amount that calculated from node children.
* @param {IBalanceSheetSection} node
* @returns {IBalanceSheetDataNode}
*/
private aggregateNodeTotalMapper = (
node: IBalanceSheetDataNode
): IBalanceSheetDataNode => {
return R.compose(
R.when(
this.query.isPreviousYearActive,
this.previousYearAggregateNodeComposer
),
R.when(
this.query.isPreviousPeriodActive,
this.previousPeriodAggregateNodeComposer
),
R.when(
this.query.isDatePeriodsColumnsType,
this.assocAggregateNodeDatePeriods
)
)(node);
};
/**
* Mappes the aggregate schema node type.
* @param {IBalanceSheetSchemaAggregateNode} node - Schema node.
* @return {IBalanceSheetAggregateNode}
*/
private reportSchemaAggregateNodeMapper = (
node: IBalanceSheetSchemaAggregateNode
): IBalanceSheetAggregateNode => {
const total = this.getTotalOfNodes(node.children);
return {
name: this.i18n.__(node.name),
id: node.id,
nodeType: BALANCE_SHEET_SCHEMA_NODE_TYPE.AGGREGATE,
type: BALANCE_SHEET_SCHEMA_NODE_TYPE.AGGREGATE,
total: this.getTotalAmountMeta(total),
children: node.children,
};
};
/**
* Compose shema aggregate node of balance sheet schema.
* @param {IBalanceSheetSchemaAggregateNode} node
* @returns {IBalanceSheetSchemaAggregateNode}
*/
private schemaAggregateNodeCompose = (
node: IBalanceSheetSchemaAggregateNode
) => {
return R.compose(
this.aggregateNodeTotalMapper,
this.reportSchemaAggregateNodeMapper
)(node);
};
/**
* Mappes the given report schema node.
* @param {IBalanceSheetSchemaNode} node - Schema node.
* @return {IBalanceSheetDataNode}
*/
private reportAggregateSchemaParser = (
node: IBalanceSheetSchemaNode
): IBalanceSheetDataNode => {
return R.compose(
R.when(
this.isSchemaNodeType(BALANCE_SHEET_SCHEMA_NODE_TYPE.AGGREGATE),
this.schemaAggregateNodeCompose
),
R.when(
this.isSchemaNodeType(BALANCE_SHEET_SCHEMA_NODE_TYPE.ACCOUNTS),
this.schemaAggregateNodeCompose
)
)(node);
};
/**
* Mappes the report schema nodes.
* @param {IBalanceSheetSchemaNode[]} nodes -
* @return {IBalanceSheetStructureSection[]}
*/
public aggregatesSchemaParser = (
nodes: (IBalanceSheetSchemaNode | IBalanceSheetDataNode)[]
): (IBalanceSheetDataNode | IBalanceSheetSchemaNode)[] => {
return this.mapNodesDeepReverse(nodes, this.reportAggregateSchemaParser);
};
};

View File

@@ -6,6 +6,7 @@ import {
IBalanceSheetAggregateNode, IBalanceSheetAggregateNode,
IBalanceSheetTotal, IBalanceSheetTotal,
IBalanceSheetCommonNode, IBalanceSheetCommonNode,
IBalanceSheetComparsions,
} from '@/interfaces'; } from '@/interfaces';
import { FinancialPreviousPeriod } from '../FinancialPreviousPeriod'; import { FinancialPreviousPeriod } from '../FinancialPreviousPeriod';
import { FinancialHorizTotals } from '../FinancialHorizTotals'; import { FinancialHorizTotals } from '../FinancialHorizTotals';

View File

@@ -156,13 +156,14 @@ export const BalanceSheetComparsionPreviousYear = (Base: any) =>
* @param {IBalanceSheetCommonNode} node * @param {IBalanceSheetCommonNode} node
* @returns {IBalanceSheetCommonNode} * @returns {IBalanceSheetCommonNode}
*/ */
private assocPreviousYearAggregateHorizNode = ( public assocPreviousYearAggregateHorizNode = (
node: IBalanceSheetCommonNode node: IBalanceSheetCommonNode
) => { ): IBalanceSheetCommonNode => {
const horizontalTotals = R.addIndex(R.map)( const horizontalTotals = R.addIndex(R.map)(
this.previousYearAggregateHorizNodeComposer(node), this.previousYearAggregateHorizNodeComposer(node),
node.horizontalTotals node.horizontalTotals
); ) as IBalanceSheetTotal[];
return R.assoc('horizontalTotals', horizontalTotals, node); return R.assoc('horizontalTotals', horizontalTotals, node);
}; };
@@ -258,12 +259,11 @@ export const BalanceSheetComparsionPreviousYear = (Base: any) =>
// ------------------------------ // ------------------------------
// # Horizontal Nodes - Aggregate. // # Horizontal Nodes - Aggregate.
// ------------------------------ // ------------------------------
/** /**
* Detarmines whether the given node has horizontal totals. * Detarmines whether the given node has horizontal totals.
* @param {IBalanceSheetCommonNode} node * @param {IBalanceSheetCommonNode} node
* @returns {boolean} * @returns {boolean}
*/ */
private isNodeHasHorizontalTotals = (node: IBalanceSheetCommonNode) => public isNodeHasHorizontalTotals = (node: IBalanceSheetCommonNode) =>
!isEmpty(node.horizontalTotals); !isEmpty(node.horizontalTotals);
}; };

View File

@@ -107,9 +107,9 @@ export const BalanceSheetDatePeriods = (Base: FinancialSheet) =>
/** /**
* *
* @param {IBalanceSheetAccountNode} node * @param {IBalanceSheetAccountNode} node
* @param {Date} fromDate * @param {Date} fromDate
* @param {Date} toDate * @param {Date} toDate
* @returns {IBalanceSheetAccountNode} * @returns {IBalanceSheetAccountNode}
*/ */
private getAccountNodeDatePeriod = ( private getAccountNodeDatePeriod = (
@@ -201,7 +201,7 @@ export const BalanceSheetDatePeriods = (Base: FinancialSheet) =>
}; };
/** /**
* *
* @param node * @param node
* @returns * @returns
*/ */

View File

@@ -0,0 +1,226 @@
import * as R from 'ramda';
import {
BALANCE_SHEET_SCHEMA_NODE_TYPE,
IBalanceSheetDataNode,
IBalanceSheetNetIncomeNode,
IBalanceSheetSchemaNetIncomeNode,
IBalanceSheetSchemaNode,
IBalanceSheetTotalPeriod,
} from '@/interfaces';
import { BalanceSheetComparsionPreviousYear } from './BalanceSheetComparsionPreviousYear';
import { BalanceSheetComparsionPreviousPeriod } from './BalanceSheetComparsionPreviousPeriod';
import { FinancialPreviousPeriod } from '../FinancialPreviousPeriod';
import { FinancialHorizTotals } from '../FinancialHorizTotals';
import BalanceSheetRepository from './BalanceSheetRepository';
import { BalanceSheetQuery } from './BalanceSheetQuery';
import { BalanceSheetNetIncomePP } from './BalanceSheetNetIncomePP';
import { BalanceSheetNetIncomePY } from './BalanceSheetNetIncomePY';
export const BalanceSheetNetIncome = (Base: any) =>
class extends R.compose(
BalanceSheetNetIncomePP,
BalanceSheetNetIncomePY,
BalanceSheetComparsionPreviousYear,
BalanceSheetComparsionPreviousPeriod,
FinancialPreviousPeriod,
FinancialHorizTotals
)(Base) {
private repository: BalanceSheetRepository;
private query: BalanceSheetQuery;
/**
* Retrieves the closing balance of income accounts.
* @returns {number}
*/
private getIncomeTotal = () => {
const closeingBalance = this.repository.incomeLedger.getClosingBalance();
return closeingBalance;
};
/**
* Retrieves the closing balance of expenses accounts.
* @returns {number}
*/
private getExpensesTotal = () => {
const closingBalance = this.repository.expensesLedger.getClosingBalance();
return closingBalance;
};
/**
* Retrieves the total net income.
* @returns {number}
*/
protected getNetIncomeTotal = () => {
const income = this.getIncomeTotal();
const expenses = this.getExpensesTotal();
return income - expenses;
};
/**
* Mappes the aggregate schema node type.
* @param {IBalanceSheetSchemaNetIncomeNode} node - Schema node.
* @return {IBalanceSheetAggregateNode}
*/
protected schemaNetIncomeNodeMapper = (
node: IBalanceSheetSchemaNetIncomeNode
): IBalanceSheetNetIncomeNode => {
const total = this.getNetIncomeTotal();
return {
id: node.id,
name: this.i18n.__(node.name),
nodeType: BALANCE_SHEET_SCHEMA_NODE_TYPE.NET_INCOME,
total: this.getTotalAmountMeta(total),
};
};
/**
* Mapps the net income shcema node to report node.
* @param {IBalanceSheetSchemaNetIncomeNode} node
* @returns {IBalanceSheetNetIncomeNode}
*/
protected schemaNetIncomeNodeCompose = (
node: IBalanceSheetSchemaNetIncomeNode
): IBalanceSheetNetIncomeNode => {
return R.compose(
R.when(
this.query.isPreviousYearActive,
this.previousYearNetIncomeNodeCompose
),
R.when(
this.query.isPreviousPeriodActive,
this.previousPeriodNetIncomeNodeCompose
),
R.when(
this.query.isDatePeriodsColumnsType,
this.assocNetIncomeDatePeriodsNode
),
this.schemaNetIncomeNodeMapper
)(node);
};
// --------------------------------
// # Date Periods
// --------------------------------
/**
* Retreives total income of the given date period.
* @param {number} accountId -
* @param {Date} toDate -
* @returns {number}
*/
private getIncomeDatePeriodTotal = (toDate: Date): number => {
const periodTotalBetween = this.repository.incomePeriodsAccountsLedger
.whereToDate(toDate)
.getClosingBalance();
const periodOpening =
this.repository.incomePeriodsOpeningAccountsLedger.getClosingBalance();
return periodOpening + periodTotalBetween;
};
/**
* Retrieves total expense of the given date period.
* @param {number} accountId -
* @param {Date} toDate -
* @returns {number}
*/
private getExpensesDatePeriodTotal = (toDate: Date): number => {
const periodTotalBetween = this.repository.expensesPeriodsAccountsLedger
.whereToDate(toDate)
.getClosingBalance();
const periodOpening =
this.repository.expensesOpeningAccountLedger.getClosingBalance();
return periodOpening + periodTotalBetween;
};
/**
* Retrieve the given net income date period total.
* @param {number} accountId
* @param {Date} toDate
* @returns {number}
*/
private getNetIncomeDatePeriodTotal = (toDate: Date): number => {
const income = this.getIncomeDatePeriodTotal(toDate);
const expense = this.getExpensesDatePeriodTotal(toDate);
return income - expense;
};
/**
* Retrieves the net income date period node.
* @param {IBalanceSheetNetIncomeNode} node
* @param {Date} fromDate
* @param {Date} toDate
* @returns {IBalanceSheetNetIncomeNode}
*/
private getNetIncomeDatePeriodNode = (
node: IBalanceSheetNetIncomeNode,
fromDate: Date,
toDate: Date
): IBalanceSheetTotalPeriod => {
const periodTotal = this.getNetIncomeDatePeriodTotal(toDate);
return this.getDatePeriodTotalMeta(periodTotal, fromDate, toDate);
};
/**
* Retrieve total date periods of the given net income node.
* @param {IBalanceSheetNetIncomeNode} node
* @returns {IBalanceSheetNetIncomeNode}
*/
private getNetIncomeDatePeriodsNode = (
node: IBalanceSheetNetIncomeNode
): IBalanceSheetTotalPeriod[] => {
return this.getReportNodeDatePeriods(
node,
this.getNetIncomeDatePeriodNode
);
};
/**
* Assoc total date periods to net income node.
* @param {IBalanceSheetNetIncomeNode} node
* @returns {IBalanceSheetNetIncomeNode}
*/
public assocNetIncomeDatePeriodsNode = (
node: IBalanceSheetNetIncomeNode
): IBalanceSheetNetIncomeNode => {
const datePeriods = this.getNetIncomeDatePeriodsNode(node);
return R.assoc('horizontalTotals', datePeriods, node);
};
// -----------------------------
// - Net Income Nodes Praser
// -----------------------------
/**
* Mappes the given report schema node.
* @param {IBalanceSheetSchemaNode} node - Schema node.
* @return {IBalanceSheetDataNode}
*/
private reportNetIncomeNodeSchemaParser = (
schemaNode: IBalanceSheetSchemaNode
): IBalanceSheetDataNode => {
return R.compose(
R.when(
this.isSchemaNodeType(BALANCE_SHEET_SCHEMA_NODE_TYPE.NET_INCOME),
this.schemaNetIncomeNodeCompose
)
)(schemaNode);
};
/**
* Parses the report net income schema nodes.
* @param {(IBalanceSheetSchemaNode | IBalanceSheetDataNode)[]} nodes -
* @return {IBalanceSheetDataNode[]}
*/
public netIncomeSchemaParser = (
nodes: (IBalanceSheetSchemaNode | IBalanceSheetDataNode)[]
): IBalanceSheetDataNode[] => {
return this.mapNodesDeep(nodes, this.reportNetIncomeNodeSchemaParser);
};
};

View File

@@ -0,0 +1,120 @@
import * as R from 'ramda';
import {
IBalanceSheetNetIncomeNode,
IBalanceSheetTotalPeriod,
} from '@/interfaces';
import { BalanceSheetComparsionPreviousYear } from './BalanceSheetComparsionPreviousYear';
import { BalanceSheetComparsionPreviousPeriod } from './BalanceSheetComparsionPreviousPeriod';
import { FinancialPreviousPeriod } from '../FinancialPreviousPeriod';
import { FinancialHorizTotals } from '../FinancialHorizTotals';
import BalanceSheetRepository from './BalanceSheetRepository';
import { BalanceSheetQuery } from './BalanceSheetQuery';
import { BalanceSheetNetIncomePP } from './BalanceSheetNetIncomePP';
import { BalanceSheetNetIncomePY } from './BalanceSheetNetIncomePY';
export const BalanceSheetNetIncomeDatePeriods = (Base: any) =>
class extends R.compose(
BalanceSheetNetIncomePP,
BalanceSheetNetIncomePY,
BalanceSheetComparsionPreviousYear,
BalanceSheetComparsionPreviousPeriod,
FinancialPreviousPeriod,
FinancialHorizTotals
)(Base) {
private repository: BalanceSheetRepository;
private query: BalanceSheetQuery;
// --------------------------------
// # Date Periods
// --------------------------------
/**
* Retreives total income of the given date period.
* @param {number} accountId -
* @param {Date} toDate -
* @returns {number}
*/
private getIncomeDatePeriodTotal = (toDate: Date): number => {
const periodTotalBetween = this.repository.incomePeriodsAccountsLedger
.whereToDate(toDate)
.getClosingBalance();
const periodOpening =
this.repository.incomePeriodsOpeningAccountsLedger.getClosingBalance();
return periodOpening + periodTotalBetween;
};
/**
* Retrieves total expense of the given date period.
* @param {number} accountId -
* @param {Date} toDate -
* @returns {number}
*/
private getExpensesDatePeriodTotal = (toDate: Date): number => {
const periodTotalBetween = this.repository.expensesPeriodsAccountsLedger
.whereToDate(toDate)
.getClosingBalance();
const periodOpening =
this.repository.expensesOpeningAccountLedger.getClosingBalance();
return periodOpening + periodTotalBetween;
};
/**
* Retrieve the given net income date period total.
* @param {number} accountId
* @param {Date} toDate
* @returns {number}
*/
private getNetIncomeDatePeriodTotal = (toDate: Date): number => {
const income = this.getIncomeDatePeriodTotal(toDate);
const expense = this.getExpensesDatePeriodTotal(toDate);
return income - expense;
};
/**
* Retrieves the net income date period node.
* @param {IBalanceSheetNetIncomeNode} node
* @param {Date} fromDate
* @param {Date} toDate
* @returns {IBalanceSheetNetIncomeNode}
*/
private getNetIncomeDatePeriodNode = (
node: IBalanceSheetNetIncomeNode,
fromDate: Date,
toDate: Date
): IBalanceSheetTotalPeriod => {
const periodTotal = this.getNetIncomeDatePeriodTotal(toDate);
return this.getDatePeriodTotalMeta(periodTotal, fromDate, toDate);
};
/**
* Retrieve total date periods of the given net income node.
* @param {IBalanceSheetNetIncomeNode} node
* @returns {IBalanceSheetNetIncomeNode}
*/
private getNetIncomeDatePeriodsNode = (
node: IBalanceSheetNetIncomeNode
): IBalanceSheetTotalPeriod[] => {
return this.getReportNodeDatePeriods(
node,
this.getNetIncomeDatePeriodNode
);
};
/**
* Assoc total date periods to net income node.
* @param {IBalanceSheetNetIncomeNode} node
* @returns {IBalanceSheetNetIncomeNode}
*/
public assocNetIncomeDatePeriodsNode = (
node: IBalanceSheetNetIncomeNode
): IBalanceSheetNetIncomeNode => {
const datePeriods = this.getNetIncomeDatePeriodsNode(node);
return R.assoc('horizontalTotals', datePeriods, node);
};
};

View File

@@ -0,0 +1,127 @@
import * as R from 'ramda';
import { BalanceSheetComparsionPreviousPeriod } from './BalanceSheetComparsionPreviousPeriod';
import { FinancialPreviousPeriod } from '../FinancialPreviousPeriod';
import { FinancialHorizTotals } from '../FinancialHorizTotals';
import { IBalanceSheetNetIncomeNode, IBalanceSheetTotal } from '@/interfaces';
import { BalanceSheetQuery } from './BalanceSheetQuery';
import BalanceSheetRepository from './BalanceSheetRepository';
export const BalanceSheetNetIncomeDatePeriodsPP = (Base: any) =>
class extends R.compose(
BalanceSheetComparsionPreviousPeriod,
FinancialPreviousPeriod,
FinancialHorizTotals
)(Base) {
query: BalanceSheetQuery;
repository: BalanceSheetRepository;
/**
* Retrieves the PY total income of the given date period.
* @param {number} accountId -
* @param {Date} toDate -
* @return {number}
*/
private getPPIncomeDatePeriodTotal = R.curry((toDate: Date) => {
const PYPeriodsTotal = this.repository.incomePPPeriodsAccountsLedger
.whereToDate(toDate)
.getClosingBalance();
const PYPeriodsOpeningTotal =
this.repository.incomePPPeriodsOpeningAccountLedger.getClosingBalance();
return PYPeriodsOpeningTotal + PYPeriodsTotal;
});
/**
* Retrieves the PY total expense of the given date period.
* @param {number} accountId -
* @param {Date} toDate -
* @returns {number}
*/
private getPPExpenseDatePeriodTotal = R.curry((toDate: Date) => {
const PYPeriodsTotal = this.repository.expensePPPeriodsAccountsLedger
.whereToDate(toDate)
.getClosingBalance();
const PYPeriodsOpeningTotal =
this.repository.expensePPPeriodsOpeningAccountLedger.getClosingBalance();
return PYPeriodsOpeningTotal + PYPeriodsTotal;
});
/**
* Retrieve the given net income total of the given period.
* @param {number} accountId - Account id.
* @param {Date} toDate - To date.
* @returns {number}
*/
private getPPNetIncomeDatePeriodTotal = R.curry((toDate: Date) => {
const income = this.getPPIncomeDatePeriodTotal(toDate);
const expense = this.getPPExpenseDatePeriodTotal(toDate);
return income - expense;
});
/**
* Assoc preivous period to account horizontal total node.
* @param {IBalanceSheetAccountNode} node
* @returns {}
*/
private assocPreviousPeriodNetIncomeHorizTotal = R.curry(
(node: IBalanceSheetNetIncomeNode, totalNode) => {
const total = this.getPPNetIncomeDatePeriodTotal(
totalNode.previousPeriodToDate.date
);
return R.assoc('previousPeriod', this.getAmountMeta(total), totalNode);
}
);
/**
* Compose previous period to aggregate horizontal nodes.
* @param {IBalanceSheetTotal} node
* @returns {IBalanceSheetTotal}
*/
private previousPeriodNetIncomeHorizNodeComposer = R.curry(
(
node: IBalanceSheetNetIncomeNode,
horiontalTotalNode: IBalanceSheetTotal
): IBalanceSheetTotal => {
return R.compose(
R.when(
this.query.isPreviousPeriodPercentageActive,
this.assocPreviousPeriodTotalPercentageNode
),
R.when(
this.query.isPreviousPeriodChangeActive,
this.assocPreviousPeriodTotalChangeNode
),
R.when(
this.query.isPreviousPeriodActive,
this.assocPreviousPeriodNetIncomeHorizTotal(node)
),
R.when(
this.query.isPreviousPeriodActive,
this.assocPreviousPeriodHorizNodeFromToDates(
this.query.displayColumnsBy
)
)
)(horiontalTotalNode);
}
);
/**
* Associate the PP to net income horizontal nodes.
* @param {IBalanceSheetCommonNode} node
* @returns {IBalanceSheetCommonNode}
*/
public assocPreviousPeriodNetIncomeHorizNode = (
node: IBalanceSheetNetIncomeNode
): IBalanceSheetNetIncomeNode => {
const horizontalTotals = R.addIndex(R.map)(
this.previousPeriodNetIncomeHorizNodeComposer(node),
node.horizontalTotals
) as IBalanceSheetTotal[];
return R.assoc('horizontalTotals', horizontalTotals, node);
};
};

View File

@@ -0,0 +1,122 @@
import * as R from 'ramda';
import { BalanceSheetComparsionPreviousYear } from './BalanceSheetComparsionPreviousYear';
import { FinancialPreviousPeriod } from '../FinancialPreviousPeriod';
import { FinancialHorizTotals } from '../FinancialHorizTotals';
import { IBalanceSheetNetIncomeNode, IBalanceSheetTotal } from '@/interfaces';
import { BalanceSheetQuery } from './BalanceSheetQuery';
import BalanceSheetRepository from './BalanceSheetRepository';
export const BalanceSheetNetIncomeDatePeriodsPY = (Base: any) =>
class extends R.compose(
BalanceSheetComparsionPreviousYear,
FinancialPreviousPeriod,
FinancialHorizTotals
)(Base) {
query: BalanceSheetQuery;
repository: BalanceSheetRepository;
/**
* Retrieves the PY total income of the given date period.
* @param {Date} toDate -
* @return {number}
*/
private getPYIncomeDatePeriodTotal = R.curry((toDate: Date) => {
const PYPeriodsTotal = this.repository.incomePYPeriodsAccountsLedger
.whereToDate(toDate)
.getClosingBalance();
const PYPeriodsOpeningTotal =
this.repository.incomePYPeriodsOpeningAccountLedger.getClosingBalance();
return PYPeriodsOpeningTotal + PYPeriodsTotal;
});
/**
* Retrieves the PY total expense of the given date period.
* @param {Date} toDate -
* @returns {number}
*/
private getPYExpenseDatePeriodTotal = R.curry((toDate: Date) => {
const PYPeriodsTotal = this.repository.expensePYPeriodsAccountsLedger
.whereToDate(toDate)
.getClosingBalance();
const PYPeriodsOpeningTotal =
this.repository.expensePYPeriodsOpeningAccountLedger.getClosingBalance();
return PYPeriodsOpeningTotal + PYPeriodsTotal;
});
/**
* Retrieve the given net income total of the given period.
* @param {Date} toDate - To date.
* @returns {number}
*/
private getPYNetIncomeDatePeriodTotal = R.curry((toDate: Date) => {
const income = this.getPYIncomeDatePeriodTotal(toDate);
const expense = this.getPYExpenseDatePeriodTotal(toDate);
return income - expense;
});
/**
* Assoc preivous year to account horizontal total node.
* @param {IBalanceSheetAccountNode} node
* @returns {}
*/
private assocPreviousYearNetIncomeHorizTotal = R.curry(
(node: IBalanceSheetNetIncomeNode, totalNode) => {
const total = this.getPYNetIncomeDatePeriodTotal(
totalNode.previousYearToDate.date
);
return R.assoc('previousYear', this.getAmountMeta(total), totalNode);
}
);
/**
* Compose PY to net income horizontal nodes.
* @param {IBalanceSheetTotal} node
* @returns {IBalanceSheetTotal}
*/
private previousYearNetIncomeHorizNodeComposer = R.curry(
(
node: IBalanceSheetNetIncomeNode,
horiontalTotalNode: IBalanceSheetTotal
): IBalanceSheetTotal => {
return R.compose(
R.when(
this.query.isPreviousYearPercentageActive,
this.assocPreviousYearTotalPercentageNode
),
R.when(
this.query.isPreviousYearChangeActive,
this.assocPreviousYearTotalChangeNode
),
R.when(
this.query.isPreviousYearActive,
this.assocPreviousYearNetIncomeHorizTotal(node)
),
R.when(
this.query.isPreviousYearActive,
this.assocPreviousYearHorizNodeFromToDates
)
)(horiontalTotalNode);
}
);
/**
* Associate the PY to net income horizontal nodes.
* @param {IBalanceSheetCommonNode} node
* @returns {IBalanceSheetCommonNode}
*/
public assocPreviousYearNetIncomeHorizNode = (
node: IBalanceSheetNetIncomeNode
): IBalanceSheetNetIncomeNode => {
const horizontalTotals = R.addIndex(R.map)(
this.previousYearNetIncomeHorizNodeComposer(node),
node.horizontalTotals
) as IBalanceSheetTotal[];
return R.assoc('horizontalTotals', horizontalTotals, node);
};
};

View File

@@ -0,0 +1,75 @@
import * as R from 'ramda';
import {
IBalanceSheetDataNode,
IBalanceSheetNetIncomeNode,
} from '@/interfaces';
import { BalanceSheetComparsionPreviousPeriod } from './BalanceSheetComparsionPreviousPeriod';
import { FinancialPreviousPeriod } from '../FinancialPreviousPeriod';
import { FinancialHorizTotals } from '../FinancialHorizTotals';
import BalanceSheetRepository from './BalanceSheetRepository';
import { BalanceSheetQuery } from './BalanceSheetQuery';
import { BalanceSheetNetIncomeDatePeriodsPP } from './BalanceSheetNetIncomeDatePeriodsPP';
export const BalanceSheetNetIncomePP = (Base: any) =>
class extends R.compose(
BalanceSheetNetIncomeDatePeriodsPP,
BalanceSheetComparsionPreviousPeriod,
FinancialPreviousPeriod,
FinancialHorizTotals
)(Base) {
private repository: BalanceSheetRepository;
private query: BalanceSheetQuery;
// -------------------------------
// # Previous Period (PP)
// -------------------------------
/**
* Retrieves the PP net income.
* @returns {}
*/
protected getPreviousPeriodNetIncome = () => {
const income = this.repository.incomePPAccountsLedger.getClosingBalance();
const expense =
this.repository.expensePPAccountsLedger.getClosingBalance();
return income - expense;
};
/**
* Associates the previous period to account node.
* @param {IBalanceSheetDataNode} node
* @returns {IBalanceSheetDataNode}
*/
protected assocPreviousPeriodNetIncomeNode = (
node: IBalanceSheetDataNode
): IBalanceSheetDataNode => {
const total = this.getPreviousPeriodNetIncome();
return R.assoc('previousPeriod', this.getAmountMeta(total), node);
};
/**
* Previous period account node composer.
* @param {IBalanceSheetNetIncomeNode} node
* @returns {IBalanceSheetNetIncomeNode}
*/
protected previousPeriodNetIncomeNodeCompose = (
node: IBalanceSheetNetIncomeNode
): IBalanceSheetNetIncomeNode => {
return R.compose(
R.when(
this.isNodeHasHorizTotals,
this.assocPreviousPeriodNetIncomeHorizNode
),
R.when(
this.query.isPreviousPeriodPercentageActive,
this.assocPreviousPeriodPercentageNode
),
R.when(
this.query.isPreviousPeriodChangeActive,
this.assocPreviousPeriodChangeNode
),
this.assocPreviousPeriodNetIncomeNode
)(node);
};
};

View File

@@ -0,0 +1,79 @@
import * as R from 'ramda';
import {
IBalanceSheetDataNode,
IBalanceSheetNetIncomeNode,
} from '@/interfaces';
import { BalanceSheetComparsionPreviousYear } from './BalanceSheetComparsionPreviousYear';
import { BalanceSheetComparsionPreviousPeriod } from './BalanceSheetComparsionPreviousPeriod';
import { FinancialPreviousPeriod } from '../FinancialPreviousPeriod';
import { FinancialHorizTotals } from '../FinancialHorizTotals';
import BalanceSheetRepository from './BalanceSheetRepository';
import { BalanceSheetQuery } from './BalanceSheetQuery';
import { BalanceSheetNetIncomeDatePeriodsPY } from './BalanceSheetNetIncomeDatePeriodsPY';
export const BalanceSheetNetIncomePY = (Base: any) =>
class extends R.compose(
BalanceSheetNetIncomeDatePeriodsPY,
BalanceSheetComparsionPreviousYear,
BalanceSheetComparsionPreviousPeriod,
FinancialPreviousPeriod,
FinancialHorizTotals
)(Base) {
private repository: BalanceSheetRepository;
private query: BalanceSheetQuery;
// ------------------------------
// # Previous Year (PY)
// ------------------------------
/**
* Retrieves the previous year (PY) net income.
* @returns {number}
*/
protected getPreviousYearNetIncome = () => {
const income =
this.repository.incomePYTotalAccountsLedger.getClosingBalance();
const expense =
this.repository.expensePYTotalAccountsLedger.getClosingBalance();
return income - expense;
};
/**
* Assoc previous year on aggregate node.
* @param {IBalanceSheetAccountNode} node
* @returns {IBalanceSheetAccountNode}
*/
protected assocPreviousYearNetIncomeNode = (
node: IBalanceSheetNetIncomeNode
): IBalanceSheetNetIncomeNode => {
const total = this.getPreviousYearNetIncome();
return R.assoc('previousYear', this.getTotalAmountMeta(total), node);
};
/**
* Assoc previous year attributes to aggregate node.
* @param {IBalanceSheetAccountNode} node
* @returns {IBalanceSheetAccountNode}
*/
protected previousYearNetIncomeNodeCompose = (
node: IBalanceSheetNetIncomeNode
): IBalanceSheetNetIncomeNode => {
return R.compose(
R.when(
this.query.isPreviousYearPercentageActive,
this.assocPreviousYearTotalPercentageNode
),
R.when(
this.query.isPreviousYearChangeActive,
this.assocPreviousYearTotalChangeNode
),
// Associate the PY to date periods horizontal nodes.
R.when(
this.isNodeHasHorizontalTotals,
this.assocPreviousYearNetIncomeHorizNode
),
this.assocPreviousYearNetIncomeNode
)(node);
};
};

View File

@@ -12,26 +12,31 @@ export class BalanceSheetQuery extends R.compose(FinancialDateRanges)(
* @param {IBalanceSheetQuery} * @param {IBalanceSheetQuery}
*/ */
public readonly query: IBalanceSheetQuery; public readonly query: IBalanceSheetQuery;
/** /**
* Previous year to date. * Previous year to date.
* @param {Date} * @param {Date}
*/ */
public readonly PYToDate: Date; public readonly PYToDate: Date;
/** /**
* Previous year from date. * Previous year from date.
* @param {Date} * @param {Date}
*/ */
public readonly PYFromDate: Date; public readonly PYFromDate: Date;
/** /**
* Previous period to date. * Previous period to date.
* @param {Date} * @param {Date}
*/ */
public readonly PPToDate: Date; public readonly PPToDate: Date;
/** /**
* Previous period from date. * Previous period from date.
* @param {Date} * @param {Date}
*/ */
public readonly PPFromDate: Date; public readonly PPFromDate: Date;
/** /**
* Constructor method * Constructor method
* @param {IBalanceSheetQuery} query * @param {IBalanceSheetQuery} query

View File

@@ -3,6 +3,7 @@ import * as R from 'ramda';
import { Knex } from 'knex'; import { Knex } from 'knex';
import { isEmpty } from 'lodash'; import { isEmpty } from 'lodash';
import { import {
IAccount,
IAccountTransactionsGroupBy, IAccountTransactionsGroupBy,
IBalanceSheetQuery, IBalanceSheetQuery,
ILedger, ILedger,
@@ -11,9 +12,12 @@ import { transformToMapBy } from 'utils';
import Ledger from '@/services/Accounting/Ledger'; import Ledger from '@/services/Accounting/Ledger';
import { BalanceSheetQuery } from './BalanceSheetQuery'; import { BalanceSheetQuery } from './BalanceSheetQuery';
import { FinancialDatePeriods } from '../FinancialDatePeriods'; import { FinancialDatePeriods } from '../FinancialDatePeriods';
import { ACCOUNT_PARENT_TYPE, ACCOUNT_TYPE } from '@/data/AccountTypes';
import { BalanceSheetRepositoryNetIncome } from './BalanceSheetRepositoryNetIncome';
@Service() @Service()
export default class BalanceSheetRepository extends R.compose( export default class BalanceSheetRepository extends R.compose(
BalanceSheetRepositoryNetIncome,
FinancialDatePeriods FinancialDatePeriods
)(class {}) { )(class {}) {
/** /**
@@ -65,8 +69,22 @@ export default class BalanceSheetRepository extends R.compose(
*/ */
public readonly PPFromDate: Date; public readonly PPFromDate: Date;
/**
* Total closing accounts ledger.
* @param {Ledger}
*/
public totalAccountsLedger: Ledger; public totalAccountsLedger: Ledger;
/**
* Total income accounts ledger.
*/
public incomeLedger: Ledger;
/**
* Total expense accounts ledger.
*/
public expensesLedger: Ledger;
/** /**
* Transactions group type. * Transactions group type.
* @param {IAccountTransactionsGroupBy} * @param {IAccountTransactionsGroupBy}
@@ -171,6 +189,8 @@ export default class BalanceSheetRepository extends R.compose(
) { ) {
await this.initPeriodsPreviousPeriod(); await this.initPeriodsPreviousPeriod();
} }
//
await this.asyncInitializeNetIncome();
}; };
// ---------------------------- // ----------------------------
@@ -181,6 +201,7 @@ export default class BalanceSheetRepository extends R.compose(
this.accounts = accounts; this.accounts = accounts;
this.accountsByType = transformToMapBy(accounts, 'accountType'); this.accountsByType = transformToMapBy(accounts, 'accountType');
this.accountsByParentType = transformToMapBy(accounts, 'accountParentType');
}; };
// ---------------------------- // ----------------------------
@@ -309,14 +330,15 @@ export default class BalanceSheetRepository extends R.compose(
/** /**
* Closing accounts date periods. * Closing accounts date periods.
* @param openingDate * @param {Date} fromDate
* @param datePeriodsType * @param {Date} toDate
* @param {string} datePeriodsType
* @returns * @returns
*/ */
public accountsDatePeriods = async ( public accountsDatePeriods = async (
fromDate: Date, fromDate: Date,
toDate: Date, toDate: Date,
datePeriodsType datePeriodsType: string
) => { ) => {
const { AccountTransaction } = this.models; const { AccountTransaction } = this.models;
@@ -336,6 +358,7 @@ export default class BalanceSheetRepository extends R.compose(
/** /**
* Retrieve the opening balance transactions of the report. * Retrieve the opening balance transactions of the report.
* @param {Date|string} openingDate -
*/ */
public closingAccountsTotal = async (openingDate: Date | string) => { public closingAccountsTotal = async (openingDate: Date | string) => {
const { AccountTransaction } = this.models; const { AccountTransaction } = this.models;

View File

@@ -0,0 +1,222 @@
import * as R from 'ramda';
import { IAccount, ILedger } from '@/interfaces';
import { FinancialDatePeriods } from '../FinancialDatePeriods';
import { ACCOUNT_PARENT_TYPE } from '@/data/AccountTypes';
export const BalanceSheetRepositoryNetIncome = (Base) =>
class extends R.compose(FinancialDatePeriods)(Base) {
// -----------------------
// # Net Income
// -----------------------
public incomeAccounts: IAccount[];
public incomeAccountsIds: number[];
public expenseAccounts: IAccount[];
public expenseAccountsIds: number[];
public incomePeriodsAccountsLedger: ILedger;
public incomePeriodsOpeningAccountsLedger: ILedger;
public expensesPeriodsAccountsLedger: ILedger;
public expensesOpeningAccountLedger: ILedger;
public incomePPAccountsLedger: ILedger;
public expensePPAccountsLedger: ILedger;
public incomePPPeriodsAccountsLedger: ILedger;
public incomePPPeriodsOpeningAccountLedger: ILedger;
public expensePPPeriodsAccountsLedger: ILedger;
public expensePPPeriodsOpeningAccountLedger: ILedger;
public incomePYTotalAccountsLedger: ILedger;
public expensePYTotalAccountsLedger: ILedger;
public incomePYPeriodsAccountsLedger: ILedger;
public incomePYPeriodsOpeningAccountLedger: ILedger;
public expensePYPeriodsAccountsLedger: ILedger;
public expensePYPeriodsOpeningAccountLedger: ILedger;
/**
* Async initialize.
* @returns {Promise<void>}
*/
public asyncInitializeNetIncome = async () => {
await this.initAccounts();
await this.initAccountsTotalLedger();
// Net Income
this.initIncomeAccounts();
this.initExpenseAccounts();
this.initIncomeTotalLedger();
this.initExpensesTotalLedger();
// Date periods
if (this.query.isDatePeriodsColumnsType()) {
this.initNetIncomeDatePeriods();
}
// Previous Year (PY).
if (this.query.isPreviousYearActive()) {
this.initNetIncomePreviousYear();
}
// Previous Period (PP).
if (this.query.isPreviousPeriodActive()) {
this.initNetIncomePreviousPeriod();
}
// Previous Year (PY) / Date Periods.
if (
this.query.isPreviousYearActive() &&
this.query.isDatePeriodsColumnsType()
) {
this.initNetIncomePeriodsPreviewYear();
}
// Previous Period (PP) / Date Periods.
if (
this.query.isPreviousPeriodActive() &&
this.query.isDatePeriodsColumnsType()
) {
this.initNetIncomePeriodsPreviousPeriod();
}
};
// ----------------------------
// # Net Income
// ----------------------------
/**
* Initialize income accounts.
*/
private initIncomeAccounts = () => {
const incomeAccounts = this.accountsByParentType.get(
ACCOUNT_PARENT_TYPE.INCOME
);
const incomeAccountsIds = incomeAccounts.map((a) => a.id);
this.incomeAccounts = incomeAccounts;
this.incomeAccountsIds = incomeAccountsIds;
};
/**
* Initialize expense accounts.
*/
private initExpenseAccounts = () => {
const expensesAccounts = this.accountsByParentType.get(
ACCOUNT_PARENT_TYPE.EXPENSE
);
const expensesAccountsIds = expensesAccounts.map((a) => a.id);
this.expenseAccounts = expensesAccounts;
this.expenseAccountsIds = expensesAccountsIds;
};
/**
* Initialize the income total ledger.
*/
private initIncomeTotalLedger = (): void => {
// Inject to the repository.
this.incomeLedger = this.totalAccountsLedger.whereAccountsIds(
this.incomeAccountsIds
);
};
/**
* Initialize the expenses total ledger.
*/
private initExpensesTotalLedger = (): void => {
this.expensesLedger = this.totalAccountsLedger.whereAccountsIds(
this.expenseAccountsIds
);
};
// ----------------------------
// # Net Income - Date Periods
// ----------------------------
/**
* Initialize the net income date periods.
*/
public initNetIncomeDatePeriods = () => {
this.incomePeriodsAccountsLedger =
this.periodsAccountsLedger.whereAccountsIds(this.incomeAccountsIds);
this.incomePeriodsOpeningAccountsLedger =
this.periodsOpeningAccountLedger.whereAccountsIds(
this.incomeAccountsIds
);
this.expensesPeriodsAccountsLedger =
this.periodsAccountsLedger.whereAccountsIds(this.expenseAccountsIds);
this.expensesOpeningAccountLedger =
this.periodsOpeningAccountLedger.whereAccountsIds(
this.expenseAccountsIds
);
};
// ----------------------------
// # Net Income - Previous Period
// ----------------------------
/**
* Initialize the total net income PP.
*/
public initNetIncomePreviousPeriod = () => {
this.incomePPAccountsLedger = this.PPTotalAccountsLedger.whereAccountsIds(
this.incomeAccountsIds
);
this.expensePPAccountsLedger =
this.PPTotalAccountsLedger.whereAccountsIds(this.expenseAccountsIds);
};
/**
* Initialize the net income periods of previous period.
*/
public initNetIncomePeriodsPreviousPeriod = () => {
this.incomePPPeriodsAccountsLedger =
this.PPPeriodsAccountsLedger.whereAccountsIds(this.incomeAccountsIds);
this.incomePPPeriodsOpeningAccountLedger =
this.PPPeriodsOpeningAccountLedger.whereAccountsIds(
this.incomeAccountsIds
);
this.expensePPPeriodsAccountsLedger =
this.PPPeriodsAccountsLedger.whereAccountsIds(this.expenseAccountsIds);
this.expensePPPeriodsOpeningAccountLedger =
this.PPPeriodsOpeningAccountLedger.whereAccountsIds(
this.expenseAccountsIds
);
};
// ----------------------------
// # Net Income - Previous Year
// ----------------------------
/**
* Initialize the net income PY total.
*/
public initNetIncomePreviousYear = () => {
this.incomePYTotalAccountsLedger =
this.PYTotalAccountsLedger.whereAccountsIds(this.incomeAccountsIds);
this.expensePYTotalAccountsLedger =
this.PYTotalAccountsLedger.whereAccountsIds(this.expenseAccountsIds);
};
/**
* Initialize the net income PY periods.
*/
public initNetIncomePeriodsPreviewYear = () => {
this.incomePYPeriodsAccountsLedger =
this.PYPeriodsAccountsLedger.whereAccountsIds(this.incomeAccountsIds);
this.incomePYPeriodsOpeningAccountLedger =
this.PYPeriodsOpeningAccountLedger.whereAccountsIds(
this.incomeAccountsIds
);
this.expensePYPeriodsAccountsLedger =
this.PYPeriodsAccountsLedger.whereAccountsIds(this.expenseAccountsIds);
this.expensePYPeriodsOpeningAccountLedger =
this.PYPeriodsOpeningAccountLedger.whereAccountsIds(
this.expenseAccountsIds
);
};
};

View File

@@ -7,12 +7,11 @@ import {
import { ACCOUNT_TYPE } from '@/data/AccountTypes'; import { ACCOUNT_TYPE } from '@/data/AccountTypes';
import { FinancialSchema } from '../FinancialSchema'; import { FinancialSchema } from '../FinancialSchema';
export const BalanceSheetSchema = (Base) => export const BalanceSheetSchema = (Base) =>
class extends R.compose(FinancialSchema)(Base) { class extends R.compose(FinancialSchema)(Base) {
/** /**
* Retrieves the balance sheet schema. * Retrieves the balance sheet schema.
* @returns * @returns
*/ */
getSchema = () => { getSchema = () => {
return getBalanceSheetSchema(); return getBalanceSheetSchema();
@@ -115,6 +114,13 @@ export const getBalanceSheetSchema = () => [
id: BALANCE_SHEET_SCHEMA_NODE_ID.EQUITY, id: BALANCE_SHEET_SCHEMA_NODE_ID.EQUITY,
type: BALANCE_SHEET_SCHEMA_NODE_TYPE.ACCOUNTS, type: BALANCE_SHEET_SCHEMA_NODE_TYPE.ACCOUNTS,
accountsTypes: [ACCOUNT_TYPE.EQUITY], accountsTypes: [ACCOUNT_TYPE.EQUITY],
children: [
{
name: 'balance_sheet.net_income',
id: BALANCE_SHEET_SCHEMA_NODE_ID.NET_INCOME,
type: BALANCE_SHEET_SCHEMA_NODE_TYPE.NET_INCOME,
},
],
}, },
], ],
alwaysShow: true, alwaysShow: true,

View File

@@ -37,7 +37,7 @@ export default class BalanceSheetStatementService
displayColumnsBy: 'month', displayColumnsBy: 'month',
fromDate: moment().startOf('year').format('YYYY-MM-DD'), fromDate: moment().startOf('year').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'), toDate: moment().format('YYYY-MM-DD'),
numberFormat: { numberFormat: {
precision: 2, precision: 2,

View File

@@ -8,6 +8,10 @@ import {
BALANCE_SHEET_SCHEMA_NODE_TYPE, BALANCE_SHEET_SCHEMA_NODE_TYPE,
IBalanceSheetDataNode, IBalanceSheetDataNode,
IBalanceSheetSchemaNode, IBalanceSheetSchemaNode,
IBalanceSheetNetIncomeNode,
IBalanceSheetAccountNode,
IBalanceSheetAccountsNode,
IBalanceSheetAggregateNode,
} from '@/interfaces'; } from '@/interfaces';
import { tableRowMapper } from 'utils'; import { tableRowMapper } from 'utils';
import FinancialSheet from '../FinancialSheet'; import FinancialSheet from '../FinancialSheet';
@@ -108,11 +112,13 @@ export default class BalanceSheetTable extends R.compose(
}; };
/** /**
* * Retrieves the table row from the given report aggregate node.
* @param node * @param {IBalanceSheetAggregateNode} node
* @returns {ITableRow} * @returns {ITableRow}
*/ */
private aggregateNodeTableRowsMapper = (node): ITableRow => { private aggregateNodeTableRowsMapper = (
node: IBalanceSheetAggregateNode
): ITableRow => {
const columns = this.commonColumnsAccessors(); const columns = this.commonColumnsAccessors();
const meta = { const meta = {
rowTypes: [IROW_TYPE.AGGREGATE], rowTypes: [IROW_TYPE.AGGREGATE],
@@ -122,11 +128,13 @@ export default class BalanceSheetTable extends R.compose(
}; };
/** /**
* * Retrieves the table row from the given report accounts node.
* @param node * @param {IBalanceSheetAccountsNode} node
* @returns {ITableRow} * @returns {ITableRow}
*/ */
private accountsNodeTableRowsMapper = (node): ITableRow => { private accountsNodeTableRowsMapper = (
node: IBalanceSheetAccountsNode
): ITableRow => {
const columns = this.commonColumnsAccessors(); const columns = this.commonColumnsAccessors();
const meta = { const meta = {
rowTypes: [IROW_TYPE.ACCOUNTS], rowTypes: [IROW_TYPE.ACCOUNTS],
@@ -136,11 +144,13 @@ export default class BalanceSheetTable extends R.compose(
}; };
/** /**
* * Retrieves the table row from the given report account node.
* @param {} node * @param {IBalanceSheetAccountNode} node
* @returns {ITableRow} * @returns {ITableRow}
*/ */
private accountNodeTableRowsMapper = (node): ITableRow => { private accountNodeTableRowsMapper = (
node: IBalanceSheetAccountNode
): ITableRow => {
const columns = this.commonColumnsAccessors(); const columns = this.commonColumnsAccessors();
const meta = { const meta = {
@@ -150,6 +160,22 @@ export default class BalanceSheetTable extends R.compose(
return tableRowMapper(node, columns, meta); return tableRowMapper(node, columns, meta);
}; };
/**
* Retrieves the table row from the given report net income node.
* @param {IBalanceSheetNetIncomeNode} node
* @returns {ITableRow}
*/
private netIncomeNodeTableRowsMapper = (
node: IBalanceSheetNetIncomeNode
): ITableRow => {
const columns = this.commonColumnsAccessors();
const meta = {
rowTypes: [IROW_TYPE.NET_INCOME],
id: node.id,
};
return tableRowMapper(node, columns, meta);
};
/** /**
* Mappes the given report node to table rows. * Mappes the given report node to table rows.
* @param {IBalanceSheetDataNode} node - * @param {IBalanceSheetDataNode} node -
@@ -169,6 +195,10 @@ export default class BalanceSheetTable extends R.compose(
this.isNodeType(BALANCE_SHEET_SCHEMA_NODE_TYPE.ACCOUNT), this.isNodeType(BALANCE_SHEET_SCHEMA_NODE_TYPE.ACCOUNT),
this.accountNodeTableRowsMapper, this.accountNodeTableRowsMapper,
], ],
[
this.isNodeType(BALANCE_SHEET_SCHEMA_NODE_TYPE.NET_INCOME),
this.netIncomeNodeTableRowsMapper,
],
])(node); ])(node);
}; };

View File

@@ -9,5 +9,6 @@ export enum IROW_TYPE {
AGGREGATE = 'AGGREGATE', AGGREGATE = 'AGGREGATE',
ACCOUNTS = 'ACCOUNTS', ACCOUNTS = 'ACCOUNTS',
ACCOUNT = 'ACCOUNT', ACCOUNT = 'ACCOUNT',
NET_INCOME = 'NET_INCOME',
TOTAL = 'TOTAL', TOTAL = 'TOTAL',
} }

View File

@@ -40,7 +40,7 @@ export default class CashFlowStatementService
displayColumnsType: 'total', displayColumnsType: 'total',
displayColumnsBy: 'day', displayColumnsBy: 'day',
fromDate: moment().startOf('year').format('YYYY-MM-DD'), fromDate: moment().startOf('year').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'), toDate: moment().format('YYYY-MM-DD'),
numberFormat: { numberFormat: {
precision: 2, precision: 2,
divideOn1000: false, divideOn1000: false,

View File

@@ -31,8 +31,8 @@ export default class GeneralLedgerService {
*/ */
get defaultQuery() { get defaultQuery() {
return { return {
fromDate: moment().startOf('year').format('YYYY-MM-DD'), fromDate: moment().startOf('month').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'), toDate: moment().format('YYYY-MM-DD'),
basis: 'cash', basis: 'cash',
numberFormat: { numberFormat: {
noCents: false, noCents: false,

View File

@@ -16,13 +16,13 @@ import { Tenant } from '@/system/models';
@Service() @Service()
export default class InventoryDetailsService extends FinancialSheet { export default class InventoryDetailsService extends FinancialSheet {
@Inject() @Inject()
tenancy: TenancyService; private tenancy: TenancyService;
@Inject() @Inject()
reportRepo: InventoryDetailsRepository; private reportRepo: InventoryDetailsRepository;
@Inject() @Inject()
inventoryService: InventoryService; private inventoryService: InventoryService;
/** /**
* Defaults balance sheet filter query. * Defaults balance sheet filter query.
@@ -30,8 +30,8 @@ export default class InventoryDetailsService extends FinancialSheet {
*/ */
private get defaultQuery(): IInventoryDetailsQuery { private get defaultQuery(): IInventoryDetailsQuery {
return { return {
fromDate: moment().startOf('year').format('YYYY-MM-DD'), fromDate: moment().startOf('month').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'), toDate: moment().format('YYYY-MM-DD'),
itemsIds: [], itemsIds: [],
numberFormat: { numberFormat: {
precision: 2, precision: 2,

View File

@@ -27,7 +27,7 @@ export default class InventoryValuationSheetService {
*/ */
get defaultQuery(): IInventoryValuationReportQuery { get defaultQuery(): IInventoryValuationReportQuery {
return { return {
asDate: moment().endOf('year').format('YYYY-MM-DD'), asDate: moment().format('YYYY-MM-DD'),
itemsIds: [], itemsIds: [],
numberFormat: { numberFormat: {
precision: 2, precision: 2,

View File

@@ -25,8 +25,8 @@ export default class JournalSheetService {
*/ */
get defaultQuery() { get defaultQuery() {
return { return {
fromDate: moment().startOf('year').format('YYYY-MM-DD'), fromDate: moment().startOf('month').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'), toDate: moment().format('YYYY-MM-DD'),
fromRange: null, fromRange: null,
toRange: null, toRange: null,
accountsIds: [], accountsIds: [],

View File

@@ -8,7 +8,7 @@ import { IProfitLossSheetQuery } from '@/interfaces';
*/ */
export const getDefaultPLQuery = (): IProfitLossSheetQuery => ({ export const getDefaultPLQuery = (): IProfitLossSheetQuery => ({
fromDate: moment().startOf('year').format('YYYY-MM-DD'), fromDate: moment().startOf('year').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'), toDate: moment().format('YYYY-MM-DD'),
numberFormat: { numberFormat: {
divideOn1000: false, divideOn1000: false,

View File

@@ -12,10 +12,7 @@ import { Tenant } from '@/system/models';
@Service() @Service()
export default class InventoryValuationReportService { export default class InventoryValuationReportService {
@Inject() @Inject()
tenancy: TenancyService; private tenancy: TenancyService;
@Inject('logger')
logger: any;
/** /**
* Defaults balance sheet filter query. * Defaults balance sheet filter query.
@@ -23,8 +20,8 @@ export default class InventoryValuationReportService {
*/ */
get defaultQuery(): IInventoryValuationReportQuery { get defaultQuery(): IInventoryValuationReportQuery {
return { return {
fromDate: moment().startOf('year').format('YYYY-MM-DD'), fromDate: moment().startOf('month').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'), toDate: moment().format('YYYY-MM-DD'),
itemsIds: [], itemsIds: [],
numberFormat: { numberFormat: {
precision: 2, precision: 2,
@@ -73,9 +70,9 @@ export default class InventoryValuationReportService {
tenantId: number, tenantId: number,
query: IInventoryValuationReportQuery query: IInventoryValuationReportQuery
): Promise<{ ): Promise<{
data: IInventoryValuationStatement, data: IInventoryValuationStatement;
query: IInventoryValuationReportQuery, query: IInventoryValuationReportQuery;
meta: IInventoryValuationSheetMeta, meta: IInventoryValuationSheetMeta;
}> { }> {
const { Item, InventoryTransaction } = this.tenancy.models(tenantId); const { Item, InventoryTransaction } = this.tenancy.models(tenantId);
@@ -87,7 +84,7 @@ export default class InventoryValuationReportService {
...this.defaultQuery, ...this.defaultQuery,
...query, ...query,
}; };
const inventoryItems = await Item.query().onBuild(q => { const inventoryItems = await Item.query().onBuild((q) => {
q.where('type', 'inventory'); q.where('type', 'inventory');
if (filter.itemsIds.length > 0) { if (filter.itemsIds.length > 0) {
@@ -106,7 +103,7 @@ export default class InventoryValuationReportService {
builder.whereIn('itemId', inventoryItemsIds); builder.whereIn('itemId', inventoryItemsIds);
// Filter the date range of the sheet. // Filter the date range of the sheet.
builder.modify('filterDateRange', filter.fromDate, filter.toDate) builder.modify('filterDateRange', filter.fromDate, filter.toDate);
} }
); );

View File

@@ -23,8 +23,8 @@ export default class SalesByItemsReportService {
*/ */
get defaultQuery(): ISalesByItemsReportQuery { get defaultQuery(): ISalesByItemsReportQuery {
return { return {
fromDate: moment().startOf('year').format('YYYY-MM-DD'), fromDate: moment().startOf('month').format('YYYY-MM-DD'),
toDate: moment().endOf('year').format('YYYY-MM-DD'), toDate: moment().format('YYYY-MM-DD'),
itemsIds: [], itemsIds: [],
numberFormat: { numberFormat: {
precision: 2, precision: 2,

View File

@@ -0,0 +1,131 @@
import * as R from 'ramda';
import { isEmpty, sumBy } from 'lodash';
import { ITaxRate } from '@/interfaces';
import {
SalesTaxLiabilitySummaryPayableById,
SalesTaxLiabilitySummaryQuery,
SalesTaxLiabilitySummaryRate,
SalesTaxLiabilitySummaryReportData,
SalesTaxLiabilitySummarySalesById,
SalesTaxLiabilitySummaryTotal,
} from '@/interfaces/SalesTaxLiabilitySummary';
import FinancialSheet from '../FinancialSheet';
export class SalesTaxLiabilitySummary extends FinancialSheet {
private query: SalesTaxLiabilitySummaryQuery;
private taxRates: ITaxRate[];
private payableTaxesById: SalesTaxLiabilitySummaryPayableById;
private salesTaxesById: SalesTaxLiabilitySummarySalesById;
/**
* Sales tax liability summary constructor.
* @param {SalesTaxLiabilitySummaryQuery} query
* @param {ITaxRate[]} taxRates
* @param {SalesTaxLiabilitySummaryPayableById} payableTaxesById
* @param {SalesTaxLiabilitySummarySalesById} salesTaxesById
*/
constructor(
query: SalesTaxLiabilitySummaryQuery,
taxRates: ITaxRate[],
payableTaxesById: SalesTaxLiabilitySummaryPayableById,
salesTaxesById: SalesTaxLiabilitySummarySalesById
) {
super();
this.query = query;
this.taxRates = taxRates;
this.payableTaxesById = payableTaxesById;
this.salesTaxesById = salesTaxesById;
}
/**
* Retrieves the tax rate liability node.
* @param {ITaxRate} taxRate
* @returns {SalesTaxLiabilitySummaryRate}
*/
private taxRateLiability = (
taxRate: ITaxRate
): SalesTaxLiabilitySummaryRate => {
const payableTax = this.payableTaxesById[taxRate.id];
const salesTax = this.salesTaxesById[taxRate.id];
const payableTaxAmount = payableTax
? payableTax.credit - payableTax.debit
: 0;
const salesTaxAmount = salesTax ? salesTax.credit - salesTax.debit : 0;
// Calculates the tax percentage.
const taxPercentage = R.compose(
R.unless(R.equals(0), R.divide(R.__, salesTaxAmount))
)(payableTaxAmount);
// Calculates the payable tax amount.
const collectedTaxAmount = payableTax ? payableTax.debit : 0;
return {
id: taxRate.id,
taxName: `${taxRate.name} (${taxRate.rate}%)`,
taxableAmount: this.getAmountMeta(salesTaxAmount),
taxAmount: this.getAmountMeta(payableTaxAmount),
taxPercentage: this.getPercentageTotalAmountMeta(taxPercentage),
collectedTaxAmount: this.getAmountMeta(collectedTaxAmount),
};
};
/**
* Filters the non-transactions tax rates.
* @param {SalesTaxLiabilitySummaryRate[]} nodes
* @returns {SalesTaxLiabilitySummaryRate[]}
*/
private filterNonTransactionsTaxRates = (
nodes: SalesTaxLiabilitySummaryRate[]
): SalesTaxLiabilitySummaryRate[] => {
return nodes.filter((node) => {
const salesTrxs = this.salesTaxesById[node.id];
const payableTrxs = this.payableTaxesById[node.id];
return !isEmpty(salesTrxs) || !isEmpty(payableTrxs);
});
};
/**
* Retrieves the tax rates liability nodes.
* @returns {SalesTaxLiabilitySummaryRate[]}
*/
private taxRatesLiability = (): SalesTaxLiabilitySummaryRate[] => {
return R.compose(
this.filterNonTransactionsTaxRates,
R.map(this.taxRateLiability)
)(this.taxRates);
};
/**
* Retrieves the tax rates total node.
* @param {SalesTaxLiabilitySummaryRate[]} nodes
* @returns {SalesTaxLiabilitySummaryTotal}
*/
private taxRatesTotal = (
nodes: SalesTaxLiabilitySummaryRate[]
): SalesTaxLiabilitySummaryTotal => {
const taxableAmount = sumBy(nodes, 'taxableAmount.amount');
const taxAmount = sumBy(nodes, 'taxAmount.amount');
const collectedTaxAmount = sumBy(nodes, 'collectedTaxAmount.amount');
return {
taxableAmount: this.getTotalAmountMeta(taxableAmount),
taxAmount: this.getTotalAmountMeta(taxAmount),
collectedTaxAmount: this.getTotalAmountMeta(collectedTaxAmount),
};
};
/**
* Retrieves the report data.
* @returns {SalesTaxLiabilitySummaryReportData}
*/
public reportData = (): SalesTaxLiabilitySummaryReportData => {
const taxRates = this.taxRatesLiability();
const total = this.taxRatesTotal(taxRates);
return { taxRates, total };
};
}

View File

@@ -0,0 +1,79 @@
import { ACCOUNT_TYPE } from '@/data/AccountTypes';
import {
SalesTaxLiabilitySummaryPayableById,
SalesTaxLiabilitySummarySalesById,
} from '@/interfaces/SalesTaxLiabilitySummary';
import HasTenancyService from '@/services/Tenancy/TenancyService';
import { keyBy } from 'lodash';
import { Inject, Service } from 'typedi';
@Service()
export class SalesTaxLiabilitySummaryRepository {
@Inject()
private tenancy: HasTenancyService;
/**
* Retrieve tax rates.
* @param {number} tenantId
* @returns {Promise<TaxRate[]>}
*/
public taxRates = (tenantId: number) => {
const { TaxRate } = this.tenancy.models(tenantId);
return TaxRate.query().orderBy('name', 'desc');
};
/**
* Retrieve taxes payable sum grouped by tax rate id.
* @param {number} tenantId
* @returns {Promise<SalesTaxLiabilitySummaryPayableById>}
*/
public async taxesPayableSumGroupedByRateId(
tenantId: number
): Promise<SalesTaxLiabilitySummaryPayableById> {
const { AccountTransaction, Account } = this.tenancy.models(tenantId);
// Retrieves tax payable accounts.
const taxPayableAccounts = await Account.query().whereIn('accountType', [
ACCOUNT_TYPE.TAX_PAYABLE,
]);
const payableAccountsIds = taxPayableAccounts.map((account) => account.id);
const groupedTaxesById = await AccountTransaction.query()
.whereIn('account_id', payableAccountsIds)
.whereNot('tax_rate_id', null)
.groupBy('tax_rate_id')
.select(['tax_rate_id'])
.sum('credit as credit')
.sum('debit as debit');
return keyBy(groupedTaxesById, 'taxRateId');
}
/**
* Retrieve taxes sales sum grouped by tax rate id.
* @param {number} tenantId
* @returns {Promise<SalesTaxLiabilitySummarySalesById>}
*/
public taxesSalesSumGroupedByRateId = async (
tenantId: number
): Promise<SalesTaxLiabilitySummarySalesById> => {
const { AccountTransaction, Account } = this.tenancy.models(tenantId);
const incomeAccounts = await Account.query().whereIn('accountType', [
ACCOUNT_TYPE.INCOME,
ACCOUNT_TYPE.OTHER_INCOME,
]);
const incomeAccountsIds = incomeAccounts.map((account) => account.id);
const groupedTaxesById = await AccountTransaction.query()
.whereIn('account_id', incomeAccountsIds)
.whereNot('tax_rate_id', null)
.groupBy('tax_rate_id')
.select(['tax_rate_id'])
.sum('credit as credit')
.sum('debit as debit');
return keyBy(groupedTaxesById, 'taxRateId');
};
}

View File

@@ -0,0 +1,98 @@
import { Inject, Service } from 'typedi';
import { SalesTaxLiabilitySummaryRepository } from './SalesTaxLiabilitySummaryRepository';
import {
SalesTaxLiabilitySummaryMeta,
SalesTaxLiabilitySummaryQuery,
} from '@/interfaces/SalesTaxLiabilitySummary';
import { SalesTaxLiabilitySummary } from './SalesTaxLiabilitySummary';
import { SalesTaxLiabilitySummaryTable } from './SalesTaxLiabilitySummaryTable';
import HasTenancyService from '@/services/Tenancy/TenancyService';
@Service()
export class SalesTaxLiabilitySummaryService {
@Inject()
private repostiory: SalesTaxLiabilitySummaryRepository;
@Inject()
private tenancy: HasTenancyService;
/**
* Retrieve sales tax liability summary.
* @param {number} tenantId
* @param {SalesTaxLiabilitySummaryQuery} query
* @returns
*/
public async salesTaxLiability(
tenantId: number,
query: SalesTaxLiabilitySummaryQuery
) {
const payableByRateId =
await this.repostiory.taxesPayableSumGroupedByRateId(tenantId);
const salesByRateId = await this.repostiory.taxesSalesSumGroupedByRateId(
tenantId
);
const taxRates = await this.repostiory.taxRates(tenantId);
const taxLiabilitySummary = new SalesTaxLiabilitySummary(
query,
taxRates,
payableByRateId,
salesByRateId
);
return {
data: taxLiabilitySummary.reportData(),
query,
meta: this.reportMetadata(tenantId),
};
}
/**
* Retrieve sales tax liability summary table.
* @param {number} tenantId
* @param {SalesTaxLiabilitySummaryQuery} query
* @returns
*/
public async salesTaxLiabilitySummaryTable(
tenantId: number,
query: SalesTaxLiabilitySummaryQuery
) {
const report = await this.salesTaxLiability(tenantId, query);
// Creates the sales tax liability summary table.
const table = new SalesTaxLiabilitySummaryTable(report.data, query);
return {
table: {
rows: table.tableRows(),
columns: table.tableColumns(),
},
data: report.data,
query: report.query,
meta: report.meta,
};
}
/**
* Retrieve the report meta.
* @param {number} tenantId -
* @returns {IBalanceSheetMeta}
*/
private reportMetadata(tenantId: number): SalesTaxLiabilitySummaryMeta {
const settings = this.tenancy.settings(tenantId);
const organizationName = settings.get({
group: 'organization',
key: 'name',
});
const baseCurrency = settings.get({
group: 'organization',
key: 'base_currency',
});
return {
organizationName,
baseCurrency,
};
}
}

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