From 1018a4960e60e896afddced16387aa6d0c7124f9 Mon Sep 17 00:00:00 2001 From: Tim Fabian Date: Tue, 1 Dec 2026 09:50:01 +0100 Subject: [PATCH 1/5] fixes & features --- .github/workflows/cd.yml | 2 +- CODE_STYLE.md | 9 + CONTRIBUTING.md | 35 +- README.md | 9 +- angular.json | 194 +++ cspell.words.txt | 11 +- eslint.config.mjs | 24 +- package-lock.json | 117 +- package.json | 8 +- projects/ngx-approval-requests/CHANGELOG.md | 13 + projects/ngx-approval-requests/LICENSE | 21 + projects/ngx-approval-requests/README.md | 187 +++ .../api/approval-request.service.spec.ts | 128 ++ .../api/approval-request.service.ts | 154 ++ .../approval-requests-config-changes.model.ts | 51 + .../api/approval-requests-config.model.ts | 61 + .../api/approval-requests-config.provider.ts | 134 ++ .../api/approval-requests-labels.model.ts | 123 ++ .../api/approval-requests-paths.model.ts | 13 + .../api/approval-requests-query.model.ts | 23 + .../ngx-approval-requests/api/ng-package.json | 5 + .../ngx-approval-requests/api/public-api.ts | 7 + .../approval-request-changes.component.html | 8 + .../approval-request-changes.component.ts | 25 + .../approval-request-row-view.model.ts | 19 + .../approval-request-view.model.ts | 47 + .../approval-request.component.html | 45 + .../approval-request.component.spec.ts | 247 ++++ .../approval-request.component.ts | 259 ++++ .../approval-request.stories.ts | 121 ++ .../approval-request/ng-package.json | 5 + .../approval-request/public-api.ts | 1 + .../approval-request-list-item.model.ts | 39 + .../approval-requests.component.html | 39 + .../approval-requests.component.spec.ts | 142 ++ .../approval-requests.component.ts | 110 ++ .../approval-requests.stories.ts | 100 ++ .../approval-requests/ng-package.json | 5 + .../approval-requests/public-api.ts | 1 + .../locale/messages.de.xlf | 195 +++ .../ngx-approval-requests/ng-package.json | 8 + projects/ngx-approval-requests/package.json | 37 + .../ngx-approval-requests/src/public-api.ts | 4 + projects/ngx-approval-requests/tailwind.css | 1 + .../ngx-approval-requests/tsconfig.lib.json | 17 + .../tsconfig.lib.prod.json | 11 + .../ngx-approval-requests/tsconfig.spec.json | 10 + projects/ngx-auth/CHANGELOG.md | 26 + projects/ngx-auth/README.md | 80 +- .../accept-invitation-config.model.ts | 11 +- .../accept-invitation-config.provider.ts | 1 + .../accept-invitation-password.component.ts | 2 +- .../accept-invitation-state.type.ts | 6 +- .../accept-invitation.component.html | 70 +- .../accept-invitation.component.spec.ts | 90 +- .../accept-invitation.component.ts | 67 +- .../accept-invitation.stories.ts | 53 +- .../auth/any-level-permission.model.ts | 4 +- projects/ngx-auth/auth/auth-config.model.ts | 6 +- .../ngx-auth/auth/auth-config.provider.ts | 4 +- .../ngx-auth/auth/auth-error-body.model.ts | 2 +- .../ngx-auth/auth/auth-error.utilities.ts | 24 +- projects/ngx-auth/auth/auth-guards.spec.ts | 1 + projects/ngx-auth/auth/auth-headers.model.ts | 2 +- projects/ngx-auth/auth/auth-paths.model.ts | 10 +- .../ngx-auth/auth/auth-strategy-name.type.ts | 2 +- projects/ngx-auth/auth/auth.interceptor.ts | 12 +- projects/ngx-auth/auth/auth.provider.ts | 2 +- projects/ngx-auth/auth/auth.service.spec.ts | 1 + projects/ngx-auth/auth/auth.service.ts | 139 +- projects/ngx-auth/auth/dpop.service.ts | 4 +- .../auth/linked-identity-details.model.ts | 4 +- .../ngx-auth/auth/linked-identity.model.ts | 4 +- projects/ngx-auth/auth/passkey.utilities.ts | 10 +- projects/ngx-auth/auth/permission.guard.ts | 6 +- .../change-password-config.model.ts | 6 +- .../change-password.component.ts | 2 +- .../change-password.stories.ts | 34 +- .../confirm-email-config.model.ts | 2 +- .../confirm-email/confirm-email.component.ts | 9 +- .../confirm-email/confirm-email.stories.ts | 28 +- .../confirm-password-reset-config.model.ts | 6 +- .../confirm-password-reset.component.ts | 6 +- .../confirm-password-reset.stories.ts | 34 +- .../email/email-settings-config.model.ts | 2 +- .../email/email-settings.component.ts | 8 +- .../ngx-auth/email/email-settings.stories.ts | 5 +- .../identities/connectable-provider.model.ts | 2 +- .../identities/identities-config.model.ts | 8 +- .../identities/identities.component.ts | 11 +- .../ngx-auth/identities/identities.stories.ts | 42 +- .../identities/identity-api-access.model.ts | 3 +- .../identities/identity-provider.model.ts | 2 +- .../ngx-auth/identities/identity-row.model.ts | 2 +- projects/ngx-auth/locale/messages.de.xlf | 903 ++++++++++++ .../login-link-config-changes.model.ts | 12 + .../login-link/login-link-config.model.ts | 49 + .../login-link/login-link-config.provider.ts | 49 + .../login-link/login-link.component.html | 25 + .../login-link/login-link.component.spec.ts | 191 +++ .../login-link/login-link.component.ts | 137 ++ .../ngx-auth/login-link/login-link.stories.ts | 116 ++ projects/ngx-auth/login-link/ng-package.json | 5 + projects/ngx-auth/login-link/public-api.ts | 4 + projects/ngx-auth/login/login-config.model.ts | 23 +- .../ngx-auth/login/login-config.provider.ts | 2 + .../login/login-enrollment.component.ts | 11 +- .../ngx-auth/login/login-provider.model.ts | 6 +- projects/ngx-auth/login/login-step.model.ts | 8 +- projects/ngx-auth/login/login.component.html | 42 +- .../ngx-auth/login/login.component.spec.ts | 95 +- projects/ngx-auth/login/login.component.ts | 144 +- projects/ngx-auth/login/login.stories.ts | 140 +- projects/ngx-auth/login/other-login.model.ts | 2 +- .../ngx-auth/login/pending-login.model.ts | 26 + projects/ngx-auth/login/public-api.ts | 3 +- projects/ngx-auth/ng-package.json | 2 +- projects/ngx-auth/package.json | 15 +- .../provider-error-config.model.ts | 2 +- .../provider-error.component.ts | 6 +- .../request-password-reset-config.model.ts | 6 +- .../request-password-reset.component.ts | 8 +- .../request-password-reset.stories.ts | 8 +- .../second-factor-config.model.ts | 2 +- .../second-factor-form.component.ts | 8 +- .../ngx-auth/service-accounts/ng-package.json | 5 + .../ngx-auth/service-accounts/public-api.ts | 6 + .../service-accounts-config-changes.model.ts | 21 + .../service-accounts-config.model.ts | 53 + .../service-accounts-config.provider.ts | 128 ++ .../service-accounts-labels.model.ts | 249 ++++ .../service-accounts.component.html | 267 ++++ .../service-accounts.component.spec.ts | 343 +++++ .../service-accounts.component.ts | 706 +++++++++ .../service-accounts.service.ts | 105 ++ .../service-accounts.stories.ts | 238 +++ .../sessions/sessions-config.model.ts | 4 +- .../ngx-auth/sessions/sessions.component.ts | 2 +- .../ngx-auth/sessions/sessions.stories.ts | 40 +- .../two-factor/two-factor-config.model.ts | 2 +- .../two-factor/two-factor-dialog.component.ts | 4 +- .../two-factor/two-factor-dialog.stories.ts | 8 +- ...two-factor-enrollment-details.component.ts | 2 +- .../two-factor-enrollment-step.type.ts | 4 +- .../two-factor-enrollment.component.ts | 10 +- .../two-factor-enrollment.stories.ts | 50 +- .../two-factor-settings.component.ts | 10 +- .../two-factor/two-factor-settings.stories.ts | 26 +- projects/ngx-backup/CHANGELOG.md | 11 + projects/ngx-backup/LICENSE | 21 + projects/ngx-backup/README.md | 133 ++ .../api/backup-config-changes.model.ts | 17 + .../ngx-backup/api/backup-config.model.ts | 27 + .../ngx-backup/api/backup-config.provider.ts | 153 ++ .../api/backup-labels-changes.model.ts | 8 + .../ngx-backup/api/backup-labels.model.ts | 11 + .../api/backup-transports.service.spec.ts | 117 ++ .../api/backup-transports.service.ts | 79 + projects/ngx-backup/api/ng-package.json | 5 + projects/ngx-backup/api/public-api.ts | 8 + projects/ngx-backup/api/sftp-login.type.ts | 4 + .../api/tenant-transports-labels.model.ts | 273 ++++ .../fixtures/backup-story.utilities.ts | 61 + .../fixtures/backup-testing.utilities.ts | 117 ++ .../ngx-backup/fixtures/backup.fixtures.ts | 123 ++ ...backup-transports-backend-options.model.ts | 32 + .../fake-backup-transports-backend.model.ts | 297 ++++ projects/ngx-backup/locale/messages.de.xlf | 291 ++++ projects/ngx-backup/ng-package.json | 8 + projects/ngx-backup/package.json | 37 + projects/ngx-backup/src/public-api.ts | 5 + projects/ngx-backup/tailwind.css | 1 + .../tenant-transports/ng-package.json | 5 + .../tenant-transports/public-api.ts | 1 + .../tenant-transports.component.html | 244 ++++ .../tenant-transports.component.spec.ts | 402 ++++++ .../tenant-transports.component.ts | 831 +++++++++++ .../tenant-transports.stories.ts | 63 + projects/ngx-backup/test-setup.ts | 4 + projects/ngx-backup/tsconfig.lib.json | 18 + projects/ngx-backup/tsconfig.lib.prod.json | 11 + projects/ngx-backup/tsconfig.spec.json | 10 + projects/ngx-bank/CHANGELOG.md | 14 + projects/ngx-bank/LICENSE | 21 + projects/ngx-bank/README.md | 203 +++ .../api/bank-accounts-labels.model.ts | 33 + .../api/bank-amount.utilities.spec.ts | 28 + .../ngx-bank/api/bank-amount.utilities.ts | 79 + .../ngx-bank/api/bank-common-labels.model.ts | 103 ++ .../ngx-bank/api/bank-config-changes.model.ts | 39 + projects/ngx-bank/api/bank-config.model.ts | 69 + projects/ngx-bank/api/bank-config.provider.ts | 219 +++ projects/ngx-bank/api/bank-day.utilities.ts | 35 + .../ngx-bank/api/bank-iban.utilities.spec.ts | 26 + projects/ngx-bank/api/bank-iban.utilities.ts | 45 + projects/ngx-bank/api/bank-json.utilities.ts | 66 + .../ngx-bank/api/bank-labels-changes.model.ts | 8 + projects/ngx-bank/api/bank-labels.model.ts | 36 + .../api/bank-match-target-option.model.ts | 13 + .../ngx-bank/api/bank-match.utilities.spec.ts | 15 + projects/ngx-bank/api/bank-match.utilities.ts | 24 + .../api/bank-matching-labels.model.ts | 93 ++ projects/ngx-bank/api/bank-paths.model.ts | 50 + .../api/bank-statement-upload-labels.model.ts | 49 + .../api/bank-statements-labels.model.ts | 33 + .../api/bank-statements-query.model.ts | 17 + .../api/bank-transactions-labels.model.ts | 73 + projects/ngx-bank/api/bank-view.directive.ts | 120 ++ projects/ngx-bank/api/bank.service.spec.ts | 161 +++ projects/ngx-bank/api/bank.service.ts | 357 +++++ projects/ngx-bank/api/ng-package.json | 5 + projects/ngx-bank/api/public-api.ts | 20 + .../bank-accounts.component.html | 34 + .../bank-accounts.component.spec.ts | 108 ++ .../bank-accounts/bank-accounts.component.ts | 147 ++ .../bank-accounts/bank-accounts.stories.ts | 26 + .../ngx-bank/bank-accounts/ng-package.json | 5 + projects/ngx-bank/bank-accounts/public-api.ts | 1 + .../bank-matching.component.html | 43 + .../bank-matching.component.spec.ts | 250 ++++ .../bank-matching/bank-matching.component.ts | 218 +++ .../bank-matching/bank-matching.stories.ts | 35 + .../bank-matching/manual-match.component.html | 36 + .../bank-matching/manual-match.component.ts | 241 ++++ .../match-suggestion-view.model.ts | 41 + .../match-suggestion.component.html | 41 + .../match-suggestion.component.ts | 34 + .../ngx-bank/bank-matching/ng-package.json | 5 + projects/ngx-bank/bank-matching/public-api.ts | 1 + .../bank-statements.component.html | 44 + .../bank-statements.component.spec.ts | 92 ++ .../bank-statements.component.ts | 278 ++++ .../bank-statements.stories.ts | 27 + .../ngx-bank/bank-statements/ng-package.json | 5 + .../ngx-bank/bank-statements/public-api.ts | 1 + .../statement-row-view.model.ts | 29 + .../statement-transaction-row-view.model.ts | 25 + .../bank-transactions.component.html | 44 + .../bank-transactions.component.spec.ts | 261 ++++ .../bank-transactions.component.ts | 254 ++++ .../bank-transactions.stories.ts | 40 + .../bank-transactions/ng-package.json | 5 + .../ngx-bank/bank-transactions/public-api.ts | 1 + .../transaction-details.component.html | 58 + .../transaction-details.component.ts | 230 +++ .../transaction-match-status.type.ts | 4 + .../transaction-match-view.model.ts | 41 + .../transaction-row-view.model.ts | 33 + .../transaction-status-filter.type.ts | 7 + .../fixtures/bank-backend.utilities.ts | 124 ++ .../ngx-bank/fixtures/bank-story.utilities.ts | 35 + .../fixtures/bank-testing.utilities.ts | 138 ++ projects/ngx-bank/fixtures/bank.fixtures.ts | 627 ++++++++ projects/ngx-bank/locale/messages.de.xlf | 407 ++++++ projects/ngx-bank/ng-package.json | 8 + projects/ngx-bank/package.json | 37 + projects/ngx-bank/src/public-api.ts | 4 + .../imported-statement-row-view.model.ts | 29 + .../ngx-bank/statement-upload/ng-package.json | 5 + .../ngx-bank/statement-upload/public-api.ts | 1 + .../statement-upload.component.html | 26 + .../statement-upload.component.spec.ts | 93 ++ .../statement-upload.component.ts | 162 +++ .../statement-upload.stories.ts | 19 + projects/ngx-bank/tailwind.css | 1 + projects/ngx-bank/test-setup.ts | 29 + projects/ngx-bank/tsconfig.lib.json | 18 + projects/ngx-bank/tsconfig.lib.prod.json | 11 + projects/ngx-bank/tsconfig.spec.json | 10 + projects/ngx-bookkeeping/CHANGELOG.md | 21 + projects/ngx-bookkeeping/LICENSE | 21 + projects/ngx-bookkeeping/README.md | 365 +++++ .../api/bookkeeping-amount.utilities.spec.ts | 31 + .../api/bookkeeping-amount.utilities.ts | 86 ++ .../api/bookkeeping-common-labels.model.ts | 105 ++ .../api/bookkeeping-config-changes.model.ts | 34 + .../api/bookkeeping-config.model.ts | 62 + .../api/bookkeeping-config.provider.spec.ts | 89 ++ .../api/bookkeeping-config.provider.ts | 284 ++++ .../api/bookkeeping-day.utilities.spec.ts | 36 + .../api/bookkeeping-day.utilities.ts | 84 ++ .../bookkeeping-entry-form-labels.model.ts | 65 + .../api/bookkeeping-file.model.ts | 13 + .../api/bookkeeping-file.utilities.spec.ts | 12 + .../api/bookkeeping-file.utilities.ts | 39 + .../bookkeeping-fiscal-year.utilities.spec.ts | 25 + .../api/bookkeeping-fiscal-year.utilities.ts | 57 + .../bookkeeping-fiscal-years-labels.model.ts | 222 +++ .../api/bookkeeping-journal-labels.model.ts | 85 ++ .../api/bookkeeping-json.utilities.ts | 158 ++ .../api/bookkeeping-labels-changes.model.ts | 8 + .../api/bookkeeping-labels.model.ts | 41 + .../api/bookkeeping-ledger-labels.model.ts | 25 + .../api/bookkeeping-paths.model.ts | 67 + .../api/bookkeeping-statement-labels.model.ts | 45 + .../bookkeeping-trial-balance-labels.model.ts | 33 + .../api/bookkeeping-view.directive.ts | 178 +++ .../api/bookkeeping.service.spec.ts | 116 ++ .../api/bookkeeping.service.ts | 381 +++++ .../e-bilanz-account-mappings-labels.model.ts | 85 ++ .../api/e-bilanz-certificate-labels.model.ts | 49 + .../api/e-bilanz-common-labels.model.ts | 105 ++ .../api/e-bilanz-config-changes.model.ts | 21 + .../api/e-bilanz-config.model.ts | 37 + .../api/e-bilanz-config.provider.spec.ts | 42 + .../api/e-bilanz-config.provider.ts | 299 ++++ .../api/e-bilanz-correction-status.type.ts | 7 + .../api/e-bilanz-filing-labels.model.ts | 197 +++ .../api/e-bilanz-labels-changes.model.ts | 8 + .../api/e-bilanz-labels.model.ts | 41 + .../api/e-bilanz-paths.model.ts | 52 + .../api/e-bilanz-preparation-labels.model.ts | 79 + .../api/e-bilanz-records-labels.model.ts | 57 + .../api/e-bilanz-review-labels.model.ts | 74 + .../api/e-bilanz.service.spec.ts | 334 +++++ .../ngx-bookkeeping/api/e-bilanz.service.ts | 232 +++ .../api/fiscal-year-filing-resolver.model.ts | 13 + .../fiscal-year-filing-resolver.provider.ts | 22 + projects/ngx-bookkeeping/api/ng-package.json | 5 + projects/ngx-bookkeeping/api/public-api.ts | 37 + .../balance-sheet.component.html | 1 + .../balance-sheet.component.spec.ts | 96 ++ .../balance-sheet/balance-sheet.component.ts | 22 + .../balance-sheet/balance-sheet.stories.ts | 75 + .../balance-sheet/ng-package.json | 5 + .../balance-sheet/public-api.ts | 1 + .../e-bilanz-account-mappings.component.html | 118 ++ .../e-bilanz-account-mappings.component.ts | 287 ++++ .../e-bilanz/e-bilanz-account-view.model.ts | 17 + .../e-bilanz/e-bilanz-action-view.model.ts | 17 + .../e-bilanz-certificate.component.html | 41 + .../e-bilanz-certificate.component.ts | 149 ++ .../e-bilanz/e-bilanz-content-tab.type.ts | 5 + .../e-bilanz/e-bilanz-content.component.html | 96 ++ .../e-bilanz/e-bilanz-content.component.ts | 194 +++ .../e-bilanz/e-bilanz-exporter-view.model.ts | 15 + .../e-bilanz-figure-row-view.model.ts | 23 + .../e-bilanz/e-bilanz-figure-view.model.ts | 21 + .../e-bilanz/e-bilanz-figures.type.ts | 5 + .../e-bilanz/e-bilanz-filing-view.model.ts | 43 + .../e-bilanz/e-bilanz-filing.component.html | 77 + .../e-bilanz/e-bilanz-filing.component.ts | 268 ++++ .../e-bilanz/e-bilanz-filings.component.html | 56 + .../e-bilanz/e-bilanz-filings.component.ts | 132 ++ .../e-bilanz/e-bilanz-finding-target.model.ts | 16 + .../e-bilanz/e-bilanz-finding-view.model.ts | 27 + .../e-bilanz/e-bilanz-findings.component.html | 21 + .../e-bilanz/e-bilanz-findings.component.ts | 108 ++ .../e-bilanz-fixed-asset-value-view.model.ts | 17 + .../e-bilanz-fixed-asset-view.model.ts | 27 + ...-bilanz-manual-filing-dialog-data.model.ts | 9 + ...bilanz-manual-filing-dialog.component.html | 16 + ...e-bilanz-manual-filing-dialog.component.ts | 87 ++ .../e-bilanz/e-bilanz-mapping-view.model.ts | 27 + .../e-bilanz/e-bilanz-outcome.model.ts | 22 + .../e-bilanz/e-bilanz-phase.type.ts | 5 + .../e-bilanz/e-bilanz-position-view.model.ts | 35 + .../e-bilanz-preparation.component.html | 81 ++ .../e-bilanz-preparation.component.ts | 364 +++++ .../e-bilanz-statement-tab-view.model.ts | 21 + .../e-bilanz/e-bilanz-statement-view.model.ts | 19 + .../e-bilanz/e-bilanz-tab.type.ts | 4 + .../e-bilanz/e-bilanz-test.component.html | 20 + .../e-bilanz/e-bilanz-test.component.ts | 94 ++ .../e-bilanz-transmission.component.html | 41 + .../e-bilanz-transmission.component.ts | 153 ++ .../e-bilanz-unmapped-account-view.model.ts | 29 + .../e-bilanz/e-bilanz-unsettled-view.model.ts | 17 + .../e-bilanz/e-bilanz-view.utilities.ts | 303 ++++ .../e-bilanz/e-bilanz.component.html | 190 +++ .../e-bilanz/e-bilanz.component.spec.ts | 941 ++++++++++++ .../e-bilanz/e-bilanz.component.ts | 704 +++++++++ .../e-bilanz/e-bilanz.stories.ts | 165 +++ .../ngx-bookkeeping/e-bilanz/ng-package.json | 5 + .../ngx-bookkeeping/e-bilanz/public-api.ts | 1 + .../closing-proposal-line-view.model.ts | 17 + .../closing-proposal-view.model.ts | 37 + .../closing-proposal.component.html | 35 + .../closing-proposal.component.ts | 44 + .../fiscal-year-closing.component.html | 39 + .../fiscal-year-closing.component.ts | 324 +++++ .../fiscal-year-details.component.html | 37 + .../fiscal-year-details.component.ts | 182 +++ .../fiscal-year-export.component.html | 14 + .../fiscal-year-export.component.ts | 84 ++ ...fiscal-year-reopening-dialog-data.model.ts | 15 + ...iscal-year-reopening-dialog.component.html | 34 + ...al-year-reopening-dialog.component.spec.ts | 205 +++ .../fiscal-year-reopening-dialog.component.ts | 132 ++ .../fiscal-year-row-view.model.ts | 25 + .../fiscal-years/fiscal-years.component.html | 55 + .../fiscal-years.component.spec.ts | 225 +++ .../fiscal-years/fiscal-years.component.ts | 282 ++++ .../fiscal-years/fiscal-years.stories.ts | 101 ++ .../fiscal-years/ng-package.json | 5 + .../fiscal-years/public-api.ts | 1 + .../fixtures/bookkeeping-story.utilities.ts | 98 ++ .../fixtures/bookkeeping-testing.utilities.ts | 189 +++ .../fixtures/bookkeeping.fixtures.ts | 571 ++++++++ .../fixtures/e-bilanz.fixtures.ts | 290 ++++ .../fake-e-bilanz-backend-options.model.ts | 44 + .../fixtures/fake-e-bilanz-backend.model.ts | 767 ++++++++++ .../income-statement.component.html | 1 + .../income-statement.component.spec.ts | 48 + .../income-statement.component.ts | 22 + .../income-statement.stories.ts | 36 + .../income-statement/ng-package.json | 5 + .../income-statement/public-api.ts | 1 + .../journal-entry-form-line-view.model.ts | 25 + .../journal-entry-form-line.model.ts | 21 + .../journal-entry-form.component.html | 109 ++ .../journal-entry-form.component.spec.ts | 150 ++ .../journal-entry-form.component.ts | 397 +++++ .../journal-entry-form.stories.ts | 33 + .../journal-entry-form/ng-package.json | 5 + .../journal-entry-form/public-api.ts | 1 + ...ournal-entry-reversal-dialog-data.model.ts | 13 + ...urnal-entry-reversal-dialog.component.html | 17 + ...journal-entry-reversal-dialog.component.ts | 97 ++ .../journal/journal-entry-view.model.ts | 64 + .../journal/journal-entry.component.html | 59 + .../journal/journal-entry.component.ts | 40 + .../journal/journal-line-view.model.ts | 21 + .../journal/journal.component.html | 49 + .../journal/journal.component.spec.ts | 220 +++ .../journal/journal.component.ts | 300 ++++ .../journal/journal.stories.ts | 55 + .../ngx-bookkeeping/journal/ng-package.json | 5 + .../ngx-bookkeeping/journal/public-api.ts | 1 + .../ledger/ledger-balance-view.model.ts | 17 + .../ledger/ledger-balance.component.html | 5 + .../ledger/ledger-balance.component.ts | 19 + .../ledger/ledger-line-view.model.ts | 39 + .../ledger/ledger-table.component.html | 49 + .../ledger/ledger-table.component.ts | 35 + .../ledger/ledger-view.model.ts | 32 + .../ledger/ledger.component.html | 32 + .../ledger/ledger.component.spec.ts | 68 + .../ledger/ledger.component.ts | 177 +++ .../ngx-bookkeeping/ledger/ledger.stories.ts | 31 + .../ngx-bookkeeping/ledger/ng-package.json | 5 + projects/ngx-bookkeeping/ledger/public-api.ts | 1 + .../ngx-bookkeeping/locale/messages.de.xlf | 1283 +++++++++++++++++ projects/ngx-bookkeeping/ng-package.json | 8 + projects/ngx-bookkeeping/package.json | 36 + projects/ngx-bookkeeping/src/public-api.ts | 4 + .../ngx-bookkeeping/statement/ng-package.json | 5 + .../ngx-bookkeeping/statement/public-api.ts | 1 + .../statement-position-view.model.ts | 25 + .../statement/statement-table.component.html | 26 + .../statement/statement-table.component.ts | 29 + .../statement/statement-view.model.ts | 37 + .../statement/statement.component.html | 32 + .../statement/statement.component.ts | 212 +++ projects/ngx-bookkeeping/tailwind.css | 1 + projects/ngx-bookkeeping/test-setup.ts | 29 + .../trial-balance/ng-package.json | 5 + .../trial-balance/public-api.ts | 1 + .../trial-balance-row-view.model.ts | 33 + .../trial-balance/trial-balance-view.model.ts | 31 + .../trial-balance.component.html | 66 + .../trial-balance.component.spec.ts | 65 + .../trial-balance/trial-balance.component.ts | 132 ++ .../trial-balance/trial-balance.stories.ts | 35 + projects/ngx-bookkeeping/tsconfig.lib.json | 18 + .../ngx-bookkeeping/tsconfig.lib.prod.json | 11 + projects/ngx-bookkeeping/tsconfig.spec.json | 10 + projects/ngx-change-sets/CHANGELOG.md | 17 + projects/ngx-change-sets/README.md | 63 +- .../change-sets/change-set-view.model.ts | 8 +- .../change-sets/change-sets-config.model.ts | 10 +- .../change-sets-config.provider.ts | 4 +- .../change-sets/change-sets.component.html | 2 +- .../change-sets/change-sets.component.spec.ts | 21 +- .../change-sets/change-sets.component.ts | 38 +- .../change-sets/change-value.utilities.ts | 35 - .../change-sets/changes-table.component.ts | 36 - .../change-value.utilities.spec.ts | 6 + .../changes/change-value.utilities.ts | 54 + .../change-view.model.ts | 2 +- .../changes/changes-config-changes.model.ts | 11 + .../changes/changes-config.model.ts | 33 + .../changes/changes-config.provider.ts | 45 + .../changes.component.html} | 6 +- .../changes/changes.component.spec.ts | 66 + .../changes/changes.component.ts | 53 + .../changes/changes.stories.ts | 30 + .../ngx-change-sets/changes/ng-package.json | 5 + .../ngx-change-sets/changes/public-api.ts | 6 + .../changes/value-change.model.ts | 7 + .../change-sets-field-config.model.ts | 9 + .../change-sets-field-config.provider.ts | 39 + .../change-sets-field-data.model.ts | 20 + .../change-sets-field.component.html | 17 + .../change-sets-field.component.spec.ts | 204 +++ .../change-sets-field.component.ts | 71 + .../entity-field/change-sets-field.stories.ts | 123 ++ .../entity-field/ng-package.json | 5 + .../entity-field/public-api.ts | 4 + .../ngx-change-sets/locale/messages.de.xlf | 119 ++ projects/ngx-change-sets/ng-package.json | 2 +- projects/ngx-change-sets/package.json | 17 +- projects/ngx-ecommerce/CHANGELOG.md | 7 + projects/ngx-ecommerce/README.md | 2 + .../input-extras/input-extras.component.ts | 4 +- .../input-extras/input-extras.stories.ts | 6 +- projects/ngx-ecommerce/locale/messages.de.xlf | 71 + projects/ngx-ecommerce/ng-package.json | 2 +- projects/ngx-ecommerce/package.json | 9 +- projects/ngx-entity/CHANGELOG.md | 27 + projects/ngx-entity/README.md | 47 +- .../dialog/entity-dialog.service.spec.ts | 53 +- .../editor/entity-editor.component.html | 2 +- .../editor/entity-editor.component.ts | 22 +- .../entity/chips-array-item-metadata.model.ts | 9 + .../entity/entity-text.utilities.ts | 19 +- .../entity/entity.utilities.spec.ts | 40 + .../ngx-entity/entity/entity.utilities.ts | 12 +- .../ngx-entity/entity/enum-labels.type.ts | 5 + .../entity/number-property-metadata.model.ts | 15 +- .../entity/property-position.model.ts | 5 +- .../ngx-entity/entity/property.decorator.ts | 25 +- projects/ngx-entity/entity/public-api.ts | 1 + .../entity/string-property-metadata.model.ts | 19 +- .../entity-autocomplete-field.component.html | 2 + .../field-base/base-entity-field.directive.ts | 16 +- .../entity-boolean-field.component.html | 1 + .../entity-cards-field.component.html | 13 + .../entity-cards-field.component.spec.ts | 179 +++ .../entity-cards-field.component.ts | 44 + .../entity-cards-field.stories.html | 6 + .../field-cards/entity-cards-field.stories.ts | 104 ++ .../ngx-entity/field-cards/ng-package.json | 5 + projects/ngx-entity/field-cards/public-api.ts | 1 + .../entity-chips-field.component.html | 1 + .../entity-chips-field.component.ts | 2 +- .../entity-date-field.component.html | 1 + .../entity-number-field.component.html | 1 + .../entity-reference-field.component.html | 1 + .../entity-select-field.component.html | 1 + .../entity-select-field.component.ts | 6 +- .../entity-slider-field.component.html | 1 + .../entity-string-field.component.html | 2 + .../entity-textarea-field.component.html | 1 + .../field/entity-field-kind.type.ts | 5 +- .../field/entity-field.component.spec.ts | 36 +- .../field/entity-field.component.ts | 16 +- .../field/entity-field.utilities.ts | 12 +- .../field/entity-fields.provider.ts | 1 + .../form/entity-form-rows.component.html | 1 + .../form/entity-form-rows.component.ts | 19 +- .../form/entity-form.component.html | 9 +- .../form/entity-form.component.spec.ts | 113 +- .../ngx-entity/form/entity-form.component.ts | 25 +- .../form/entity-form.utilities.spec.ts | 22 + .../ngx-entity/form/entity-form.utilities.ts | 26 +- projects/ngx-entity/locale/messages.de.xlf | 179 +++ projects/ngx-entity/ng-package.json | 2 +- projects/ngx-entity/package.json | 16 +- .../page/entity-page.component.spec.ts | 27 + .../table/entity-table.component.spec.ts | 6 +- .../table/entity-table.utilities.ts | 4 +- projects/ngx-error-handling/CHANGELOG.md | 11 + projects/ngx-error-handling/README.md | 4 +- .../error-response.utilities.spec.ts | 19 + .../error-response.utilities.ts | 13 + .../ngx-error-handling/locale/messages.de.xlf | 39 + projects/ngx-error-handling/ng-package.json | 2 +- projects/ngx-error-handling/package.json | 11 +- projects/ngx-navigation/CHANGELOG.md | 20 + projects/ngx-navigation/README.md | 12 +- .../breadcrumbs/breadcrumbs.stories.ts | 2 +- .../footer/footer.component.html | 4 +- .../footer/footer.component.spec.ts | 21 +- .../language-menu-items.component.ts | 2 +- .../language-switcher-config.provider.ts | 2 +- .../language-switcher.component.spec.ts | 23 +- .../language-switcher.component.ts | 16 +- .../ngx-navigation/locale/messages.de.xlf | 43 + .../nav-element/nav-row.component.html | 6 +- .../nav-element/nav-row.component.ts | 58 +- .../nav-menu/nav-menu.component.ts | 2 +- .../navbar/navbar-config.model.ts | 12 +- .../navbar/navbar-config.provider.ts | 9 +- .../navbar/navbar.component.html | 11 + .../navbar/navbar.component.spec.ts | 33 +- .../ngx-navigation/navbar/navbar.component.ts | 18 +- .../ngx-navigation/navbar/navbar.stories.ts | 3 +- .../navigation/nav-anchor.model.ts | 2 +- .../navigation/nav-row-width.type.ts | 6 + .../navigation/navigation-config.model.ts | 14 +- .../navigation/navigation-config.provider.ts | 6 +- .../navigation/navigation.service.spec.ts | 2 +- .../ngx-navigation/navigation/public-api.ts | 1 + projects/ngx-navigation/ng-package.json | 2 +- .../not-found/not-found-config.provider.ts | 2 +- .../not-found/not-found.component.spec.ts | 2 +- projects/ngx-navigation/package.json | 9 +- projects/ngx-persistence-logger/CHANGELOG.md | 10 + projects/ngx-persistence-logger/README.md | 2 + .../locale/messages.de.xlf | 71 + .../applications-filter.component.ts | 2 +- .../log-history/levels-filter.component.ts | 2 +- .../log-history/log-history.component.ts | 2 +- .../ngx-persistence-logger/ng-package.json | 2 +- projects/ngx-persistence-logger/package.json | 11 +- projects/ngx-projects/CHANGELOG.md | 15 + projects/ngx-projects/LICENSE | 21 + projects/ngx-projects/README.md | 196 +++ projects/ngx-projects/api/ng-package.json | 5 + .../api/project-board-labels.model.ts | 97 ++ .../api/project-board.service.spec.ts | 263 ++++ .../ngx-projects/api/project-board.service.ts | 199 +++ .../api/project-board.utilities.spec.ts | 49 + .../api/project-board.utilities.ts | 135 ++ .../api/project-calendar-labels.model.ts | 75 + .../api/project-day.utilities.spec.ts | 17 + .../ngx-projects/api/project-day.utilities.ts | 100 ++ .../api/project-label-color.utilities.spec.ts | 23 + .../api/project-label-color.utilities.ts | 27 + .../api/project-role.utilities.spec.ts | 31 + .../api/project-role.utilities.ts | 32 + .../api/project-sharing-labels.model.ts | 85 ++ .../api/project-task-labels.model.ts | 129 ++ .../api/projects-common-labels.model.ts | 51 + .../api/projects-config-changes.model.ts | 21 + .../ngx-projects/api/projects-config.model.ts | 68 + .../api/projects-config.provider.ts | 296 ++++ .../api/projects-labels-changes.model.ts | 8 + .../ngx-projects/api/projects-labels.model.ts | 41 + .../ngx-projects/api/projects-paths.model.ts | 50 + .../api/projects-tree-labels.model.ts | 65 + .../api/projects-view.directive.ts | 141 ++ .../ngx-projects/api/projects.service.spec.ts | 312 ++++ projects/ngx-projects/api/projects.service.ts | 469 ++++++ projects/ngx-projects/api/public-api.ts | 20 + .../api/recurring-tasks-labels.model.ts | 151 ++ projects/ngx-projects/board/ng-package.json | 5 + .../board/project-board.component.html | 134 ++ .../board/project-board.component.spec.ts | 237 +++ .../board/project-board.component.ts | 345 +++++ .../board/project-board.stories.ts | 62 + projects/ngx-projects/board/public-api.ts | 3 + .../board/task-card-label-view.model.ts | 19 + .../board/task-card-view.model.ts | 43 + .../ngx-projects/calendar/ng-package.json | 5 + .../calendar/project-calendar.component.html | 76 + .../project-calendar.component.spec.ts | 165 +++ .../calendar/project-calendar.component.ts | 347 +++++ .../calendar/project-calendar.stories.ts | 61 + projects/ngx-projects/calendar/public-api.ts | 1 + .../fixtures/projects-backend.utilities.ts | 137 ++ .../fixtures/projects-story.utilities.ts | 72 + .../fixtures/projects-testing.utilities.ts | 159 ++ .../fixtures/projects.fixtures.ts | 356 +++++ projects/ngx-projects/locale/messages.de.xlf | 683 +++++++++ projects/ngx-projects/ng-package.json | 8 + projects/ngx-projects/package.json | 43 + .../ngx-projects/projects/ng-package.json | 5 + .../projects/project-node.model.ts | 23 + .../projects/project-tree.utilities.spec.ts | 69 + .../projects/project-tree.utilities.ts | 50 + .../projects/projects.component.html | 89 ++ .../projects/projects.component.spec.ts | 120 ++ .../projects/projects.component.ts | 220 +++ .../ngx-projects/projects/projects.stories.ts | 43 + projects/ngx-projects/projects/public-api.ts | 3 + .../recurring-tasks/ng-package.json | 5 + .../recurring-tasks/public-api.ts | 3 + .../recurring-task-view.model.ts | 23 + .../recurring-task.utilities.spec.ts | 57 + .../recurring-task.utilities.ts | 31 + .../recurring-tasks.component.html | 112 ++ .../recurring-tasks.component.spec.ts | 124 ++ .../recurring-tasks.component.ts | 377 +++++ .../recurring-tasks.stories.ts | 33 + projects/ngx-projects/sharing/ng-package.json | 5 + .../sharing/project-share-view.model.ts | 31 + .../sharing/project-sharing.component.html | 67 + .../sharing/project-sharing.component.spec.ts | 112 ++ .../sharing/project-sharing.component.ts | 221 +++ .../sharing/project-sharing.stories.ts | 42 + projects/ngx-projects/sharing/public-api.ts | 2 + projects/ngx-projects/src/public-api.ts | 4 + projects/ngx-projects/tailwind.css | 1 + projects/ngx-projects/task/ng-package.json | 5 + .../task/project-task.component.html | 174 +++ .../task/project-task.component.spec.ts | 201 +++ .../task/project-task.component.ts | 652 +++++++++ .../ngx-projects/task/project-task.stories.ts | 54 + projects/ngx-projects/task/public-api.ts | 3 + .../task/task-change-set.service.spec.ts | 68 + .../task/task-change-set.service.ts | 46 + .../task/task-comment-view.model.ts | 29 + projects/ngx-projects/test-setup.ts | 33 + projects/ngx-projects/tsconfig.lib.json | 18 + projects/ngx-projects/tsconfig.lib.prod.json | 11 + projects/ngx-projects/tsconfig.spec.json | 10 + projects/ngx-pwa/CHANGELOG.md | 7 + projects/ngx-pwa/README.md | 2 + projects/ngx-pwa/locale/messages.de.xlf | 123 ++ projects/ngx-pwa/ng-package.json | 2 +- .../offline-status-bar.component.ts | 4 +- .../offline-status-bar.stories.ts | 6 + .../offline-status-view.model.ts | 2 +- projects/ngx-pwa/package.json | 9 +- .../sync-dialog/sync-dialog.component.ts | 3 +- projects/ngx-tracking/CHANGELOG.md | 18 + projects/ngx-tracking/README.md | 105 +- .../analytics/analytics-config.model.ts | 11 + .../analytics/analytics-config.provider.ts | 14 + .../analytics/analytics.provider.ts | 23 + .../analytics/analytics.service.spec.ts | 227 +++ .../analytics/analytics.service.ts | 245 ++++ .../ngx-tracking/analytics/ng-package.json | 5 + projects/ngx-tracking/analytics/public-api.ts | 4 + .../consent/consent-config.model.ts | 11 +- .../consent/consent.service.spec.ts | 80 +- .../ngx-tracking/consent/consent.service.ts | 41 +- .../consent/tracking-consent.provider.ts | 8 +- projects/ngx-tracking/locale/messages.de.xlf | 59 + projects/ngx-tracking/ng-package.json | 2 +- projects/ngx-tracking/package.json | 15 +- .../privacy-settings.component.ts | 2 +- projects/ngx-web-dav/CHANGELOG.md | 14 + projects/ngx-web-dav/LICENSE | 21 + projects/ngx-web-dav/README.md | 188 +++ .../api/file-mirror-conflicts-labels.model.ts | 91 ++ .../file-mirror-share-link-labels.model.ts | 61 + .../api/file-mirror.service.spec.ts | 89 ++ .../ngx-web-dav/api/file-mirror.service.ts | 88 ++ projects/ngx-web-dav/api/ng-package.json | 5 + projects/ngx-web-dav/api/public-api.ts | 10 + .../api/web-dav-config-changes.model.ts | 21 + .../ngx-web-dav/api/web-dav-config.model.ts | 51 + .../api/web-dav-config.provider.ts | 160 ++ .../api/web-dav-connections-labels.model.ts | 131 ++ .../api/web-dav-connections.service.spec.ts | 136 ++ .../api/web-dav-connections.service.ts | 83 ++ .../api/web-dav-labels-changes.model.ts | 8 + .../ngx-web-dav/api/web-dav-labels.model.ts | 22 + .../file-mirror-conflicts.component.html | 76 + .../file-mirror-conflicts.component.spec.ts | 172 +++ .../file-mirror-conflicts.component.ts | 264 ++++ .../file-mirror-conflicts.stories.ts | 56 + .../ngx-web-dav/conflicts/ng-package.json | 5 + projects/ngx-web-dav/conflicts/public-api.ts | 1 + .../ngx-web-dav/connections/ng-package.json | 5 + .../ngx-web-dav/connections/public-api.ts | 1 + .../web-dav-connections.component.html | 176 +++ .../web-dav-connections.component.spec.ts | 277 ++++ .../web-dav-connections.component.ts | 444 ++++++ .../web-dav-connections.stories.ts | 57 + .../fake-file-mirror-backend-options.model.ts | 29 + .../fake-file-mirror-backend.model.ts | 201 +++ ...b-dav-connections-backend-options.model.ts | 29 + .../fake-web-dav-connections-backend.model.ts | 230 +++ .../fixtures/web-dav-story.utilities.ts | 83 ++ .../fixtures/web-dav-testing.utilities.ts | 105 ++ .../ngx-web-dav/fixtures/web-dav.fixtures.ts | 146 ++ projects/ngx-web-dav/locale/messages.de.xlf | 279 ++++ projects/ngx-web-dav/ng-package.json | 8 + projects/ngx-web-dav/package.json | 36 + .../file-mirror-share-link.component.html | 35 + .../file-mirror-share-link.component.spec.ts | 168 +++ .../file-mirror-share-link.component.ts | 193 +++ .../file-mirror-share-link.stories.ts | 35 + .../ngx-web-dav/share-link/ng-package.json | 5 + projects/ngx-web-dav/share-link/public-api.ts | 1 + projects/ngx-web-dav/src/public-api.ts | 6 + projects/ngx-web-dav/tailwind.css | 1 + projects/ngx-web-dav/test-setup.ts | 4 + projects/ngx-web-dav/tsconfig.lib.json | 18 + projects/ngx-web-dav/tsconfig.lib.prod.json | 11 + projects/ngx-web-dav/tsconfig.spec.json | 10 + projects/ngx-websocket/CHANGELOG.md | 10 + projects/ngx-websocket/LICENSE | 21 + projects/ngx-websocket/README.md | 127 ++ projects/ngx-websocket/ng-package.json | 8 + projects/ngx-websocket/package.json | 22 + projects/ngx-websocket/src/public-api.ts | 4 + projects/ngx-websocket/tsconfig.lib.json | 16 + projects/ngx-websocket/tsconfig.lib.prod.json | 11 + projects/ngx-websocket/tsconfig.spec.json | 10 + .../ngx-websocket/websocket/ng-package.json | 5 + .../ngx-websocket/websocket/public-api.ts | 13 + .../websocket/socket-io-client.function.ts | 43 + .../websocket/websocket-answer.error.ts | 35 + .../websocket-client-factory.type.ts | 7 + .../websocket-client-options.model.ts | 24 + .../websocket/websocket-client.model.ts | 41 + .../websocket/websocket-config.model.ts | 44 + .../websocket/websocket-config.provider.ts | 47 + .../websocket-handshake-auth.model.ts | 15 + .../websocket-headers-resolver.type.ts | 6 + .../websocket/websocket-listener.type.ts | 4 + .../websocket/websocket-message.model.ts | 26 + .../websocket/websocket-message.utilities.ts | 28 + .../websocket/websocket-replay.model.ts | 10 + .../websocket/websocket.service.spec.ts | 241 ++++ .../websocket/websocket.service.ts | 246 ++++ .../testing/http/http-testing.utilities.ts | 63 +- .../websocket/fake-websocket-answer.model.ts | 17 + .../fake-websocket-handshake.model.ts | 17 + .../websocket/fake-websocket-message.model.ts | 13 + .../testing/websocket/fake-websocket.model.ts | 280 ++++ projects/testing/websocket/ng-package.json | 5 + projects/testing/websocket/public-api.ts | 4 + projects/ui/.storybook/main.ts | 8 +- projects/ui/.storybook/styles.css | 6 + projects/ui/.storybook/tsconfig.json | 4 +- projects/ui/CHANGELOG.md | 30 + projects/ui/README.md | 153 +- projects/ui/address/address.component.ts | 4 +- .../ui/back-to-top/back-to-top.component.ts | 2 +- projects/ui/board/board-card-context.model.ts | 15 + .../ui/board/board-column-context.model.ts | 20 + projects/ui/board/board-column.model.ts | 17 + projects/ui/board/board-config.model.ts | 40 + projects/ui/board/board-config.provider.ts | 48 + projects/ui/board/board-move-result.model.ts | 16 + projects/ui/board/board-move.model.ts | 25 + projects/ui/board/board.component.html | 81 ++ projects/ui/board/board.component.spec.ts | 233 +++ projects/ui/board/board.component.ts | 390 +++++ projects/ui/board/board.stories.ts | 120 ++ projects/ui/board/board.utilities.spec.ts | 35 + projects/ui/board/board.utilities.ts | 42 + projects/ui/board/ng-package.json | 5 + projects/ui/board/public-api.ts | 9 + .../ui/breadcrumbs/breadcrumb.component.ts | 2 +- projects/ui/byline/byline-item.model.ts | 2 +- projects/ui/byline/byline.component.spec.ts | 2 +- projects/ui/byline/byline.stories.ts | 3 +- .../ui/callout/callout-config.provider.ts | 7 +- projects/ui/callout/callout.component.spec.ts | 4 +- projects/ui/callout/callout.stories.ts | 2 +- projects/ui/card/card-media.component.html | 1 + projects/ui/card/card-media.component.ts | 20 + projects/ui/card/card.component.spec.ts | 24 + projects/ui/card/card.component.ts | 3 +- projects/ui/card/card.stories.ts | 30 +- projects/ui/card/public-api.ts | 1 + .../category-overview-config.provider.ts | 2 +- .../category-overview.stories.ts | 3 +- .../check-list/check-list-config.provider.ts | 3 +- .../check-list/check-list.component.spec.ts | 4 +- projects/ui/check-list/check-list.stories.ts | 2 +- .../ui/consent-gate/consent-gate.component.ts | 2 +- .../count-badge/count-badge-config.model.ts | 21 + .../count-badge-config.provider.ts | 36 + .../count-badge/count-badge-placement.type.ts | 5 + .../ui/count-badge/count-badge.component.html | 6 + .../count-badge/count-badge.component.spec.ts | 80 + .../ui/count-badge/count-badge.component.ts | 91 ++ .../ui/count-badge/count-badge.stories.ts | 89 ++ projects/ui/count-badge/ng-package.json | 5 + projects/ui/count-badge/public-api.ts | 4 + projects/ui/drawer/drawer.component.ts | 2 +- .../empty-state-config.provider.ts | 4 +- .../empty-state/empty-state.component.spec.ts | 4 +- .../event-calendar-event.component.ts | 2 +- .../event-calendar.component.ts | 3 +- .../filter-tiles/filter-tile-option.model.ts | 2 +- .../filter-tiles-config.provider.ts | 2 +- .../filter-tiles.component.spec.ts | 2 +- .../ui/filter-tiles/filter-tiles.stories.ts | 5 +- .../form-draft/form-draft.directive.spec.html | 2 +- .../form-draft/form-draft.directive.spec.ts | 57 +- .../ui/form-draft/form-draft.directive.ts | 60 +- projects/ui/gallery/gallery.component.ts | 4 +- projects/ui/icon/icon-definition.model.ts | 2 +- projects/ui/icon/icon.component.spec.ts | 2 +- projects/ui/icon/icon.component.ts | 4 +- projects/ui/icon/icon.stories.ts | 5 +- .../input-boolean/input-boolean.component.ts | 3 +- .../input-cards-multiple.component.ts | 2 +- .../ui/input-cards/input-cards.component.ts | 2 +- .../ui/input-cards/input-cards.stories.ts | 4 +- .../ui/input-chips/input-chip.component.ts | 2 +- .../ui/input-chips/input-chips.component.ts | 2 +- .../input-date-range.component.ts | 7 +- .../input-date-calendar.component.ts | 5 +- .../input-date/input-date.component.spec.ts | 3 +- .../ui/input-date/input-date.component.ts | 6 +- .../input-date/input-date.utilities.spec.ts | 24 + .../ui/input-date/input-date.utilities.ts | 46 +- .../input-file/input-file-entry.component.ts | 3 +- .../input-file-summary.component.ts | 2 +- .../ui/input-file/input-file.component.ts | 3 +- .../ui/input-select/input-select.component.ts | 2 +- .../ui/input-string/input-string.component.ts | 5 +- .../ui/input-time/input-time.component.ts | 2 +- projects/ui/input/input-config.model.ts | 6 + projects/ui/input/input-config.provider.ts | 7 + projects/ui/input/input-date-part.type.ts | 4 + projects/ui/input/public-api.ts | 1 + projects/ui/link/link.component.ts | 2 +- projects/ui/link/link.stories.ts | 3 +- projects/ui/locale/messages.de.xlf | 599 ++++++++ .../ui/logo-cloud/logo-cloud-logo.model.ts | 7 +- .../logo-cloud/logo-cloud-shown-logo.model.ts | 6 +- .../ui/logo-cloud/logo-cloud.component.html | 4 +- .../logo-cloud/logo-cloud.component.spec.ts | 15 +- .../ui/logo-cloud/logo-cloud.component.ts | 26 +- projects/ui/map/map.component.ts | 2 +- projects/ui/markdown/markdown-config.model.ts | 10 + .../ui/markdown/markdown-config.provider.ts | 33 + projects/ui/markdown/markdown.component.html | 1 + .../ui/markdown/markdown.component.spec.ts | 133 ++ projects/ui/markdown/markdown.component.ts | 47 + projects/ui/markdown/markdown.stories.ts | 52 + projects/ui/markdown/markdown.utilities.ts | 55 + projects/ui/markdown/ng-package.json | 5 + projects/ui/markdown/public-api.ts | 4 + projects/ui/menu/menu-item.component.ts | 2 +- projects/ui/menu/menu.stories.ts | 3 +- .../news-ticker-config.provider.ts | 2 +- .../ui/news-ticker/news-ticker.component.ts | 3 +- projects/ui/ng-package.json | 2 +- projects/ui/package.json | 15 +- .../ui/pagination/pagination.component.ts | 5 +- .../ui/person-card/person-card.component.ts | 3 +- projects/ui/popover/popover.stories.ts | 2 +- projects/ui/price/price.component.html | 21 +- .../pricing-card/pricing-card.component.html | 12 +- .../pricing-card.component.spec.ts | 15 +- .../ui/pricing-card/pricing-card.component.ts | 7 +- projects/ui/rating/rating.component.ts | 2 +- projects/ui/result/result-config.provider.ts | 5 +- projects/ui/result/result.component.spec.ts | 2 +- projects/ui/result/result.stories.ts | 2 +- .../ui/rich-text/rich-text.component.html | 9 +- .../ui/rich-text/rich-text.component.spec.ts | 18 + projects/ui/rich-text/rich-text.component.ts | 16 +- .../search-toolbar/filter-button.component.ts | 2 +- .../spam-protection.component.spec.ts | 3 + .../spam-protection.component.ts | 8 + .../ui/stepper/stepper-marker.component.ts | 2 +- projects/ui/steps/public-api.ts | 1 + projects/ui/steps/step-media.component.html | 1 + projects/ui/steps/step-media.component.ts | 34 + projects/ui/steps/step.component.html | 10 +- projects/ui/steps/step.component.ts | 38 +- projects/ui/steps/steps.component.spec.ts | 31 + projects/ui/steps/steps.stories.ts | 22 +- projects/ui/table/table-footer.component.ts | 2 +- .../ui/table/table-header-cell.component.ts | 5 +- projects/ui/table/table.component.spec.ts | 3 +- .../ui/testimonial/testimonial.component.ts | 2 +- .../theme-menu-items.component.ts | 2 +- .../theme-switcher-config.provider.ts | 4 +- projects/ui/theme.css | 27 + scripts/translations.ts | 250 ++++ tests/board.spec.ts | 65 + tests/bump-version.spec.ts | 7 + tests/entry-points.spec.ts | 2 +- tests/global-setup.ts | 28 +- tests/styling.spec.ts | 20 + tests/translations.spec.ts | 142 ++ tsconfig.json | 56 + 961 files changed, 58473 insertions(+), 944 deletions(-) create mode 100644 projects/ngx-approval-requests/CHANGELOG.md create mode 100644 projects/ngx-approval-requests/LICENSE create mode 100644 projects/ngx-approval-requests/README.md create mode 100644 projects/ngx-approval-requests/api/approval-request.service.spec.ts create mode 100644 projects/ngx-approval-requests/api/approval-request.service.ts create mode 100644 projects/ngx-approval-requests/api/approval-requests-config-changes.model.ts create mode 100644 projects/ngx-approval-requests/api/approval-requests-config.model.ts create mode 100644 projects/ngx-approval-requests/api/approval-requests-config.provider.ts create mode 100644 projects/ngx-approval-requests/api/approval-requests-labels.model.ts create mode 100644 projects/ngx-approval-requests/api/approval-requests-paths.model.ts create mode 100644 projects/ngx-approval-requests/api/approval-requests-query.model.ts create mode 100644 projects/ngx-approval-requests/api/ng-package.json create mode 100644 projects/ngx-approval-requests/api/public-api.ts create mode 100644 projects/ngx-approval-requests/approval-request/approval-request-changes.component.html create mode 100644 projects/ngx-approval-requests/approval-request/approval-request-changes.component.ts create mode 100644 projects/ngx-approval-requests/approval-request/approval-request-row-view.model.ts create mode 100644 projects/ngx-approval-requests/approval-request/approval-request-view.model.ts create mode 100644 projects/ngx-approval-requests/approval-request/approval-request.component.html create mode 100644 projects/ngx-approval-requests/approval-request/approval-request.component.spec.ts create mode 100644 projects/ngx-approval-requests/approval-request/approval-request.component.ts create mode 100644 projects/ngx-approval-requests/approval-request/approval-request.stories.ts create mode 100644 projects/ngx-approval-requests/approval-request/ng-package.json create mode 100644 projects/ngx-approval-requests/approval-request/public-api.ts create mode 100644 projects/ngx-approval-requests/approval-requests/approval-request-list-item.model.ts create mode 100644 projects/ngx-approval-requests/approval-requests/approval-requests.component.html create mode 100644 projects/ngx-approval-requests/approval-requests/approval-requests.component.spec.ts create mode 100644 projects/ngx-approval-requests/approval-requests/approval-requests.component.ts create mode 100644 projects/ngx-approval-requests/approval-requests/approval-requests.stories.ts create mode 100644 projects/ngx-approval-requests/approval-requests/ng-package.json create mode 100644 projects/ngx-approval-requests/approval-requests/public-api.ts create mode 100644 projects/ngx-approval-requests/locale/messages.de.xlf create mode 100644 projects/ngx-approval-requests/ng-package.json create mode 100644 projects/ngx-approval-requests/package.json create mode 100644 projects/ngx-approval-requests/src/public-api.ts create mode 100644 projects/ngx-approval-requests/tailwind.css create mode 100644 projects/ngx-approval-requests/tsconfig.lib.json create mode 100644 projects/ngx-approval-requests/tsconfig.lib.prod.json create mode 100644 projects/ngx-approval-requests/tsconfig.spec.json create mode 100644 projects/ngx-auth/CHANGELOG.md create mode 100644 projects/ngx-auth/locale/messages.de.xlf create mode 100644 projects/ngx-auth/login-link/login-link-config-changes.model.ts create mode 100644 projects/ngx-auth/login-link/login-link-config.model.ts create mode 100644 projects/ngx-auth/login-link/login-link-config.provider.ts create mode 100644 projects/ngx-auth/login-link/login-link.component.html create mode 100644 projects/ngx-auth/login-link/login-link.component.spec.ts create mode 100644 projects/ngx-auth/login-link/login-link.component.ts create mode 100644 projects/ngx-auth/login-link/login-link.stories.ts create mode 100644 projects/ngx-auth/login-link/ng-package.json create mode 100644 projects/ngx-auth/login-link/public-api.ts create mode 100644 projects/ngx-auth/login/pending-login.model.ts create mode 100644 projects/ngx-auth/service-accounts/ng-package.json create mode 100644 projects/ngx-auth/service-accounts/public-api.ts create mode 100644 projects/ngx-auth/service-accounts/service-accounts-config-changes.model.ts create mode 100644 projects/ngx-auth/service-accounts/service-accounts-config.model.ts create mode 100644 projects/ngx-auth/service-accounts/service-accounts-config.provider.ts create mode 100644 projects/ngx-auth/service-accounts/service-accounts-labels.model.ts create mode 100644 projects/ngx-auth/service-accounts/service-accounts.component.html create mode 100644 projects/ngx-auth/service-accounts/service-accounts.component.spec.ts create mode 100644 projects/ngx-auth/service-accounts/service-accounts.component.ts create mode 100644 projects/ngx-auth/service-accounts/service-accounts.service.ts create mode 100644 projects/ngx-auth/service-accounts/service-accounts.stories.ts create mode 100644 projects/ngx-backup/CHANGELOG.md create mode 100644 projects/ngx-backup/LICENSE create mode 100644 projects/ngx-backup/README.md create mode 100644 projects/ngx-backup/api/backup-config-changes.model.ts create mode 100644 projects/ngx-backup/api/backup-config.model.ts create mode 100644 projects/ngx-backup/api/backup-config.provider.ts create mode 100644 projects/ngx-backup/api/backup-labels-changes.model.ts create mode 100644 projects/ngx-backup/api/backup-labels.model.ts create mode 100644 projects/ngx-backup/api/backup-transports.service.spec.ts create mode 100644 projects/ngx-backup/api/backup-transports.service.ts create mode 100644 projects/ngx-backup/api/ng-package.json create mode 100644 projects/ngx-backup/api/public-api.ts create mode 100644 projects/ngx-backup/api/sftp-login.type.ts create mode 100644 projects/ngx-backup/api/tenant-transports-labels.model.ts create mode 100644 projects/ngx-backup/fixtures/backup-story.utilities.ts create mode 100644 projects/ngx-backup/fixtures/backup-testing.utilities.ts create mode 100644 projects/ngx-backup/fixtures/backup.fixtures.ts create mode 100644 projects/ngx-backup/fixtures/fake-backup-transports-backend-options.model.ts create mode 100644 projects/ngx-backup/fixtures/fake-backup-transports-backend.model.ts create mode 100644 projects/ngx-backup/locale/messages.de.xlf create mode 100644 projects/ngx-backup/ng-package.json create mode 100644 projects/ngx-backup/package.json create mode 100644 projects/ngx-backup/src/public-api.ts create mode 100644 projects/ngx-backup/tailwind.css create mode 100644 projects/ngx-backup/tenant-transports/ng-package.json create mode 100644 projects/ngx-backup/tenant-transports/public-api.ts create mode 100644 projects/ngx-backup/tenant-transports/tenant-transports.component.html create mode 100644 projects/ngx-backup/tenant-transports/tenant-transports.component.spec.ts create mode 100644 projects/ngx-backup/tenant-transports/tenant-transports.component.ts create mode 100644 projects/ngx-backup/tenant-transports/tenant-transports.stories.ts create mode 100644 projects/ngx-backup/test-setup.ts create mode 100644 projects/ngx-backup/tsconfig.lib.json create mode 100644 projects/ngx-backup/tsconfig.lib.prod.json create mode 100644 projects/ngx-backup/tsconfig.spec.json create mode 100644 projects/ngx-bank/CHANGELOG.md create mode 100644 projects/ngx-bank/LICENSE create mode 100644 projects/ngx-bank/README.md create mode 100644 projects/ngx-bank/api/bank-accounts-labels.model.ts create mode 100644 projects/ngx-bank/api/bank-amount.utilities.spec.ts create mode 100644 projects/ngx-bank/api/bank-amount.utilities.ts create mode 100644 projects/ngx-bank/api/bank-common-labels.model.ts create mode 100644 projects/ngx-bank/api/bank-config-changes.model.ts create mode 100644 projects/ngx-bank/api/bank-config.model.ts create mode 100644 projects/ngx-bank/api/bank-config.provider.ts create mode 100644 projects/ngx-bank/api/bank-day.utilities.ts create mode 100644 projects/ngx-bank/api/bank-iban.utilities.spec.ts create mode 100644 projects/ngx-bank/api/bank-iban.utilities.ts create mode 100644 projects/ngx-bank/api/bank-json.utilities.ts create mode 100644 projects/ngx-bank/api/bank-labels-changes.model.ts create mode 100644 projects/ngx-bank/api/bank-labels.model.ts create mode 100644 projects/ngx-bank/api/bank-match-target-option.model.ts create mode 100644 projects/ngx-bank/api/bank-match.utilities.spec.ts create mode 100644 projects/ngx-bank/api/bank-match.utilities.ts create mode 100644 projects/ngx-bank/api/bank-matching-labels.model.ts create mode 100644 projects/ngx-bank/api/bank-paths.model.ts create mode 100644 projects/ngx-bank/api/bank-statement-upload-labels.model.ts create mode 100644 projects/ngx-bank/api/bank-statements-labels.model.ts create mode 100644 projects/ngx-bank/api/bank-statements-query.model.ts create mode 100644 projects/ngx-bank/api/bank-transactions-labels.model.ts create mode 100644 projects/ngx-bank/api/bank-view.directive.ts create mode 100644 projects/ngx-bank/api/bank.service.spec.ts create mode 100644 projects/ngx-bank/api/bank.service.ts create mode 100644 projects/ngx-bank/api/ng-package.json create mode 100644 projects/ngx-bank/api/public-api.ts create mode 100644 projects/ngx-bank/bank-accounts/bank-accounts.component.html create mode 100644 projects/ngx-bank/bank-accounts/bank-accounts.component.spec.ts create mode 100644 projects/ngx-bank/bank-accounts/bank-accounts.component.ts create mode 100644 projects/ngx-bank/bank-accounts/bank-accounts.stories.ts create mode 100644 projects/ngx-bank/bank-accounts/ng-package.json create mode 100644 projects/ngx-bank/bank-accounts/public-api.ts create mode 100644 projects/ngx-bank/bank-matching/bank-matching.component.html create mode 100644 projects/ngx-bank/bank-matching/bank-matching.component.spec.ts create mode 100644 projects/ngx-bank/bank-matching/bank-matching.component.ts create mode 100644 projects/ngx-bank/bank-matching/bank-matching.stories.ts create mode 100644 projects/ngx-bank/bank-matching/manual-match.component.html create mode 100644 projects/ngx-bank/bank-matching/manual-match.component.ts create mode 100644 projects/ngx-bank/bank-matching/match-suggestion-view.model.ts create mode 100644 projects/ngx-bank/bank-matching/match-suggestion.component.html create mode 100644 projects/ngx-bank/bank-matching/match-suggestion.component.ts create mode 100644 projects/ngx-bank/bank-matching/ng-package.json create mode 100644 projects/ngx-bank/bank-matching/public-api.ts create mode 100644 projects/ngx-bank/bank-statements/bank-statements.component.html create mode 100644 projects/ngx-bank/bank-statements/bank-statements.component.spec.ts create mode 100644 projects/ngx-bank/bank-statements/bank-statements.component.ts create mode 100644 projects/ngx-bank/bank-statements/bank-statements.stories.ts create mode 100644 projects/ngx-bank/bank-statements/ng-package.json create mode 100644 projects/ngx-bank/bank-statements/public-api.ts create mode 100644 projects/ngx-bank/bank-statements/statement-row-view.model.ts create mode 100644 projects/ngx-bank/bank-statements/statement-transaction-row-view.model.ts create mode 100644 projects/ngx-bank/bank-transactions/bank-transactions.component.html create mode 100644 projects/ngx-bank/bank-transactions/bank-transactions.component.spec.ts create mode 100644 projects/ngx-bank/bank-transactions/bank-transactions.component.ts create mode 100644 projects/ngx-bank/bank-transactions/bank-transactions.stories.ts create mode 100644 projects/ngx-bank/bank-transactions/ng-package.json create mode 100644 projects/ngx-bank/bank-transactions/public-api.ts create mode 100644 projects/ngx-bank/bank-transactions/transaction-details.component.html create mode 100644 projects/ngx-bank/bank-transactions/transaction-details.component.ts create mode 100644 projects/ngx-bank/bank-transactions/transaction-match-status.type.ts create mode 100644 projects/ngx-bank/bank-transactions/transaction-match-view.model.ts create mode 100644 projects/ngx-bank/bank-transactions/transaction-row-view.model.ts create mode 100644 projects/ngx-bank/bank-transactions/transaction-status-filter.type.ts create mode 100644 projects/ngx-bank/fixtures/bank-backend.utilities.ts create mode 100644 projects/ngx-bank/fixtures/bank-story.utilities.ts create mode 100644 projects/ngx-bank/fixtures/bank-testing.utilities.ts create mode 100644 projects/ngx-bank/fixtures/bank.fixtures.ts create mode 100644 projects/ngx-bank/locale/messages.de.xlf create mode 100644 projects/ngx-bank/ng-package.json create mode 100644 projects/ngx-bank/package.json create mode 100644 projects/ngx-bank/src/public-api.ts create mode 100644 projects/ngx-bank/statement-upload/imported-statement-row-view.model.ts create mode 100644 projects/ngx-bank/statement-upload/ng-package.json create mode 100644 projects/ngx-bank/statement-upload/public-api.ts create mode 100644 projects/ngx-bank/statement-upload/statement-upload.component.html create mode 100644 projects/ngx-bank/statement-upload/statement-upload.component.spec.ts create mode 100644 projects/ngx-bank/statement-upload/statement-upload.component.ts create mode 100644 projects/ngx-bank/statement-upload/statement-upload.stories.ts create mode 100644 projects/ngx-bank/tailwind.css create mode 100644 projects/ngx-bank/test-setup.ts create mode 100644 projects/ngx-bank/tsconfig.lib.json create mode 100644 projects/ngx-bank/tsconfig.lib.prod.json create mode 100644 projects/ngx-bank/tsconfig.spec.json create mode 100644 projects/ngx-bookkeeping/CHANGELOG.md create mode 100644 projects/ngx-bookkeeping/LICENSE create mode 100644 projects/ngx-bookkeeping/README.md create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-amount.utilities.spec.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-amount.utilities.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-common-labels.model.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-config-changes.model.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-config.model.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-config.provider.spec.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-config.provider.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-day.utilities.spec.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-day.utilities.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-entry-form-labels.model.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-file.model.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-file.utilities.spec.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-file.utilities.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-fiscal-year.utilities.spec.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-fiscal-year.utilities.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-fiscal-years-labels.model.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-journal-labels.model.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-json.utilities.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-labels-changes.model.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-labels.model.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-ledger-labels.model.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-paths.model.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-statement-labels.model.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-trial-balance-labels.model.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping-view.directive.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping.service.spec.ts create mode 100644 projects/ngx-bookkeeping/api/bookkeeping.service.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz-account-mappings-labels.model.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz-certificate-labels.model.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz-common-labels.model.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz-config-changes.model.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz-config.model.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz-config.provider.spec.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz-config.provider.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz-correction-status.type.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz-filing-labels.model.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz-labels-changes.model.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz-labels.model.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz-paths.model.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz-preparation-labels.model.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz-records-labels.model.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz-review-labels.model.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz.service.spec.ts create mode 100644 projects/ngx-bookkeeping/api/e-bilanz.service.ts create mode 100644 projects/ngx-bookkeeping/api/fiscal-year-filing-resolver.model.ts create mode 100644 projects/ngx-bookkeeping/api/fiscal-year-filing-resolver.provider.ts create mode 100644 projects/ngx-bookkeeping/api/ng-package.json create mode 100644 projects/ngx-bookkeeping/api/public-api.ts create mode 100644 projects/ngx-bookkeeping/balance-sheet/balance-sheet.component.html create mode 100644 projects/ngx-bookkeeping/balance-sheet/balance-sheet.component.spec.ts create mode 100644 projects/ngx-bookkeeping/balance-sheet/balance-sheet.component.ts create mode 100644 projects/ngx-bookkeeping/balance-sheet/balance-sheet.stories.ts create mode 100644 projects/ngx-bookkeeping/balance-sheet/ng-package.json create mode 100644 projects/ngx-bookkeeping/balance-sheet/public-api.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-account-mappings.component.html create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-account-mappings.component.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-account-view.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-action-view.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-certificate.component.html create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-certificate.component.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-content-tab.type.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-content.component.html create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-content.component.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-exporter-view.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-figure-row-view.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-figure-view.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-figures.type.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-filing-view.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-filing.component.html create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-filing.component.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-filings.component.html create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-filings.component.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-finding-target.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-finding-view.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-findings.component.html create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-findings.component.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-fixed-asset-value-view.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-fixed-asset-view.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-manual-filing-dialog-data.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-manual-filing-dialog.component.html create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-manual-filing-dialog.component.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-mapping-view.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-outcome.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-phase.type.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-position-view.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-preparation.component.html create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-preparation.component.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-statement-tab-view.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-statement-view.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-tab.type.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-test.component.html create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-test.component.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-transmission.component.html create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-transmission.component.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-unmapped-account-view.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-unsettled-view.model.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz-view.utilities.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz.component.html create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz.component.spec.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz.component.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/e-bilanz.stories.ts create mode 100644 projects/ngx-bookkeeping/e-bilanz/ng-package.json create mode 100644 projects/ngx-bookkeeping/e-bilanz/public-api.ts create mode 100644 projects/ngx-bookkeeping/fiscal-years/closing-proposal-line-view.model.ts create mode 100644 projects/ngx-bookkeeping/fiscal-years/closing-proposal-view.model.ts create mode 100644 projects/ngx-bookkeeping/fiscal-years/closing-proposal.component.html create mode 100644 projects/ngx-bookkeeping/fiscal-years/closing-proposal.component.ts create mode 100644 projects/ngx-bookkeeping/fiscal-years/fiscal-year-closing.component.html create mode 100644 projects/ngx-bookkeeping/fiscal-years/fiscal-year-closing.component.ts create mode 100644 projects/ngx-bookkeeping/fiscal-years/fiscal-year-details.component.html create mode 100644 projects/ngx-bookkeeping/fiscal-years/fiscal-year-details.component.ts create mode 100644 projects/ngx-bookkeeping/fiscal-years/fiscal-year-export.component.html create mode 100644 projects/ngx-bookkeeping/fiscal-years/fiscal-year-export.component.ts create mode 100644 projects/ngx-bookkeeping/fiscal-years/fiscal-year-reopening-dialog-data.model.ts create mode 100644 projects/ngx-bookkeeping/fiscal-years/fiscal-year-reopening-dialog.component.html create mode 100644 projects/ngx-bookkeeping/fiscal-years/fiscal-year-reopening-dialog.component.spec.ts create mode 100644 projects/ngx-bookkeeping/fiscal-years/fiscal-year-reopening-dialog.component.ts create mode 100644 projects/ngx-bookkeeping/fiscal-years/fiscal-year-row-view.model.ts create mode 100644 projects/ngx-bookkeeping/fiscal-years/fiscal-years.component.html create mode 100644 projects/ngx-bookkeeping/fiscal-years/fiscal-years.component.spec.ts create mode 100644 projects/ngx-bookkeeping/fiscal-years/fiscal-years.component.ts create mode 100644 projects/ngx-bookkeeping/fiscal-years/fiscal-years.stories.ts create mode 100644 projects/ngx-bookkeeping/fiscal-years/ng-package.json create mode 100644 projects/ngx-bookkeeping/fiscal-years/public-api.ts create mode 100644 projects/ngx-bookkeeping/fixtures/bookkeeping-story.utilities.ts create mode 100644 projects/ngx-bookkeeping/fixtures/bookkeeping-testing.utilities.ts create mode 100644 projects/ngx-bookkeeping/fixtures/bookkeeping.fixtures.ts create mode 100644 projects/ngx-bookkeeping/fixtures/e-bilanz.fixtures.ts create mode 100644 projects/ngx-bookkeeping/fixtures/fake-e-bilanz-backend-options.model.ts create mode 100644 projects/ngx-bookkeeping/fixtures/fake-e-bilanz-backend.model.ts create mode 100644 projects/ngx-bookkeeping/income-statement/income-statement.component.html create mode 100644 projects/ngx-bookkeeping/income-statement/income-statement.component.spec.ts create mode 100644 projects/ngx-bookkeeping/income-statement/income-statement.component.ts create mode 100644 projects/ngx-bookkeeping/income-statement/income-statement.stories.ts create mode 100644 projects/ngx-bookkeeping/income-statement/ng-package.json create mode 100644 projects/ngx-bookkeeping/income-statement/public-api.ts create mode 100644 projects/ngx-bookkeeping/journal-entry-form/journal-entry-form-line-view.model.ts create mode 100644 projects/ngx-bookkeeping/journal-entry-form/journal-entry-form-line.model.ts create mode 100644 projects/ngx-bookkeeping/journal-entry-form/journal-entry-form.component.html create mode 100644 projects/ngx-bookkeeping/journal-entry-form/journal-entry-form.component.spec.ts create mode 100644 projects/ngx-bookkeeping/journal-entry-form/journal-entry-form.component.ts create mode 100644 projects/ngx-bookkeeping/journal-entry-form/journal-entry-form.stories.ts create mode 100644 projects/ngx-bookkeeping/journal-entry-form/ng-package.json create mode 100644 projects/ngx-bookkeeping/journal-entry-form/public-api.ts create mode 100644 projects/ngx-bookkeeping/journal/journal-entry-reversal-dialog-data.model.ts create mode 100644 projects/ngx-bookkeeping/journal/journal-entry-reversal-dialog.component.html create mode 100644 projects/ngx-bookkeeping/journal/journal-entry-reversal-dialog.component.ts create mode 100644 projects/ngx-bookkeeping/journal/journal-entry-view.model.ts create mode 100644 projects/ngx-bookkeeping/journal/journal-entry.component.html create mode 100644 projects/ngx-bookkeeping/journal/journal-entry.component.ts create mode 100644 projects/ngx-bookkeeping/journal/journal-line-view.model.ts create mode 100644 projects/ngx-bookkeeping/journal/journal.component.html create mode 100644 projects/ngx-bookkeeping/journal/journal.component.spec.ts create mode 100644 projects/ngx-bookkeeping/journal/journal.component.ts create mode 100644 projects/ngx-bookkeeping/journal/journal.stories.ts create mode 100644 projects/ngx-bookkeeping/journal/ng-package.json create mode 100644 projects/ngx-bookkeeping/journal/public-api.ts create mode 100644 projects/ngx-bookkeeping/ledger/ledger-balance-view.model.ts create mode 100644 projects/ngx-bookkeeping/ledger/ledger-balance.component.html create mode 100644 projects/ngx-bookkeeping/ledger/ledger-balance.component.ts create mode 100644 projects/ngx-bookkeeping/ledger/ledger-line-view.model.ts create mode 100644 projects/ngx-bookkeeping/ledger/ledger-table.component.html create mode 100644 projects/ngx-bookkeeping/ledger/ledger-table.component.ts create mode 100644 projects/ngx-bookkeeping/ledger/ledger-view.model.ts create mode 100644 projects/ngx-bookkeeping/ledger/ledger.component.html create mode 100644 projects/ngx-bookkeeping/ledger/ledger.component.spec.ts create mode 100644 projects/ngx-bookkeeping/ledger/ledger.component.ts create mode 100644 projects/ngx-bookkeeping/ledger/ledger.stories.ts create mode 100644 projects/ngx-bookkeeping/ledger/ng-package.json create mode 100644 projects/ngx-bookkeeping/ledger/public-api.ts create mode 100644 projects/ngx-bookkeeping/locale/messages.de.xlf create mode 100644 projects/ngx-bookkeeping/ng-package.json create mode 100644 projects/ngx-bookkeeping/package.json create mode 100644 projects/ngx-bookkeeping/src/public-api.ts create mode 100644 projects/ngx-bookkeeping/statement/ng-package.json create mode 100644 projects/ngx-bookkeeping/statement/public-api.ts create mode 100644 projects/ngx-bookkeeping/statement/statement-position-view.model.ts create mode 100644 projects/ngx-bookkeeping/statement/statement-table.component.html create mode 100644 projects/ngx-bookkeeping/statement/statement-table.component.ts create mode 100644 projects/ngx-bookkeeping/statement/statement-view.model.ts create mode 100644 projects/ngx-bookkeeping/statement/statement.component.html create mode 100644 projects/ngx-bookkeeping/statement/statement.component.ts create mode 100644 projects/ngx-bookkeeping/tailwind.css create mode 100644 projects/ngx-bookkeeping/test-setup.ts create mode 100644 projects/ngx-bookkeeping/trial-balance/ng-package.json create mode 100644 projects/ngx-bookkeeping/trial-balance/public-api.ts create mode 100644 projects/ngx-bookkeeping/trial-balance/trial-balance-row-view.model.ts create mode 100644 projects/ngx-bookkeeping/trial-balance/trial-balance-view.model.ts create mode 100644 projects/ngx-bookkeeping/trial-balance/trial-balance.component.html create mode 100644 projects/ngx-bookkeeping/trial-balance/trial-balance.component.spec.ts create mode 100644 projects/ngx-bookkeeping/trial-balance/trial-balance.component.ts create mode 100644 projects/ngx-bookkeeping/trial-balance/trial-balance.stories.ts create mode 100644 projects/ngx-bookkeeping/tsconfig.lib.json create mode 100644 projects/ngx-bookkeeping/tsconfig.lib.prod.json create mode 100644 projects/ngx-bookkeeping/tsconfig.spec.json create mode 100644 projects/ngx-change-sets/CHANGELOG.md delete mode 100644 projects/ngx-change-sets/change-sets/change-value.utilities.ts delete mode 100644 projects/ngx-change-sets/change-sets/changes-table.component.ts rename projects/ngx-change-sets/{change-sets => changes}/change-value.utilities.spec.ts (81%) create mode 100644 projects/ngx-change-sets/changes/change-value.utilities.ts rename projects/ngx-change-sets/{change-sets => changes}/change-view.model.ts (85%) create mode 100644 projects/ngx-change-sets/changes/changes-config-changes.model.ts create mode 100644 projects/ngx-change-sets/changes/changes-config.model.ts create mode 100644 projects/ngx-change-sets/changes/changes-config.provider.ts rename projects/ngx-change-sets/{change-sets/changes-table.component.html => changes/changes.component.html} (96%) create mode 100644 projects/ngx-change-sets/changes/changes.component.spec.ts create mode 100644 projects/ngx-change-sets/changes/changes.component.ts create mode 100644 projects/ngx-change-sets/changes/changes.stories.ts create mode 100644 projects/ngx-change-sets/changes/ng-package.json create mode 100644 projects/ngx-change-sets/changes/public-api.ts create mode 100644 projects/ngx-change-sets/changes/value-change.model.ts create mode 100644 projects/ngx-change-sets/entity-field/change-sets-field-config.model.ts create mode 100644 projects/ngx-change-sets/entity-field/change-sets-field-config.provider.ts create mode 100644 projects/ngx-change-sets/entity-field/change-sets-field-data.model.ts create mode 100644 projects/ngx-change-sets/entity-field/change-sets-field.component.html create mode 100644 projects/ngx-change-sets/entity-field/change-sets-field.component.spec.ts create mode 100644 projects/ngx-change-sets/entity-field/change-sets-field.component.ts create mode 100644 projects/ngx-change-sets/entity-field/change-sets-field.stories.ts create mode 100644 projects/ngx-change-sets/entity-field/ng-package.json create mode 100644 projects/ngx-change-sets/entity-field/public-api.ts create mode 100644 projects/ngx-change-sets/locale/messages.de.xlf create mode 100644 projects/ngx-ecommerce/CHANGELOG.md create mode 100644 projects/ngx-ecommerce/locale/messages.de.xlf create mode 100644 projects/ngx-entity/CHANGELOG.md create mode 100644 projects/ngx-entity/entity/enum-labels.type.ts create mode 100644 projects/ngx-entity/field-cards/entity-cards-field.component.html create mode 100644 projects/ngx-entity/field-cards/entity-cards-field.component.spec.ts create mode 100644 projects/ngx-entity/field-cards/entity-cards-field.component.ts create mode 100644 projects/ngx-entity/field-cards/entity-cards-field.stories.html create mode 100644 projects/ngx-entity/field-cards/entity-cards-field.stories.ts create mode 100644 projects/ngx-entity/field-cards/ng-package.json create mode 100644 projects/ngx-entity/field-cards/public-api.ts create mode 100644 projects/ngx-entity/locale/messages.de.xlf create mode 100644 projects/ngx-error-handling/CHANGELOG.md create mode 100644 projects/ngx-error-handling/locale/messages.de.xlf create mode 100644 projects/ngx-navigation/CHANGELOG.md create mode 100644 projects/ngx-navigation/locale/messages.de.xlf create mode 100644 projects/ngx-navigation/navigation/nav-row-width.type.ts create mode 100644 projects/ngx-persistence-logger/CHANGELOG.md create mode 100644 projects/ngx-persistence-logger/locale/messages.de.xlf create mode 100644 projects/ngx-projects/CHANGELOG.md create mode 100644 projects/ngx-projects/LICENSE create mode 100644 projects/ngx-projects/README.md create mode 100644 projects/ngx-projects/api/ng-package.json create mode 100644 projects/ngx-projects/api/project-board-labels.model.ts create mode 100644 projects/ngx-projects/api/project-board.service.spec.ts create mode 100644 projects/ngx-projects/api/project-board.service.ts create mode 100644 projects/ngx-projects/api/project-board.utilities.spec.ts create mode 100644 projects/ngx-projects/api/project-board.utilities.ts create mode 100644 projects/ngx-projects/api/project-calendar-labels.model.ts create mode 100644 projects/ngx-projects/api/project-day.utilities.spec.ts create mode 100644 projects/ngx-projects/api/project-day.utilities.ts create mode 100644 projects/ngx-projects/api/project-label-color.utilities.spec.ts create mode 100644 projects/ngx-projects/api/project-label-color.utilities.ts create mode 100644 projects/ngx-projects/api/project-role.utilities.spec.ts create mode 100644 projects/ngx-projects/api/project-role.utilities.ts create mode 100644 projects/ngx-projects/api/project-sharing-labels.model.ts create mode 100644 projects/ngx-projects/api/project-task-labels.model.ts create mode 100644 projects/ngx-projects/api/projects-common-labels.model.ts create mode 100644 projects/ngx-projects/api/projects-config-changes.model.ts create mode 100644 projects/ngx-projects/api/projects-config.model.ts create mode 100644 projects/ngx-projects/api/projects-config.provider.ts create mode 100644 projects/ngx-projects/api/projects-labels-changes.model.ts create mode 100644 projects/ngx-projects/api/projects-labels.model.ts create mode 100644 projects/ngx-projects/api/projects-paths.model.ts create mode 100644 projects/ngx-projects/api/projects-tree-labels.model.ts create mode 100644 projects/ngx-projects/api/projects-view.directive.ts create mode 100644 projects/ngx-projects/api/projects.service.spec.ts create mode 100644 projects/ngx-projects/api/projects.service.ts create mode 100644 projects/ngx-projects/api/public-api.ts create mode 100644 projects/ngx-projects/api/recurring-tasks-labels.model.ts create mode 100644 projects/ngx-projects/board/ng-package.json create mode 100644 projects/ngx-projects/board/project-board.component.html create mode 100644 projects/ngx-projects/board/project-board.component.spec.ts create mode 100644 projects/ngx-projects/board/project-board.component.ts create mode 100644 projects/ngx-projects/board/project-board.stories.ts create mode 100644 projects/ngx-projects/board/public-api.ts create mode 100644 projects/ngx-projects/board/task-card-label-view.model.ts create mode 100644 projects/ngx-projects/board/task-card-view.model.ts create mode 100644 projects/ngx-projects/calendar/ng-package.json create mode 100644 projects/ngx-projects/calendar/project-calendar.component.html create mode 100644 projects/ngx-projects/calendar/project-calendar.component.spec.ts create mode 100644 projects/ngx-projects/calendar/project-calendar.component.ts create mode 100644 projects/ngx-projects/calendar/project-calendar.stories.ts create mode 100644 projects/ngx-projects/calendar/public-api.ts create mode 100644 projects/ngx-projects/fixtures/projects-backend.utilities.ts create mode 100644 projects/ngx-projects/fixtures/projects-story.utilities.ts create mode 100644 projects/ngx-projects/fixtures/projects-testing.utilities.ts create mode 100644 projects/ngx-projects/fixtures/projects.fixtures.ts create mode 100644 projects/ngx-projects/locale/messages.de.xlf create mode 100644 projects/ngx-projects/ng-package.json create mode 100644 projects/ngx-projects/package.json create mode 100644 projects/ngx-projects/projects/ng-package.json create mode 100644 projects/ngx-projects/projects/project-node.model.ts create mode 100644 projects/ngx-projects/projects/project-tree.utilities.spec.ts create mode 100644 projects/ngx-projects/projects/project-tree.utilities.ts create mode 100644 projects/ngx-projects/projects/projects.component.html create mode 100644 projects/ngx-projects/projects/projects.component.spec.ts create mode 100644 projects/ngx-projects/projects/projects.component.ts create mode 100644 projects/ngx-projects/projects/projects.stories.ts create mode 100644 projects/ngx-projects/projects/public-api.ts create mode 100644 projects/ngx-projects/recurring-tasks/ng-package.json create mode 100644 projects/ngx-projects/recurring-tasks/public-api.ts create mode 100644 projects/ngx-projects/recurring-tasks/recurring-task-view.model.ts create mode 100644 projects/ngx-projects/recurring-tasks/recurring-task.utilities.spec.ts create mode 100644 projects/ngx-projects/recurring-tasks/recurring-task.utilities.ts create mode 100644 projects/ngx-projects/recurring-tasks/recurring-tasks.component.html create mode 100644 projects/ngx-projects/recurring-tasks/recurring-tasks.component.spec.ts create mode 100644 projects/ngx-projects/recurring-tasks/recurring-tasks.component.ts create mode 100644 projects/ngx-projects/recurring-tasks/recurring-tasks.stories.ts create mode 100644 projects/ngx-projects/sharing/ng-package.json create mode 100644 projects/ngx-projects/sharing/project-share-view.model.ts create mode 100644 projects/ngx-projects/sharing/project-sharing.component.html create mode 100644 projects/ngx-projects/sharing/project-sharing.component.spec.ts create mode 100644 projects/ngx-projects/sharing/project-sharing.component.ts create mode 100644 projects/ngx-projects/sharing/project-sharing.stories.ts create mode 100644 projects/ngx-projects/sharing/public-api.ts create mode 100644 projects/ngx-projects/src/public-api.ts create mode 100644 projects/ngx-projects/tailwind.css create mode 100644 projects/ngx-projects/task/ng-package.json create mode 100644 projects/ngx-projects/task/project-task.component.html create mode 100644 projects/ngx-projects/task/project-task.component.spec.ts create mode 100644 projects/ngx-projects/task/project-task.component.ts create mode 100644 projects/ngx-projects/task/project-task.stories.ts create mode 100644 projects/ngx-projects/task/public-api.ts create mode 100644 projects/ngx-projects/task/task-change-set.service.spec.ts create mode 100644 projects/ngx-projects/task/task-change-set.service.ts create mode 100644 projects/ngx-projects/task/task-comment-view.model.ts create mode 100644 projects/ngx-projects/test-setup.ts create mode 100644 projects/ngx-projects/tsconfig.lib.json create mode 100644 projects/ngx-projects/tsconfig.lib.prod.json create mode 100644 projects/ngx-projects/tsconfig.spec.json create mode 100644 projects/ngx-pwa/CHANGELOG.md create mode 100644 projects/ngx-pwa/locale/messages.de.xlf create mode 100644 projects/ngx-tracking/CHANGELOG.md create mode 100644 projects/ngx-tracking/analytics/analytics-config.model.ts create mode 100644 projects/ngx-tracking/analytics/analytics-config.provider.ts create mode 100644 projects/ngx-tracking/analytics/analytics.provider.ts create mode 100644 projects/ngx-tracking/analytics/analytics.service.spec.ts create mode 100644 projects/ngx-tracking/analytics/analytics.service.ts create mode 100644 projects/ngx-tracking/analytics/ng-package.json create mode 100644 projects/ngx-tracking/analytics/public-api.ts create mode 100644 projects/ngx-tracking/locale/messages.de.xlf create mode 100644 projects/ngx-web-dav/CHANGELOG.md create mode 100644 projects/ngx-web-dav/LICENSE create mode 100644 projects/ngx-web-dav/README.md create mode 100644 projects/ngx-web-dav/api/file-mirror-conflicts-labels.model.ts create mode 100644 projects/ngx-web-dav/api/file-mirror-share-link-labels.model.ts create mode 100644 projects/ngx-web-dav/api/file-mirror.service.spec.ts create mode 100644 projects/ngx-web-dav/api/file-mirror.service.ts create mode 100644 projects/ngx-web-dav/api/ng-package.json create mode 100644 projects/ngx-web-dav/api/public-api.ts create mode 100644 projects/ngx-web-dav/api/web-dav-config-changes.model.ts create mode 100644 projects/ngx-web-dav/api/web-dav-config.model.ts create mode 100644 projects/ngx-web-dav/api/web-dav-config.provider.ts create mode 100644 projects/ngx-web-dav/api/web-dav-connections-labels.model.ts create mode 100644 projects/ngx-web-dav/api/web-dav-connections.service.spec.ts create mode 100644 projects/ngx-web-dav/api/web-dav-connections.service.ts create mode 100644 projects/ngx-web-dav/api/web-dav-labels-changes.model.ts create mode 100644 projects/ngx-web-dav/api/web-dav-labels.model.ts create mode 100644 projects/ngx-web-dav/conflicts/file-mirror-conflicts.component.html create mode 100644 projects/ngx-web-dav/conflicts/file-mirror-conflicts.component.spec.ts create mode 100644 projects/ngx-web-dav/conflicts/file-mirror-conflicts.component.ts create mode 100644 projects/ngx-web-dav/conflicts/file-mirror-conflicts.stories.ts create mode 100644 projects/ngx-web-dav/conflicts/ng-package.json create mode 100644 projects/ngx-web-dav/conflicts/public-api.ts create mode 100644 projects/ngx-web-dav/connections/ng-package.json create mode 100644 projects/ngx-web-dav/connections/public-api.ts create mode 100644 projects/ngx-web-dav/connections/web-dav-connections.component.html create mode 100644 projects/ngx-web-dav/connections/web-dav-connections.component.spec.ts create mode 100644 projects/ngx-web-dav/connections/web-dav-connections.component.ts create mode 100644 projects/ngx-web-dav/connections/web-dav-connections.stories.ts create mode 100644 projects/ngx-web-dav/fixtures/fake-file-mirror-backend-options.model.ts create mode 100644 projects/ngx-web-dav/fixtures/fake-file-mirror-backend.model.ts create mode 100644 projects/ngx-web-dav/fixtures/fake-web-dav-connections-backend-options.model.ts create mode 100644 projects/ngx-web-dav/fixtures/fake-web-dav-connections-backend.model.ts create mode 100644 projects/ngx-web-dav/fixtures/web-dav-story.utilities.ts create mode 100644 projects/ngx-web-dav/fixtures/web-dav-testing.utilities.ts create mode 100644 projects/ngx-web-dav/fixtures/web-dav.fixtures.ts create mode 100644 projects/ngx-web-dav/locale/messages.de.xlf create mode 100644 projects/ngx-web-dav/ng-package.json create mode 100644 projects/ngx-web-dav/package.json create mode 100644 projects/ngx-web-dav/share-link/file-mirror-share-link.component.html create mode 100644 projects/ngx-web-dav/share-link/file-mirror-share-link.component.spec.ts create mode 100644 projects/ngx-web-dav/share-link/file-mirror-share-link.component.ts create mode 100644 projects/ngx-web-dav/share-link/file-mirror-share-link.stories.ts create mode 100644 projects/ngx-web-dav/share-link/ng-package.json create mode 100644 projects/ngx-web-dav/share-link/public-api.ts create mode 100644 projects/ngx-web-dav/src/public-api.ts create mode 100644 projects/ngx-web-dav/tailwind.css create mode 100644 projects/ngx-web-dav/test-setup.ts create mode 100644 projects/ngx-web-dav/tsconfig.lib.json create mode 100644 projects/ngx-web-dav/tsconfig.lib.prod.json create mode 100644 projects/ngx-web-dav/tsconfig.spec.json create mode 100644 projects/ngx-websocket/CHANGELOG.md create mode 100644 projects/ngx-websocket/LICENSE create mode 100644 projects/ngx-websocket/README.md create mode 100644 projects/ngx-websocket/ng-package.json create mode 100644 projects/ngx-websocket/package.json create mode 100644 projects/ngx-websocket/src/public-api.ts create mode 100644 projects/ngx-websocket/tsconfig.lib.json create mode 100644 projects/ngx-websocket/tsconfig.lib.prod.json create mode 100644 projects/ngx-websocket/tsconfig.spec.json create mode 100644 projects/ngx-websocket/websocket/ng-package.json create mode 100644 projects/ngx-websocket/websocket/public-api.ts create mode 100644 projects/ngx-websocket/websocket/socket-io-client.function.ts create mode 100644 projects/ngx-websocket/websocket/websocket-answer.error.ts create mode 100644 projects/ngx-websocket/websocket/websocket-client-factory.type.ts create mode 100644 projects/ngx-websocket/websocket/websocket-client-options.model.ts create mode 100644 projects/ngx-websocket/websocket/websocket-client.model.ts create mode 100644 projects/ngx-websocket/websocket/websocket-config.model.ts create mode 100644 projects/ngx-websocket/websocket/websocket-config.provider.ts create mode 100644 projects/ngx-websocket/websocket/websocket-handshake-auth.model.ts create mode 100644 projects/ngx-websocket/websocket/websocket-headers-resolver.type.ts create mode 100644 projects/ngx-websocket/websocket/websocket-listener.type.ts create mode 100644 projects/ngx-websocket/websocket/websocket-message.model.ts create mode 100644 projects/ngx-websocket/websocket/websocket-message.utilities.ts create mode 100644 projects/ngx-websocket/websocket/websocket-replay.model.ts create mode 100644 projects/ngx-websocket/websocket/websocket.service.spec.ts create mode 100644 projects/ngx-websocket/websocket/websocket.service.ts create mode 100644 projects/testing/websocket/fake-websocket-answer.model.ts create mode 100644 projects/testing/websocket/fake-websocket-handshake.model.ts create mode 100644 projects/testing/websocket/fake-websocket-message.model.ts create mode 100644 projects/testing/websocket/fake-websocket.model.ts create mode 100644 projects/testing/websocket/ng-package.json create mode 100644 projects/testing/websocket/public-api.ts create mode 100644 projects/ui/CHANGELOG.md create mode 100644 projects/ui/board/board-card-context.model.ts create mode 100644 projects/ui/board/board-column-context.model.ts create mode 100644 projects/ui/board/board-column.model.ts create mode 100644 projects/ui/board/board-config.model.ts create mode 100644 projects/ui/board/board-config.provider.ts create mode 100644 projects/ui/board/board-move-result.model.ts create mode 100644 projects/ui/board/board-move.model.ts create mode 100644 projects/ui/board/board.component.html create mode 100644 projects/ui/board/board.component.spec.ts create mode 100644 projects/ui/board/board.component.ts create mode 100644 projects/ui/board/board.stories.ts create mode 100644 projects/ui/board/board.utilities.spec.ts create mode 100644 projects/ui/board/board.utilities.ts create mode 100644 projects/ui/board/ng-package.json create mode 100644 projects/ui/board/public-api.ts create mode 100644 projects/ui/card/card-media.component.html create mode 100644 projects/ui/card/card-media.component.ts create mode 100644 projects/ui/count-badge/count-badge-config.model.ts create mode 100644 projects/ui/count-badge/count-badge-config.provider.ts create mode 100644 projects/ui/count-badge/count-badge-placement.type.ts create mode 100644 projects/ui/count-badge/count-badge.component.html create mode 100644 projects/ui/count-badge/count-badge.component.spec.ts create mode 100644 projects/ui/count-badge/count-badge.component.ts create mode 100644 projects/ui/count-badge/count-badge.stories.ts create mode 100644 projects/ui/count-badge/ng-package.json create mode 100644 projects/ui/count-badge/public-api.ts create mode 100644 projects/ui/input-date/input-date.utilities.spec.ts create mode 100644 projects/ui/input/input-date-part.type.ts create mode 100644 projects/ui/locale/messages.de.xlf create mode 100644 projects/ui/markdown/markdown-config.model.ts create mode 100644 projects/ui/markdown/markdown-config.provider.ts create mode 100644 projects/ui/markdown/markdown.component.html create mode 100644 projects/ui/markdown/markdown.component.spec.ts create mode 100644 projects/ui/markdown/markdown.component.ts create mode 100644 projects/ui/markdown/markdown.stories.ts create mode 100644 projects/ui/markdown/markdown.utilities.ts create mode 100644 projects/ui/markdown/ng-package.json create mode 100644 projects/ui/markdown/public-api.ts create mode 100644 projects/ui/steps/step-media.component.html create mode 100644 projects/ui/steps/step-media.component.ts create mode 100644 scripts/translations.ts create mode 100644 tests/board.spec.ts create mode 100644 tests/translations.spec.ts diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml index 0c7e06e..13ad913 100644 --- a/.github/workflows/cd.yml +++ b/.github/workflows/cd.yml @@ -17,7 +17,7 @@ jobs: # every published library, in the order they depend on each other, as tests/global-setup.ts builds them: # a library is published after the ones it names as peers, so it can always be installed. # tests/release-version.spec.ts checks it names every library that isn't private. - LIBRARIES: ui ngx-change-sets ngx-persistence-logger ngx-tracking ngx-pwa ngx-auth ngx-error-handling ngx-navigation ngx-entity ngx-ecommerce + LIBRARIES: ui ngx-persistence-logger ngx-tracking ngx-pwa ngx-auth ngx-error-handling ngx-navigation ngx-entity ngx-change-sets ngx-ecommerce ngx-approval-requests ngx-bookkeeping ngx-bank ngx-websocket ngx-web-dav ngx-backup ngx-projects steps: # the merge itself rather than the branch, which may have moved on by the time this runs - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/CODE_STYLE.md b/CODE_STYLE.md index 33225a9..4cd2752 100644 --- a/CODE_STYLE.md +++ b/CODE_STYLE.md @@ -19,6 +19,7 @@ and the linter disagree, the linter wins and this file is wrong; open an issue. - [Styling](#styling) - [Accessibility](#accessibility) - [Types](#types) +- [Backends](#backends) - [Comments and JSDoc](#comments-and-jsdoc) - [Tests](#tests) @@ -310,6 +311,14 @@ not match what the code takes, which is the thing worth knowing. **Prefer a named type to an inline one**, and declare the type of every non-trivial local. +# Backends + +**A library talks to a backend through models, never through a backend.** Where it sends or reads data, it describes +what it expects with the shared models of `zibri-contract`, which any api can implement. zibri implements them, and a +README may name it as one api that does, but zibri is never a requirement, a dependency or a name: an entry point, a +provider, a service or an option is named for what it does, like `@service-soft/ngx-tracking/analytics`, not for the +backend it was first built with. + # Comments and JSDoc These are two different audiences and the split is strict. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a469f2e..216ec1e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,6 +12,7 @@ All development is done using github. - [Special Notes for bugs](#special-notes-for-bugs) - [Writing code](#writing-code) - [Adding a library](#adding-a-library) + - [Texts and their German translation](#texts-and-their-german-translation) - [Workflow for submitting Code Changes](#workflow-for-submitting-code-changes) - [Releasing](#releasing) - [License](#license) @@ -47,7 +48,15 @@ Every library is published under the `@service-soft` npm organisation. Start wit 7. Add a `tailwind.css` containing `@source "./fesm2022";`, list it under `assets` in `ng-package.json` and export it in `package.json` (`"exports": { ".": { "style": "./tailwind.css" } }`). 8. In `tests/global-setup.ts`, build the library after `ui` is linked and link it into `node_modules` as `@service-soft/`, so the showcase consumes it like an external project. To build it on its own, build and link `ui` first by running `npm run test:workspace` once. Add it to the libraries of `tests/entry-points.spec.ts`, and to `LIBRARIES` in `.github/workflows/cd.yml`, after the libraries it depends on. 9. Add its stories to the one Storybook in `projects/ui/.storybook`: its folder to `stories` in `main.ts`, to `include` and `exclude` in `tsconfig.json`, and as `@source` in `styles.css`. AXE then checks them with all others. -10. Write its documentation in a `README.md` in the library's root. The build copies it into the package, so it is also its page on npm: it has to work on its own, with links to other packages on npm instead of to files in this repository. The root README only gets a row in its packages table that links to it. +10. Write its documentation in a `README.md` in the library's root. The build copies it into the package, so it is also its page on npm: it has to work on its own, with links to other packages on npm instead of to files in this repository. The root README only gets a row in its packages table that links to it. Start its `CHANGELOG.md` with the version of its first release (see [Releasing](#releasing)), and list it under `assets` in `ng-package.json`, so it ships with the package. +11. Once it has [texts](#texts-and-their-german-translation), list `locale/messages.de.xlf` under `assets` in `ng-package.json` and name it in `package.json` (`"translations": { "de": "./locale/messages.de.xlf" }`). + +## Texts and their German translation +Every text a user sees is `$localize` with an id of its own that starts with the name of the library, like `` $localize`:@@ui.table.selectAllLabel:Select all rows of this page` ``. Each library ships the German translation of its texts in `locale/messages.de.xlf`, so apps don't translate them. After adding, changing or removing a text: + +1. Run `npm run translations:update`. It extracts the texts of every library with the extraction of Angular, the one `ng extract-i18n` of an app uses, and updates its file: a new text gets a unit without a target, the unit of a removed text is removed, and every other unit keeps its target. It lists the texts to translate, and those whose English changed, which kept their old target. +2. Write the German `` of each listed text, right after its ``, and review the targets of the changed ones. Use the formal "Sie", the words the other texts use, and keep labels for screen readers short. A placeholder like `` goes into the target as it is in the source, wherever it belongs in German. +3. Run `npm run test:workspace`. `tests/translations.spec.ts` fails while a text has no German target, while a file has a unit of a text the code doesn't have or a source that differs from the code, and while the placeholders of a target don't match its source. # Workflow for submitting Code Changes 1. Create an issue if it not already exists. @@ -63,13 +72,25 @@ Every library is published under the `@service-soft` npm organisation. Start wit 9. Issue that pull request! # Releasing -Every library is released with the same version, and its major is always the major of Angular it is built for, whether a -release has breaking changes or not: `22.x.x` is for Angular 22. A new major of Angular starts the next major, a release -in between only bumps the minor or the patch. - -1. Bump every published library: `npm run release:bump -- `. It sets the version of each library that +Every library is released with the same version, `..`: + +- The major is always the major of Angular it is built for: `22.x.x` is for Angular 22. A new major of Angular starts the + next major, with the minor and the patch at 0. +- The minor counts the releases with a breaking change, in any library: a removed or renamed export, input, config key + or token, a new required peer dependency, a raised minimum version of a peer, or a changed default or behaviour an app + has to adapt to. It sets the patch back to 0. +- The patch counts every other release: new features, new entry points, new libraries and fixes. + +- `zibri-contract` is updated in every library at once, like the release itself: every library that uses it requires + the same range, and so does the root `devDependency`, even a library that needs nothing of the new version. A raised + range is a breaking change of each library whose range it raises. + +1. Add what changed to the `CHANGELOG.md` of each library that changed, under a heading with the new version, like + `## 22.4.0`, in the sections `### Breaking changes`, `### Features` and `### Fixes` that have entries. Each breaking + change says what an app has to do. The changelog ships with the package. +2. Bump every published library: `npm run release:bump -- `. It sets the version of each library that isn't `"private"` (so not `testing`), and the ranges the libraries require each other in to `^`. -2. Merge a pull request with the bump into `release` (a fix for an older major goes into `release-`). The `CD` +3. Merge a pull request with the bump into `release` (a fix for an older major goes into `release-`). The `CD` workflow then runs `npm test`, which builds every library into `dist`, and publishes each one the registry doesn't have at that version yet, in the order they depend on each other (`LIBRARIES` in `.github/workflows/cd.yml`), with provenance and under the npm tag `latest`, `latest-` for an older major or `next` for a prerelease. Then it diff --git a/README.md b/README.md index 0a03aaa..b4454e6 100644 --- a/README.md +++ b/README.md @@ -15,12 +15,19 @@ Each package documents itself in its README, which is also its page on npm. | Package | Does | |---|---| | [@service-soft/ui](./projects/ui/README.md) | The design system every other library builds on: the design tokens, theming, dark mode and the basic components, like buttons, inputs, dialogs and menus | -| [@service-soft/ngx-auth](./projects/ngx-auth/README.md) | Logs in at the auth routes of zibri with tokens or cookies, a second factor and password resets, protects routes by login and permission in a tenant, answers invitations, and has the pages for the login, passwords and invitations | +| [@service-soft/ngx-approval-requests](./projects/ngx-approval-requests/README.md) | Lists the approval requests of an api like zibri's, filtered by status and action, and reviews one: what its action does, who proposed it and why, the values it would change, and approving or rejecting it with a note after confirming, with the outcome or the message of the api | +| [@service-soft/ngx-backup](./projects/ngx-backup/README.md) | The storage a tenant keeps its backups on, at an api like zibri's: a bucket, an SFTP server, or a folder of a WebDAV server or a Nextcloud through the connections of ngx-web-dav, added once the api wrote to it, changed with its write-only secret, and removed after a question that says what happens to the backups on it, with the message of the api when the storage refused the test or backups are still stored on it | +| [@service-soft/ngx-bookkeeping](./projects/ngx-bookkeeping/README.md) | The views of double-entry books kept by an api like zibri's: the journal with reversing an entry, a form that posts only a balanced entry, the ledger, the trial balance, the balance sheet and the income statement with the year before and a pdf each, the fiscal years with their closing, reopening and their export for a tax audit, and preparing, testing and filing the E-Bilanz of a fiscal year, corrections included | +| [@service-soft/ngx-bank](./projects/ngx-bank/README.md) | The views of the bank accounts of an api like zibri's: adding an account with its IBAN checked, uploading a CAMT.053 statement, the statements with their balances, the transactions with what of each is open and reversing a match, and matching a transaction, with the suggestions reviewed as approval requests and a match proposed by hand | +| [@service-soft/ngx-auth](./projects/ngx-auth/README.md) | Logs in at an api with the auth models of zibri-contract, like zibri's, with tokens, cookies or links sent by email, a second factor and password resets, protects routes by login and permission in a tenant, answers invitations, manages service accounts, and has the pages for the login, passwords and invitations | | [@service-soft/ngx-change-sets](./projects/ngx-change-sets/README.md) | Shows the change sets of an entity as its history, like the ones zibri keeps, and lets the user undo them | | [@service-soft/ngx-ecommerce](./projects/ngx-ecommerce/README.md) | Lets the user add extras to a booking or order, like breakfast per day or a second bike, and sums up an order with its discounts, taxes and total, in the currency and language of the app | | [@service-soft/ngx-entity](./projects/ngx-entity/README.md) | Describes the entities of an app with decorators like zibri's and builds their forms from them, on a grid of 12 columns with rows and tabs, reads and writes them at the routes of zibri, and shows them in tables a page at a time, with the filters and orders the server allows, which create, edit and delete them in dialogs or on pages of their own, asking before changes are lost, and offline with ngx-pwa if you like | | [@service-soft/ngx-error-handling](./projects/ngx-error-handling/README.md) | Hands every error nothing caught to several handlers, and shows it in a dialog, with the message of zibri, the problems of the values it refused and the reference of the request | | [@service-soft/ngx-navigation](./projects/ngx-navigation/README.md) | Builds the navigation from rows of elements: a navbar whose elements move into a drawer on smaller screens, a footer, breadcrumbs from the routes, links to the sections of a page and a page for unknown urls, with the routes defined in the elements if you like, and the description, canonical url and structured data of every page for search engines | +| [@service-soft/ngx-projects](./projects/ngx-projects/README.md) | The views of the projects of an api like zibri's: the tree of nested projects, a board whose tasks move by pointer, keyboard or menu and follow the changes of others live, the details of a task with its markdown, sub-tasks, comments and history, sharing a project with a customer, recurring tasks and working calendars, each showing only what the role of the user allows | +| [@service-soft/ngx-websocket](./projects/ngx-websocket/README.md) | Connects to a websocket like zibri's with the login and the tenant of the app, connects again and catches up on what it missed, says when that isn't possible, hears its events and sends messages that wait for their answer | +| [@service-soft/ngx-web-dav](./projects/ngx-web-dav/README.md) | The connections of a tenant to folders of WebDAV servers, like its Nextcloud, at an api like zibri's: adding one once the api reached its folder, changing it and its write-only password, and deleting it, with the message of the api when the server refused the login or something still uses the connection, the files the file mirror couldn't write, to overwrite or stop mirroring, and the share link of a Nextcloud folder, to copy and revoke | | [@service-soft/ngx-persistence-logger](./projects/ngx-persistence-logger/README.md) | Logs to the console and sends the logs to a backend like the logs of zibri, and shows the logs of all applications in a log history with filters and pages | | [@service-soft/ngx-pwa](./projects/ngx-pwa/README.md) | Keeps the changes the user makes offline and syncs them later in the tenant they were made in, keeps what each user loaded to read it offline, says when the user is offline, turns push notifications on and off, and offers to reload once a new version is ready | | [@service-soft/ngx-tracking](./projects/ngx-tracking/README.md) | Asks for consent in a GDPR compliant dialog, at the first interaction if you like, so it doesn't slow down the page, and tracks only what the user allowed: Google Analytics, Google Tag Manager, the Meta Pixel or your own backend, and a funnel to show the results | diff --git a/angular.json b/angular.json index 61d84f9..72a1651 100644 --- a/angular.json +++ b/angular.json @@ -5,6 +5,172 @@ }, "newProjectRoot": "projects", "projects": { + "ngx-projects": { + "architect": { + "build": { + "builder": "@angular/build:ng-packagr", + "configurations": { + "development": { + "tsConfig": "projects/ngx-projects/tsconfig.lib.json" + }, + "production": { + "tsConfig": "projects/ngx-projects/tsconfig.lib.prod.json" + } + }, + "defaultConfiguration": "production" + }, + "test": { + "builder": "@angular/build:unit-test", + "options": { + "buildTarget": "testing:test-polyfills", + "setupFiles": ["projects/ngx-projects/test-setup.ts"], + "tsConfig": "projects/ngx-projects/tsconfig.spec.json" + } + } + }, + "prefix": "ngx", + "projectType": "library", + "root": "projects/ngx-projects", + "sourceRoot": "projects/ngx-projects" + }, + "ngx-websocket": { + "architect": { + "build": { + "builder": "@angular/build:ng-packagr", + "configurations": { + "development": { + "tsConfig": "projects/ngx-websocket/tsconfig.lib.json" + }, + "production": { + "tsConfig": "projects/ngx-websocket/tsconfig.lib.prod.json" + } + }, + "defaultConfiguration": "production" + }, + "test": { + "builder": "@angular/build:unit-test", + "options": { + "buildTarget": "testing:test-polyfills", + "tsConfig": "projects/ngx-websocket/tsconfig.spec.json" + } + } + }, + "prefix": "ngx", + "projectType": "library", + "root": "projects/ngx-websocket", + "sourceRoot": "projects/ngx-websocket" + }, + "ngx-web-dav": { + "architect": { + "build": { + "builder": "@angular/build:ng-packagr", + "configurations": { + "development": { + "tsConfig": "projects/ngx-web-dav/tsconfig.lib.json" + }, + "production": { + "tsConfig": "projects/ngx-web-dav/tsconfig.lib.prod.json" + } + }, + "defaultConfiguration": "production" + }, + "test": { + "builder": "@angular/build:unit-test", + "options": { + "buildTarget": "testing:test-polyfills", + "setupFiles": ["projects/ngx-web-dav/test-setup.ts"], + "tsConfig": "projects/ngx-web-dav/tsconfig.spec.json" + } + } + }, + "prefix": "ngx", + "projectType": "library", + "root": "projects/ngx-web-dav", + "sourceRoot": "projects/ngx-web-dav" + }, + "ngx-backup": { + "architect": { + "build": { + "builder": "@angular/build:ng-packagr", + "configurations": { + "development": { + "tsConfig": "projects/ngx-backup/tsconfig.lib.json" + }, + "production": { + "tsConfig": "projects/ngx-backup/tsconfig.lib.prod.json" + } + }, + "defaultConfiguration": "production" + }, + "test": { + "builder": "@angular/build:unit-test", + "options": { + "buildTarget": "testing:test-polyfills", + "setupFiles": ["projects/ngx-backup/test-setup.ts"], + "tsConfig": "projects/ngx-backup/tsconfig.spec.json" + } + } + }, + "prefix": "ngx", + "projectType": "library", + "root": "projects/ngx-backup", + "sourceRoot": "projects/ngx-backup" + }, + "ngx-approval-requests": { + "architect": { + "build": { + "builder": "@angular/build:ng-packagr", + "configurations": { + "development": { + "tsConfig": "projects/ngx-approval-requests/tsconfig.lib.json" + }, + "production": { + "tsConfig": "projects/ngx-approval-requests/tsconfig.lib.prod.json" + } + }, + "defaultConfiguration": "production" + }, + "test": { + "builder": "@angular/build:unit-test", + "options": { + "buildTarget": "testing:test-polyfills", + "tsConfig": "projects/ngx-approval-requests/tsconfig.spec.json" + } + } + }, + "prefix": "ngx", + "projectType": "library", + "root": "projects/ngx-approval-requests", + "sourceRoot": "projects/ngx-approval-requests" + }, + "ngx-bank": { + "architect": { + "build": { + "builder": "@angular/build:ng-packagr", + "configurations": { + "development": { + "tsConfig": "projects/ngx-bank/tsconfig.lib.json" + }, + "production": { + "tsConfig": "projects/ngx-bank/tsconfig.lib.prod.json" + } + }, + "defaultConfiguration": "production" + }, + "test": { + "builder": "@angular/build:unit-test", + "options": { + "buildTarget": "testing:test-polyfills", + "setupFiles": ["projects/ngx-bank/test-setup.ts"], + "tsConfig": "projects/ngx-bank/tsconfig.spec.json" + } + } + }, + "prefix": "ngx", + "projectType": "library", + "root": "projects/ngx-bank", + "sourceRoot": "projects/ngx-bank" + }, "ngx-auth": { "architect": { "build": { @@ -32,6 +198,34 @@ "root": "projects/ngx-auth", "sourceRoot": "projects/ngx-auth" }, + "ngx-bookkeeping": { + "architect": { + "build": { + "builder": "@angular/build:ng-packagr", + "configurations": { + "development": { + "tsConfig": "projects/ngx-bookkeeping/tsconfig.lib.json" + }, + "production": { + "tsConfig": "projects/ngx-bookkeeping/tsconfig.lib.prod.json" + } + }, + "defaultConfiguration": "production" + }, + "test": { + "builder": "@angular/build:unit-test", + "options": { + "buildTarget": "testing:test-polyfills", + "setupFiles": ["projects/ngx-bookkeeping/test-setup.ts"], + "tsConfig": "projects/ngx-bookkeeping/tsconfig.spec.json" + } + } + }, + "prefix": "ngx", + "projectType": "library", + "root": "projects/ngx-bookkeeping", + "sourceRoot": "projects/ngx-bookkeeping" + }, "ngx-change-sets": { "architect": { "build": { diff --git a/cspell.words.txt b/cspell.words.txt index 234dd75..a6bc33d 100644 --- a/cspell.words.txt +++ b/cspell.words.txt @@ -48,4 +48,13 @@ uppercased llms sitemapindex prerenders -wordmark \ No newline at end of file +wordmark +subgrid +conformances +camt +keyshortcuts +unarchived +commentable +neighbours +propfind +keygen \ No newline at end of file diff --git a/eslint.config.mjs b/eslint.config.mjs index 529a62c..25dc072 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -54,9 +54,22 @@ export default [ { // zibri is a node backend: a type of it would end up in the published declarations, and every consumer would need // zibri to compile. What a library shares with it is in zibri-contract, which zibri checks its models against. + // The index of an icon package of Font Awesome is one module, which a build only splits as a whole: every icon an + // app uses anywhere, on any page, would load with the first page that uses one. Its file per icon is a module of + // its own, which loads with the pages that use it. files: ['projects/**/*.ts', 'tests/**/*.ts'], rules: { - 'no-restricted-imports': ['warn', { paths: [{ name: 'zibri', message: 'Import the shared models from zibri-contract.' }] }] + 'no-restricted-imports': [ + 'warn', { + paths: [ + { name: 'zibri', message: 'Import the shared models from zibri-contract.' }, + ...['solid', 'regular', 'brands'].map(style => ({ + name: `@fortawesome/free-${style}-svg-icons`, + message: `Import each icon from its own file, like @fortawesome/free-${style}-svg-icons/faClock.` + })) + ] + } + ] } }, { @@ -69,15 +82,22 @@ export default [ }, { files: [ + 'projects/ngx-approval-requests/**/*.ts', 'projects/ngx-auth/**/*.ts', + 'projects/ngx-backup/**/*.ts', + 'projects/ngx-bank/**/*.ts', + 'projects/ngx-bookkeeping/**/*.ts', 'projects/ngx-change-sets/**/*.ts', 'projects/ngx-ecommerce/**/*.ts', 'projects/ngx-entity/**/*.ts', 'projects/ngx-error-handling/**/*.ts', 'projects/ngx-navigation/**/*.ts', 'projects/ngx-persistence-logger/**/*.ts', + 'projects/ngx-projects/**/*.ts', 'projects/ngx-tracking/**/*.ts', - 'projects/ngx-pwa/**/*.ts' + 'projects/ngx-pwa/**/*.ts', + 'projects/ngx-web-dav/**/*.ts', + 'projects/ngx-websocket/**/*.ts' ], rules: { 'angular/component-selector': ['warn', { style: 'kebab-case', type: 'element', prefix: 'ngx' }], diff --git a/package-lock.json b/package-lock.json index 0b4471a..e966d3e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -21,6 +21,7 @@ "@angular-devkit/build-angular": "^22.2.5", "@angular/aria": "^22.2.5", "@angular/build": "^22.2.5", + "@angular/cdk": "^22.2.5", "@angular/cli": "^22.2.5", "@angular/compiler-cli": "^22.2.5", "@angular/localize": "^22.2.6", @@ -39,15 +40,17 @@ "eslint": "^9.39.5", "eslint-plugin-better-tailwindcss": "^4.9.1", "jsdom": "^30.0.0", + "marked": "^18.2.0", "ng-packagr": "^22.2.0", "playwright": "^1.64.1", "postcss": "^8.5.30", + "socket.io-client": "^4.8.4", "storybook": "^10.6.2", "tailwindcss": "^4.3.3", "typescript": "~6.0.2", "uqr": "^0.1.3", "vitest": "^5.0.0", - "zibri-contract": "^3.2.0" + "zibri-contract": "^3.3.0" } }, "node_modules/@adobe/css-tools": { @@ -648,7 +651,6 @@ "integrity": "sha512-S9gJRQVGchy38Y0aYnEfKjFYY34c9sKbbLvwbef6wzGnYvesmsTqskQRbysWvg+F7mZuHuK0uZEDCvEfOZxYbw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "parse5": "^8.0.0", "tslib": "^2.3.0" @@ -8318,6 +8320,13 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/@socket.io/component-emitter": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz", + "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==", + "dev": true, + "license": "MIT" + }, "node_modules/@sonarsource/analyzer-commons-configurations": { "version": "2.31.0-5284", "resolved": "https://registry.npmjs.org/@sonarsource/analyzer-commons-configurations/-/analyzer-commons-configurations-2.31.0-5284.tgz", @@ -12605,6 +12614,52 @@ "url": "https://opencollective.com/express" } }, + "node_modules/engine.io-client": { + "version": "6.6.8", + "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.8.tgz", + "integrity": "sha512-DPN6+2uNi3A2cbSR3gqJepLVOnSQmbaJT4USgU+TgGPczEqLQT0i6t05jHrf4TT6rcxABrGp/1As0FyqwIZlGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.4.1", + "engine.io-parser": "~5.2.1", + "ws": "~8.21.0", + "xmlhttprequest-ssl": "~2.1.1" + } + }, + "node_modules/engine.io-client/node_modules/ws": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", + "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/engine.io-parser": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz", + "integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/enhanced-resolve": { "version": "5.27.0", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.27.0.tgz", @@ -17292,6 +17347,19 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/marked": { + "version": "18.3.0", + "resolved": "https://registry.npmjs.org/marked/-/marked-18.3.0.tgz", + "integrity": "sha512-ed8zmPXlBb3UfGXN5iHMQyMhFpdqLgoV5umUXx/Q1R+FW3q8VpqpyoKUwlENL9appo2UMvNLURDVaT3AMOryGA==", + "dev": true, + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 20" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -21334,6 +21402,36 @@ "url": "https://github.com/sponsors/cyyynthia" } }, + "node_modules/socket.io-client": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.4.tgz", + "integrity": "sha512-7wjKAvVXYOJsbmUgkWbnhPD4bFpkqrUR0++XOjpGFmqDqsqV1CI93VTraeExLxpjxEqrWgFoSRZu1ihjLWfkAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.4.1", + "engine.io-client": "~6.6.1", + "socket.io-parser": "~4.2.4" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/socket.io-parser": { + "version": "4.2.7", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.7.tgz", + "integrity": "sha512-IH/iSeO9T6gz1KkFleGDWkG9N3dl4jXVYUtMhIqH10Md0ttMer8nUNWiP1DKuNrybD2xBrixLJdCC9J6ECoYkg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.4.1" + }, + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/source-map": { "version": "0.8.0", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.8.0.tgz", @@ -24222,6 +24320,15 @@ "dev": true, "license": "MIT" }, + "node_modules/xmlhttprequest-ssl": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz", + "integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/xxhash-wasm": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz", @@ -24384,9 +24491,9 @@ } }, "node_modules/zibri-contract": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/zibri-contract/-/zibri-contract-3.2.0.tgz", - "integrity": "sha512-ALk3+1oMUysq6pfhu0SLjYYGFsrV5SpuXUeXGoEjV9Vit0m6Byfee6GtMl04B4KK1B5uM6ETE6+FnkE6VQbgfg==", + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/zibri-contract/-/zibri-contract-3.3.0.tgz", + "integrity": "sha512-THP6UVGrD9Nu0uym1017PGSACu8J7hHb3mE2KPdbGUnDBiU7FTFndsJGIC/0z0LGztFh+aQcOBPSoOjw6dmOwg==", "dev": true, "license": "MIT" }, diff --git a/package.json b/package.json index c5c31d4..5812d57 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,8 @@ "build-storybook": "ng run ui:build-storybook", "lint": "eslint . --max-warnings=0", "lint:fix": "eslint . --max-warnings=0 --fix", - "release:bump": "node scripts/bump-version.ts" + "release:bump": "node scripts/bump-version.ts", + "translations:update": "node scripts/translations.ts" }, "private": true, "packageManager": "npm@11.19.0", @@ -30,6 +31,7 @@ "@angular-devkit/build-angular": "^22.2.5", "@angular/aria": "^22.2.5", "@angular/build": "^22.2.5", + "@angular/cdk": "^22.2.5", "@angular/cli": "^22.2.5", "@angular/compiler-cli": "^22.2.5", "@angular/localize": "^22.2.6", @@ -48,14 +50,16 @@ "eslint": "^9.39.5", "eslint-plugin-better-tailwindcss": "^4.9.1", "jsdom": "^30.0.0", + "marked": "^18.2.0", "ng-packagr": "^22.2.0", "playwright": "^1.64.1", "postcss": "^8.5.30", + "socket.io-client": "^4.8.4", "storybook": "^10.6.2", "tailwindcss": "^4.3.3", "typescript": "~6.0.2", "uqr": "^0.1.3", "vitest": "^5.0.0", - "zibri-contract": "^3.2.0" + "zibri-contract": "^3.3.0" } } \ No newline at end of file diff --git a/projects/ngx-approval-requests/CHANGELOG.md b/projects/ngx-approval-requests/CHANGELOG.md new file mode 100644 index 0000000..d4e4f31 --- /dev/null +++ b/projects/ngx-approval-requests/CHANGELOG.md @@ -0,0 +1,13 @@ +# Changelog + +## 22.4.0 + +First release. + +### Features +- `@service-soft/ngx-approval-requests/api`: `ApprovalRequestService`, to list, propose, approve and reject approval + requests and count the pending ones, and `provideApprovalRequestsConfig`. +- `@service-soft/ngx-approval-requests/approval-requests`: the list of requests, filtered by status and action. +- `@service-soft/ngx-approval-requests/approval-request`: the review of one request, with its changes, to approve or + reject it with a note. +- The German translation of the texts ships with the package (`locale/messages.de.xlf`). diff --git a/projects/ngx-approval-requests/LICENSE b/projects/ngx-approval-requests/LICENSE new file mode 100644 index 0000000..959f86e --- /dev/null +++ b/projects/ngx-approval-requests/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Tim Fabian + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/projects/ngx-approval-requests/README.md b/projects/ngx-approval-requests/README.md new file mode 100644 index 0000000..85b2e8e --- /dev/null +++ b/projects/ngx-approval-requests/README.md @@ -0,0 +1,187 @@ +# ngx-approval-requests +Lists the approval requests of your api and reviews them: actions that someone without the permission to run them, like an AI assistant, a new employee or an integration, proposed, and that a person approves or rejects before they run. The review shows what the action does, who or what proposed it and why, and every value it would change, before and after. Approving and rejecting are both confirmed first, and the review then shows the outcome, or the message of the api when it refuses the decision. + +It reads and decides the requests through the `ApprovalRequestModel`s of [zibri-contract](https://www.npmjs.com/package/zibri-contract), which any api can answer; the approval plugin of [zibri](https://www.npmjs.com/package/zibri) is one that does. It is built on [@service-soft/ui](https://www.npmjs.com/package/@service-soft/ui), shows the changes with [@service-soft/ngx-change-sets](https://www.npmjs.com/package/@service-soft/ngx-change-sets), and is styled with Tailwind CSS. + +# Table of Contents +- [ngx-approval-requests](#ngx-approval-requests) +- [Table of Contents](#table-of-contents) +- [Requirements](#requirements) +- [Setup](#setup) +- [The list](#the-list) +- [The review](#the-review) + - [A second factor](#a-second-factor) +- [The pending count](#the-pending-count) +- [The names of users](#the-names-of-users) +- [The routes of the api](#the-routes-of-the-api) +- [Configuration](#configuration) + - [Translating](#translating) +- [License](#license) + +# Requirements +Angular 22 with the router and `@angular/localize`, which [translates the texts](#translating), and Tailwind CSS 4. The models, like `ApprovalRequestModel` and `ApprovalRequestStatus`, come from [zibri-contract](https://www.npmjs.com/package/zibri-contract). The review shows the values with `@service-soft/ngx-change-sets/changes`, and the messages of the api with `@service-soft/ngx-error-handling/error-response`. The inputs of ui need `@angular/aria`. + +```sh +npm install @service-soft/ngx-approval-requests @service-soft/ngx-change-sets @service-soft/ngx-error-handling @service-soft/ui @angular/aria zibri-contract +ng add @angular/localize +``` + +# Setup +Your Tailwind generates the css. Add the packages to your global stylesheet: + +```css +@import "tailwindcss"; +@import "@service-soft/ui"; +@import "@service-soft/ngx-change-sets"; +@import "@service-soft/ngx-approval-requests"; +``` + +Give it the url of the approval request routes of your api, and `HttpClient`, which it sends the requests with. The review takes the id of its request from the route, which `withComponentInputBinding()` hands it: + +```ts +// app.config.ts +import { provideHttpClient } from '@angular/common/http'; +import { provideRouter, withComponentInputBinding } from '@angular/router'; +import { provideApprovalRequestsConfig } from '@service-soft/ngx-approval-requests/api'; + +export const appConfig: ApplicationConfig = { + providers: [ + provideHttpClient(), + provideRouter(routes, withComponentInputBinding()), + provideApprovalRequestsConfig({ + baseUrl: 'https://api.example.com/approval-requests', + actions: { 'tasks.close': 'Close a task', 'tasks.label': 'Label a task' } + }) + ] +}; +``` + +```ts +// app.routes.ts +export const routes: Routes = [ + { + path: 'approval-requests', + title: 'Approval requests', + loadComponent: async () => (await import('@service-soft/ngx-approval-requests/approval-requests')).ApprovalRequestsComponent + }, + { + path: 'approval-requests/:requestId', + title: 'Approval request', + loadComponent: async () => (await import('@service-soft/ngx-approval-requests/approval-request')).ApprovalRequestComponent + } +]; +``` + +The list and the review are entry points of their own, so each page loads only its own code. Both read the `ApprovalRequestService` and the config of `@service-soft/ngx-approval-requests/api`. + +# The list +```html + +``` + +The requests of the api, the latest proposed first, 10 to a page. It shows the pending requests at first, and filters by status, or, with the `actions` of the config, by action as well. Each request shows its status, what its action is called, when it was proposed and its summary, which links to its review: to its id below the route of the list, like `/approval-requests/` from `/approval-requests`, or below the `reviewPath` of the config, like `reviewPath: '/approvals'` for a list on a dashboard. + +# The review +```html + +``` + +The summary of the request is its heading, a `h1`, after the badge of its status, then what its action is called, who or what proposed it, a user, a part of the application or a policy, when, until when it can be decided, and why. Below are the rows the action writes, each with its table, its id or "new" for a row the action creates, and the values it changes, each before and after, like the values of a change set. + +While the request is pending, the user writes a note, which is optional, and approves or rejects it. Each asks first, in a dialog whose cancel button has the focus, so nothing is decided by pressing enter. Once the api answered, the review shows the outcome: that the action ran, did not run, or failed with the error of the action, who decided it, when, and the note. The outcome takes the focus, as the buttons are gone. + +The api may refuse a decision, and the review shows its message then, and keeps the request to decide: + +| zibri refuses with | When | +|---|---| +| `403` | The user lacks a permission it takes, or approves a request they proposed themselves | +| `401` | The action takes a second factor the approval does not carry, see [a second factor](#a-second-factor) | +| `409` | The request is decided already or expired, or a row it was proposed against changed since, like "The row 0b6d… of task changed since the approval request was proposed. Propose the action again." | + +A decision that fails without a message of the api, like without a connection, says that it couldn't be sent. Any other error, a mistake in the app, goes on to the `ErrorHandler` of the app. + +## A second factor +An action can take a second factor of the approver, like `require2fa` of an action of zibri. The review sends the approval with `HttpClient`, so whatever asks for a second factor of other requests asks for this one too. With the `authInterceptor` of [@service-soft/ngx-auth](https://www.npmjs.com/package/@service-soft/ngx-auth) and its `secondFactorPrompt`, the user enters the code in a dialog, and the approval is sent once more with it. A user who cancels that sees the message of the api. + +# The pending count +`resolvePendingCount()` of the `ApprovalRequestService` loads how many requests wait for a decision. Show it with the [count badge](https://www.npmjs.com/package/@service-soft/ui#count-badge) of `@service-soft/ui`, like on the link to the list in your navigation. `lastDecision` of the service changes with every request the app approves or rejects, so the count loads again after each: + +```ts +@Component({ + selector: 'app-approvals-link', + template: ` + + Approvals + + `, + imports: [CountBadgeComponent, LinkComponent, RouterLink] +}) +export class ApprovalsLinkComponent { + private readonly approvalRequestService: ApprovalRequestService = inject(ApprovalRequestService); + + protected readonly pending: ResourceRef = resource({ + params: () => this.approvalRequestService.lastDecision(), + loader: async () => await this.approvalRequestService.resolvePendingCount() + }); +} +``` + +In the navbar of [@service-soft/ngx-navigation](https://www.npmjs.com/package/@service-soft/ngx-navigation), such a component is an element of the type `custom`. + +# The names of users +Who proposed or decided a request is the id of a user, the name of the part of the application that proposed it, or the name of a policy. The review shows it as it is, followed by what it is, like "task-cleanup (System)". To show the name of a user instead of the id, extend the `ApprovalRequestService` and provide yours in its place: + +```ts +@Service() +export class AppApprovalRequestService extends ApprovalRequestService { + private readonly userService: UserService = inject(UserService); + + override async resolveActorName(name: string, kind: ApprovalActorKind): Promise { + return kind === ApprovalActorKind.USER ? (await this.userService.resolveUser(name)).displayName : name; + } +} + +// app.config.ts +providers: [{ provide: ApprovalRequestService, useExisting: AppApprovalRequestService }] +``` + +The service reads the config of the injector it is created in, the one of the application. + +# The routes of the api +The `ApprovalRequestService` sends these requests below the `baseUrl`, as the `ApprovalRequestController` of the approval plugin of zibri answers them: + +| Request | Answers | +|---|---| +| `GET /?page&limit&status&action` | a `PaginationResult`, the latest proposed first | +| `POST /` with a `NewApprovalRequestModel`, `{ action, input, reason }` | the `ApprovalRequestDetailsModel` proposed, by `propose` of the service, which the views don't send themselves | +| `GET /:id` | its `ApprovalRequestDetailsModel`, the request and its decision or null | +| `POST /:id/approve` with an `ApprovalDecisionInputModel`, `{ note }` | its `ApprovalRequestDetailsModel` after approving | +| `POST /:id/reject` with an `ApprovalDecisionInputModel` | its `ApprovalRequestDetailsModel` after rejecting | + +Change the paths of deciding with `paths: { approve, reject }` of the config. The dates of the models arrive as the strings of json, and the service answers them as `Date`, as the models declare them. The user reading the list and the review needs `approval-requests.read` of zibri, and deciding a request `approval-requests.decide` and the `permission` of its action. Every route answers the requests of the active tenant, which the `authInterceptor` of ngx-auth sends. + +# Configuration +`provideApprovalRequestsConfig` sets the `baseUrl` and the defaults of the list and the review, for the whole app, or for a part of it when you add it to the providers of a component or route. Values you leave out keep the ones of the parent, labels and dialog texts included: + +| Option | Default | +|---|---| +| `baseUrl` | required — the url of the approval request routes of your api | +| `paths` | `{ approve: 'approve', reject: 'reject' }` — the paths below a request that decide it | +| `pageSize` | `10` — how many requests a page of the list has, at most 100 | +| `dateFormat` | `undefined` — the dates of a request in the language of the app's `LOCALE_ID`, like `11/24/2026, 09:30 AM` in `en-US` and `24.11.2026, 09:30` in `de`; a fixed format, like `'dd.MM.yyyy HH:mm'`, in the format of Angular's `DatePipe` | +| `actions` | `{}` — what the actions of your app are called, by their name; the list filters by them, and both show what an action is called instead of its name | +| `reviewPath` | `''` — the route of the review, which a request of the list links to with its id after it; empty for its id below the route of the list | +| `headingLevel` | `1` — the level of the heading of the review; its sections are headed one level below | +| `statusColors` | pending `primary`, approved `success`, rejected and expired `neutral`, failed `error` — the color of the badge of each status | +| `labels` | the English texts of the list and the review, to translate them | +| `approveConfirmDialogData`, `rejectConfirmDialogData` | the title, text and buttons of the questions before deciding | + +The values of the changes, like the format of their dates, are those of `provideChangesConfig` of `@service-soft/ngx-change-sets/changes`. + +## Translating +The default texts are `$localize` with an id of their own, like `@@ngx-approval-requests.api.approve`, so `ng extract-i18n` puts them into the messages of your app, and you translate them like its own texts. The library needs `@angular/localize` for that, `ng add @angular/localize`, also in an app of one language. A build with `localize` fills the texts in, so no part of `@angular/localize` reaches the browser. The defaults are made once the config is injected, so translations an app loads at runtime with `loadTranslations` apply as well. A text of `provideApprovalRequestsConfig` replaces the default in every language. So translate a default in your messages, and change it in the config only to say something else: a default the config replaces stays in your messages, though nothing shows it. + +German ships with the library: `locale/messages.de.xlf` of the package is an XLIFF 1.2 file with a German target for each of its texts, and its `package.json` names it in `"translations": { "de": "./locale/messages.de.xlf" }`. A merge of the translations of an app's dependencies reads that field and fills these targets into the German messages of the app, so German needs no translation of your own. Only the texts your app uses end up there, since its `ng extract-i18n` decides which units its messages have. Other languages you translate in your messages. + +# License +MIT. diff --git a/projects/ngx-approval-requests/api/approval-request.service.spec.ts b/projects/ngx-approval-requests/api/approval-request.service.spec.ts new file mode 100644 index 0000000..42650a8 --- /dev/null +++ b/projects/ngx-approval-requests/api/approval-request.service.spec.ts @@ -0,0 +1,128 @@ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { describe, expect, test } from 'vitest'; +import { ApprovalActorKind, ApprovalDecisionType, ApprovalRequestDetailsModel, ApprovalRequestModel, ApprovalRequestStatus, PaginationResult } from 'zibri-contract'; + +import { ApprovalRequestService } from './approval-request.service'; +import { provideApprovalRequestsConfig } from './approval-requests-config.provider'; + +const REQUEST: ApprovalRequestModel = { + id: 'request-1', + tenantId: 'tenant-1', + action: 'tasks.close', + input: { taskId: 'task-1' }, + reason: 'The release is out', + summary: 'Close the task "Write the release notes"', + changes: [{ entity: 'task', id: 'task-1', changes: [{ key: 'status', previousValue: 'open', newValue: 'done' }] }], + preconditions: [{ entity: 'task', id: 'task-1', hash: 'q2X4n7mW1sYc0bJt9pVhR5kLdEaFzU3oGiN8wTe6yMQ' }], + proposedBy: 'user-1', + proposedByKind: ApprovalActorKind.USER, + proposedAt: new Date('2026-11-24T09:30:00.000Z'), + status: ApprovalRequestStatus.PENDING, + expiresAt: new Date('2026-12-01T09:30:00.000Z') +}; + +const APPROVED: ApprovalRequestDetailsModel = { + request: { ...REQUEST, status: ApprovalRequestStatus.APPROVED }, + decision: { + id: 'decision-1', + tenantId: 'tenant-1', + chainSequence: 1, + chainHash: 'hash', + requestId: 'request-1', + decision: ApprovalDecisionType.APPROVED, + decidedBy: 'user-2', + decidedByKind: ApprovalActorKind.USER, + decidedAt: new Date('2026-11-24T10:00:00.000Z'), + note: 'Looks right' + } +}; + +// what the api sends: json, whose dates are strings. +function toJson(value: unknown): object { + return JSON.parse(JSON.stringify(value)) as object; +} + +function setup(): [ApprovalRequestService, HttpTestingController] { + TestBed.configureTestingModule({ + providers: [provideHttpClient(), provideHttpClientTesting(), provideApprovalRequestsConfig({ baseUrl: '/api/approval-requests' })] + }); + return [TestBed.inject(ApprovalRequestService), TestBed.inject(HttpTestingController)]; +} + +describe('ApprovalRequestService', () => { + test('loads a page of requests with the filters as query, and answers their dates as Date', async () => { + const [service, http] = setup(); + + const page: Promise> = service.resolveRequests({ + page: 2, + limit: 10, + status: ApprovalRequestStatus.PENDING, + action: 'tasks.close' + }); + const request: TestRequest = http.expectOne(({ method, url }) => method === 'GET' && url === '/api/approval-requests'); + expect(request.request.params.toString()).toBe('page=2&limit=10&status=PENDING&action=tasks.close'); + request.flush(toJson({ items: [REQUEST], totalAmount: 11 })); + + await expect(page).resolves.toEqual({ items: [REQUEST], totalAmount: 11 }); + http.verify(); + }); + + test('loads the number of pending requests from the total of a page of them', async () => { + const [service, http] = setup(); + + const count: Promise = service.resolvePendingCount(); + const request: TestRequest = http.expectOne(({ url }) => url === '/api/approval-requests'); + expect(request.request.params.toString()).toBe('page=1&limit=1&status=PENDING'); + request.flush(toJson({ items: [REQUEST], totalAmount: 3 })); + + await expect(count).resolves.toBe(3); + }); + + test('loads a request, decides it with a POST of the note below it, and keeps the last decision', async () => { + const [service, http] = setup(); + + const loaded: Promise = service.resolveRequest('request-1'); + // eslint-disable-next-line unicorn/no-null -- the api answers null while there is no decision + http.expectOne({ method: 'GET', url: '/api/approval-requests/request-1' }).flush(toJson({ request: REQUEST, decision: null })); + // eslint-disable-next-line unicorn/no-null -- the api answers null while there is no decision + await expect(loaded).resolves.toEqual({ request: REQUEST, decision: null }); + expect(service.lastDecision()).toBeUndefined(); + + const approved: Promise = service.approve('request-1', { note: 'Looks right' }); + const approve: TestRequest = http.expectOne({ method: 'POST', url: '/api/approval-requests/request-1/approve' }); + expect(approve.request.body).toEqual({ note: 'Looks right' }); + approve.flush(toJson(APPROVED)); + await expect(approved).resolves.toEqual(APPROVED); + expect(service.lastDecision()).toEqual(APPROVED); + + void service.reject('request-1', {}); + http.expectOne({ method: 'POST', url: '/api/approval-requests/request-1/reject' }); + http.verify(); + }); + + test('proposes an action with a POST of its name, input and reason, and answers its dates as Date', async () => { + const [service, http] = setup(); + + const proposed: Promise = service.propose({ + action: 'tasks.close', + input: { taskId: 'task-1' }, + reason: 'The release is out' + }); + const request: TestRequest = http.expectOne({ method: 'POST', url: '/api/approval-requests' }); + expect(request.request.body).toEqual({ action: 'tasks.close', input: { taskId: 'task-1' }, reason: 'The release is out' }); + // eslint-disable-next-line unicorn/no-null -- the api answers null while there is no decision + request.flush(toJson({ request: REQUEST, decision: null })); + + // eslint-disable-next-line unicorn/no-null -- the api answers null while there is no decision + await expect(proposed).resolves.toEqual({ request: REQUEST, decision: null }); + expect(service.lastDecision()).toBeUndefined(); + }); + + test('says what is missing without the baseUrl', async () => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + + await expect(TestBed.inject(ApprovalRequestService).resolveRequest('request-1')).rejects.toThrow('provideApprovalRequestsConfig({ baseUrl })'); + }); +}); \ No newline at end of file diff --git a/projects/ngx-approval-requests/api/approval-request.service.ts b/projects/ngx-approval-requests/api/approval-request.service.ts new file mode 100644 index 0000000..66fc7b9 --- /dev/null +++ b/projects/ngx-approval-requests/api/approval-request.service.ts @@ -0,0 +1,154 @@ +import { HttpClient } from '@angular/common/http'; +import { inject, Service, Signal, signal, WritableSignal } from '@angular/core'; +import { firstValueFrom } from 'rxjs'; +import { ApprovalActorKind, ApprovalDecisionInputModel, ApprovalDecisionModel, ApprovalRequestDetailsModel, ApprovalRequestModel, ApprovalRequestStatus, NewApprovalRequestModel, PaginationResult } from 'zibri-contract'; + +import { ApprovalRequestsConfig } from './approval-requests-config.model'; +import { APPROVAL_REQUESTS_CONFIG } from './approval-requests-config.provider'; +import { ApprovalRequestsQuery } from './approval-requests-query.model'; + +/** + * The query of a request for a page of approval requests. + */ +type RequestsParams = Record; + +/** + * Sends the requests of the approval request routes at the baseUrl of provideApprovalRequestsConfig: `GET /` for a page + * of requests, `POST /` to propose one, `GET /:id` for one with its decision, and `POST /:id/approve` and + * `POST /:id/reject` to decide one. It answers the models of zibri-contract, with their dates as Date. It needs HttpClient, from provideHttpClient. Extend it + * to show the names of users instead of their ids, and provide your class in its place. + */ +@Service() +export class ApprovalRequestService { + /** + * Sends the requests. + */ + protected readonly http: HttpClient = inject(HttpClient); + + private readonly config: ApprovalRequestsConfig = inject(APPROVAL_REQUESTS_CONFIG); + + private readonly lastDecisionSignal: WritableSignal = signal(undefined); + + /** + * The last request this service approved or rejected, with its decision, or undefined before the first. Read it in + * the params of a resource of the pending count, which then loads again after every decision of the app. + */ + readonly lastDecision: Signal = this.lastDecisionSignal.asReadonly(); + + /** + * Loads a page of the approval requests, the latest proposed first. + * @param query - The page, and the status and action to filter by. + * @returns The requests of the page, and how many match on all pages together. + */ + async resolveRequests(query: ApprovalRequestsQuery): Promise> { + const params: RequestsParams = { + page: query.page, + limit: query.limit, + ...query.status == undefined ? {} : { status: query.status }, + ...query.action == undefined ? {} : { action: query.action } + }; + const page: PaginationResult = await firstValueFrom( + this.http.get>(this.resolveUrl(), { params }) + ); + return { ...page, items: page.items.map(request => this.toRequest(request)) }; + } + + /** + * Loads how many requests wait for a decision, like for a count badge on a link to them. + * @returns The number of pending requests. + */ + async resolvePendingCount(): Promise { + const page: PaginationResult = await this.resolveRequests({ + page: 1, + limit: 1, + status: ApprovalRequestStatus.PENDING + }); + return page.totalAmount; + } + + /** + * Loads a request and its decision. + * @param id - The id of the request. + * @returns The request, and its decision or null while there is none. + */ + async resolveRequest(id: string): Promise { + return this.toDetails(await firstValueFrom(this.http.get(this.resolveUrl(id)))); + } + + /** + * Proposes an action as the logged in user, which runs once a person with its permission approves it. Rejects with + * the error of the request when the api refuses it, like for a user without the permission to propose it, or an + * input the action doesn't take. + * @param request - The name of the action, what it runs with, and why it is proposed. + * @returns The request proposed, with no decision yet. + */ + async propose(request: NewApprovalRequestModel): Promise { + return this.toDetails(await firstValueFrom(this.http.post(this.resolveUrl(), request))); + } + + /** + * Approves a request, which runs its action in the name of the logged in user. Rejects with the error of the + * request when the api refuses it, like for a request that changed since it was proposed, one the user proposed + * themselves, or one that takes a second factor. + * @param id - The id of the request. + * @param input - The note for the proposer. + * @returns The request, and its decision with the result or the error of its action. + */ + async approve(id: string, input: ApprovalDecisionInputModel): Promise { + return await this.decide(id, this.config.paths.approve, input); + } + + /** + * Rejects a request, whose action then never runs. Rejects with the error of the request when the api refuses it. + * @param id - The id of the request. + * @param input - The note for the proposer, like why it was rejected. + * @returns The request, and its decision. + */ + async reject(id: string, input: ApprovalDecisionInputModel): Promise { + return await this.decide(id, this.config.paths.reject, input); + } + + /** + * Resolves the name shown for who or what proposed or decided a request. + * @param name - The id of the user, or the name of the part of the application or of the policy. + * @param kind - Whether a user, the system or a policy it is. + * @returns The id or name as it is by default. Override it to show the name of a user instead of their id. + */ + resolveActorName(name: string, kind: ApprovalActorKind): string | Promise { + // the default needs only the name. The kind is there for an override, which looks up only the ids of users. + void kind; + return name; + } + + private async decide(id: string, path: string, input: ApprovalDecisionInputModel): Promise { + const details: ApprovalRequestDetailsModel = this.toDetails( + await firstValueFrom(this.http.post(this.resolveUrl(id, path), input)) + ); + this.lastDecisionSignal.set(details); + return details; + } + + private resolveUrl(...segments: string[]): string { + if (this.config.baseUrl == undefined) { + throw new Error('The ApprovalRequestService needs the url of the approval request routes of your api. ' + + 'Add provideApprovalRequestsConfig({ baseUrl }) to the providers of your app.'); + } + return [this.config.baseUrl, ...segments.map(segment => encodeURIComponent(segment))].join('/'); + } + + // the dates arrive as the strings of json, which the models of zibri-contract declare as Date. + private toDetails(details: ApprovalRequestDetailsModel): ApprovalRequestDetailsModel { + return { + request: this.toRequest(details.request), + decision: details.decision == undefined ? details.decision : this.toDecision(details.decision) + }; + } + + private toRequest(request: ApprovalRequestModel): ApprovalRequestModel { + return { ...request, proposedAt: new Date(request.proposedAt), expiresAt: new Date(request.expiresAt) }; + } + + private toDecision(decision: ApprovalDecisionModel): ApprovalDecisionModel { + return { ...decision, decidedAt: new Date(decision.decidedAt) }; + } +} \ No newline at end of file diff --git a/projects/ngx-approval-requests/api/approval-requests-config-changes.model.ts b/projects/ngx-approval-requests/api/approval-requests-config-changes.model.ts new file mode 100644 index 0000000..0f243fc --- /dev/null +++ b/projects/ngx-approval-requests/api/approval-requests-config-changes.model.ts @@ -0,0 +1,51 @@ +import { ConfirmDialogData } from '@service-soft/ui/dialog'; + +import { ApprovalRequestsConfig } from './approval-requests-config.model'; +import { ApprovalRequestsLabels } from './approval-requests-labels.model'; + +/** + * The values to change in the config of the approval requests. Everything is optional, including every single path, + * label and text of the confirm dialogs, but the requests need the baseUrl once. + */ +export type ApprovalRequestsConfigChanges = Partial> & { + /** + * The url of the approval request routes of your api, like 'https://api.example.com/approval-requests'. + */ + baseUrl?: string, + /** + * The paths to change. + */ + paths?: Partial, + /** + * The colors of the statuses to change. + */ + statusColors?: Partial, + /** + * The labels to change. + */ + labels?: Partial> & { + /** + * The names of the statuses to change. + */ + statuses?: Partial, + /** + * What the review says about the statuses to change. + */ + outcomes?: Partial, + /** + * The names of the kinds of actors to change. + */ + actorKinds?: Partial + }, + /** + * The texts of the question before approving to change. + */ + approveConfirmDialogData?: Partial, + /** + * The texts of the question before rejecting to change. + */ + rejectConfirmDialogData?: Partial +}; \ No newline at end of file diff --git a/projects/ngx-approval-requests/api/approval-requests-config.model.ts b/projects/ngx-approval-requests/api/approval-requests-config.model.ts new file mode 100644 index 0000000..ab35c94 --- /dev/null +++ b/projects/ngx-approval-requests/api/approval-requests-config.model.ts @@ -0,0 +1,61 @@ +import { BadgeColor } from '@service-soft/ui/badge'; +import { ConfirmDialogData } from '@service-soft/ui/dialog'; +import { HeadingLevel } from '@service-soft/ui/heading'; +import { ApprovalRequestStatus } from 'zibri-contract'; + +import { ApprovalRequestsLabels } from './approval-requests-labels.model'; +import { ApprovalRequestsPaths } from './approval-requests-paths.model'; + +/** + * Where the approval requests are, and the values their list and review use. + */ +export type ApprovalRequestsConfig = { + /** + * The url of the approval request routes of your api, like 'https://api.example.com/approval-requests'. Undefined + * until provideApprovalRequestsConfig sets it, which every request needs. + */ + baseUrl: string | undefined, + /** + * The paths below a request that decide it. + */ + paths: ApprovalRequestsPaths, + /** + * How many requests a page of the list has. At most 100, which a page of the api holds. + */ + pageSize: number, + /** + * How the dates of a request are shown: a fixed format, in the format of Angular's DatePipe, or undefined for the day + * and the time in the language of the app's LOCALE_ID. + */ + dateFormat: string | undefined, + /** + * The actions of the app by their name, with what they are called, like `{ 'tasks.close': 'Close a task' }`. The list + * offers them as a filter, and both show what they are called instead of their name. + */ + actions: Record, + /** + * The route of the review that a request of the list links to, with its id after it, like '/approval-requests'. An + * empty string links to the id below the route of the list. + */ + reviewPath: string, + /** + * The level of the heading of the review, the summary of the request. Its sections are headed one level below. + */ + headingLevel: HeadingLevel, + /** + * The color of the badge of each status, which also says the status in text. + */ + statusColors: Record, + /** + * The texts of the list and the review. + */ + labels: ApprovalRequestsLabels, + /** + * The question before approving a request. + */ + approveConfirmDialogData: ConfirmDialogData, + /** + * The question before rejecting a request. + */ + rejectConfirmDialogData: ConfirmDialogData +}; \ No newline at end of file diff --git a/projects/ngx-approval-requests/api/approval-requests-config.provider.ts b/projects/ngx-approval-requests/api/approval-requests-config.provider.ts new file mode 100644 index 0000000..aee4723 --- /dev/null +++ b/projects/ngx-approval-requests/api/approval-requests-config.provider.ts @@ -0,0 +1,134 @@ +import { inject, InjectionToken, Provider } from '@angular/core'; +import { ApprovalActorKind, ApprovalRequestStatus } from 'zibri-contract'; + +import { ApprovalRequestsConfigChanges } from './approval-requests-config-changes.model'; +import { ApprovalRequestsConfig } from './approval-requests-config.model'; + +/** + * The values of the approval requests when nothing changes them. Their texts are $localize, which an app translates like + * its own, and resolved once the config is injected, so translations an app loads at runtime apply as well. + * @returns The default config. + */ +function getDefaultApprovalRequestsConfig(): ApprovalRequestsConfig { + return { + baseUrl: undefined, + paths: { approve: 'approve', reject: 'reject' }, + pageSize: 10, + dateFormat: undefined, + actions: {}, + reviewPath: '', + headingLevel: 1, + // the badge says the status in text as well, so the color is never the only cue. + statusColors: { + [ApprovalRequestStatus.PENDING]: 'primary', + [ApprovalRequestStatus.APPROVED]: 'success', + [ApprovalRequestStatus.REJECTED]: 'neutral', + [ApprovalRequestStatus.EXPIRED]: 'neutral', + [ApprovalRequestStatus.FAILED]: 'error' + }, + labels: { + statuses: { + [ApprovalRequestStatus.PENDING]: $localize`:@@ngx-approval-requests.api.statuses.pending:Pending`, + [ApprovalRequestStatus.APPROVED]: $localize`:@@ngx-approval-requests.api.statuses.approved:Approved`, + [ApprovalRequestStatus.REJECTED]: $localize`:@@ngx-approval-requests.api.statuses.rejected:Rejected`, + [ApprovalRequestStatus.EXPIRED]: $localize`:@@ngx-approval-requests.api.statuses.expired:Expired`, + [ApprovalRequestStatus.FAILED]: $localize`:@@ngx-approval-requests.api.statuses.failed:Failed` + }, + outcomes: { + [ApprovalRequestStatus.PENDING]: $localize`:@@ngx-approval-requests.api.outcomes.pending:Nothing runs until someone approves it.`, + [ApprovalRequestStatus.APPROVED]: $localize`:@@ngx-approval-requests.api.outcomes.approved:The action ran.`, + [ApprovalRequestStatus.REJECTED]: $localize`:@@ngx-approval-requests.api.outcomes.rejected:The action did not run.`, + [ApprovalRequestStatus.EXPIRED]: $localize`:@@ngx-approval-requests.api.outcomes.expired:Nobody decided it in time. The action did not run.`, + [ApprovalRequestStatus.FAILED]: $localize`:@@ngx-approval-requests.api.outcomes.failed:The action failed. Nothing it wrote was kept.` + }, + actorKinds: { + [ApprovalActorKind.USER]: $localize`:@@ngx-approval-requests.api.actorKinds.user:User`, + [ApprovalActorKind.SYSTEM]: $localize`:@@ngx-approval-requests.api.actorKinds.system:System`, + [ApprovalActorKind.POLICY]: $localize`:@@ngx-approval-requests.api.actorKinds.policy:Policy` + }, + statusFilter: $localize`:@@ngx-approval-requests.api.statusFilter:Status`, + allStatuses: $localize`:@@ngx-approval-requests.api.allStatuses:All statuses`, + actionFilter: $localize`:@@ngx-approval-requests.api.actionFilter:Action`, + allActions: $localize`:@@ngx-approval-requests.api.allActions:All actions`, + noRequests: $localize`:@@ngx-approval-requests.api.noRequests:No approval request matches the filters.`, + loadingRequestsFailed: $localize`:@@ngx-approval-requests.api.loadingRequestsFailed:The approval requests couldn't be loaded.`, + pages: $localize`:@@ngx-approval-requests.api.pages:Pages of the approval requests`, + action: $localize`:@@ngx-approval-requests.api.action:Action`, + proposedBy: $localize`:@@ngx-approval-requests.api.proposedBy:Proposed by`, + proposedAt: $localize`:@@ngx-approval-requests.api.proposedAt:Proposed at`, + expiresAt: $localize`:@@ngx-approval-requests.api.expiresAt:Expires at`, + reason: $localize`:@@ngx-approval-requests.api.reason:Reason`, + changes: $localize`:@@ngx-approval-requests.api.changes:Changes`, + newRow: $localize`:@@ngx-approval-requests.api.newRow:new`, + noChanges: $localize`:@@ngx-approval-requests.api.noChanges:The action changes no stored values.`, + decision: $localize`:@@ngx-approval-requests.api.decision:Decision`, + note: $localize`:@@ngx-approval-requests.api.note:Note`, + noteHint: $localize`:@@ngx-approval-requests.api.noteHint:Sent with your decision, like why you reject it`, + approve: $localize`:@@ngx-approval-requests.api.approve:Approve`, + reject: $localize`:@@ngx-approval-requests.api.reject:Reject`, + decidedBy: $localize`:@@ngx-approval-requests.api.decidedBy:Decided by`, + decidedAt: $localize`:@@ngx-approval-requests.api.decidedAt:Decided at`, + error: $localize`:@@ngx-approval-requests.api.error:Error`, + loadingRequestFailed: $localize`:@@ngx-approval-requests.api.loadingRequestFailed:The approval request couldn't be loaded.`, + decisionFailed: $localize`:@@ngx-approval-requests.api.decisionFailed:The decision couldn't be sent. Please try again.`, + loading: $localize`:@@ngx-approval-requests.api.loading:Loading the approval request` + }, + approveConfirmDialogData: { + title: $localize`:@@ngx-approval-requests.api.approveConfirmDialogData.title:Approve this request?`, + paragraphs: [$localize`:@@ngx-approval-requests.api.approveConfirmDialogData.paragraphs:The action runs right away, in your name.`], + confirmButtonLabel: $localize`:@@ngx-approval-requests.api.approveConfirmDialogData.confirmButtonLabel:Approve`, + cancelButtonLabel: $localize`:@@ngx-approval-requests.api.approveConfirmDialogData.cancelButtonLabel:Cancel`, + confirmButtonColor: 'primary' + }, + rejectConfirmDialogData: { + title: $localize`:@@ngx-approval-requests.api.rejectConfirmDialogData.title:Reject this request?`, + paragraphs: [$localize`:@@ngx-approval-requests.api.rejectConfirmDialogData.paragraphs:The action won't run. This can't be undone.`], + confirmButtonLabel: $localize`:@@ngx-approval-requests.api.rejectConfirmDialogData.confirmButtonLabel:Reject`, + cancelButtonLabel: $localize`:@@ngx-approval-requests.api.rejectConfirmDialogData.cancelButtonLabel:Cancel`, + confirmButtonColor: 'error' + } + }; +} + +/** + * Where the approval requests are, and the values their list and review use, below this injector. Change them with + * provideApprovalRequestsConfig. + */ +export const APPROVAL_REQUESTS_CONFIG: InjectionToken = new InjectionToken( + 'APPROVAL_REQUESTS_CONFIG', + { providedIn: 'root', factory: () => getDefaultApprovalRequestsConfig() } +); + +/** + * Sets where the approval requests are, `{ baseUrl }`, and changes the values their list and review use, like the + * labels to translate them. Provide it in the application config for the whole app, or in a component or route for only + * that part of it. Values you leave out are taken from the parent injector, including single paths, labels and texts of + * the dialogs. + * @param config - The values to change. + * @returns The provider for APPROVAL_REQUESTS_CONFIG. + */ +export function provideApprovalRequestsConfig(config: ApprovalRequestsConfigChanges): Provider { + return { + provide: APPROVAL_REQUESTS_CONFIG, + useFactory: (): ApprovalRequestsConfig => { + const parent: ApprovalRequestsConfig = inject(APPROVAL_REQUESTS_CONFIG, { skipSelf: true, optional: true }) + ?? getDefaultApprovalRequestsConfig(); + return { + ...parent, + ...config, + baseUrl: config.baseUrl ?? parent.baseUrl, + paths: { ...parent.paths, ...config.paths }, + statusColors: { ...parent.statusColors, ...config.statusColors }, + labels: { + ...parent.labels, + ...config.labels, + statuses: { ...parent.labels.statuses, ...config.labels?.statuses }, + outcomes: { ...parent.labels.outcomes, ...config.labels?.outcomes }, + actorKinds: { ...parent.labels.actorKinds, ...config.labels?.actorKinds } + }, + approveConfirmDialogData: { ...parent.approveConfirmDialogData, ...config.approveConfirmDialogData }, + rejectConfirmDialogData: { ...parent.rejectConfirmDialogData, ...config.rejectConfirmDialogData } + }; + } + }; +} \ No newline at end of file diff --git a/projects/ngx-approval-requests/api/approval-requests-labels.model.ts b/projects/ngx-approval-requests/api/approval-requests-labels.model.ts new file mode 100644 index 0000000..c585281 --- /dev/null +++ b/projects/ngx-approval-requests/api/approval-requests-labels.model.ts @@ -0,0 +1,123 @@ +import { ApprovalActorKind, ApprovalRequestStatus } from 'zibri-contract'; + +/** + * The texts the list and the review of approval requests show, to translate them. + */ +export type ApprovalRequestsLabels = { + /** + * What each status is called, like 'Pending'. + */ + statuses: Record, + /** + * What the review says about each status, like that the action ran once it is approved. + */ + outcomes: Record, + /** + * What each kind of actor is called, shown after its name, like 'System'. + */ + actorKinds: Record, + /** + * The filter of the status. + */ + statusFilter: string, + /** + * The option of the status filter that shows the requests of every status. + */ + allStatuses: string, + /** + * The filter of the action. + */ + actionFilter: string, + /** + * The option of the action filter that shows the requests of every action. + */ + allActions: string, + /** + * What the list says when no request matches the filters. + */ + noRequests: string, + /** + * What the list says when the requests couldn't be loaded. + */ + loadingRequestsFailed: string, + /** + * What screen readers call the pagination of the list. + */ + pages: string, + /** + * The name of the action of a request. + */ + action: string, + /** + * Who or what proposed a request. + */ + proposedBy: string, + /** + * When a request was proposed. + */ + proposedAt: string, + /** + * When a request expires. + */ + expiresAt: string, + /** + * Why a request was proposed. + */ + reason: string, + /** + * The heading of the rows a request would write. + */ + changes: string, + /** + * What a row the action creates is called, in place of its id. + */ + newRow: string, + /** + * What the review says when the action changes no stored value. + */ + noChanges: string, + /** + * The heading of the decision. + */ + decision: string, + /** + * The input of the note sent with a decision. + */ + note: string, + /** + * The hint below the input of the note. + */ + noteHint: string, + /** + * The button that approves the request. + */ + approve: string, + /** + * The button that rejects the request. + */ + reject: string, + /** + * Who or what decided a request. + */ + decidedBy: string, + /** + * When a request was decided. + */ + decidedAt: string, + /** + * What the action failed with, once it ran and failed. + */ + error: string, + /** + * What the review says when the request couldn't be loaded. + */ + loadingRequestFailed: string, + /** + * What the review says when a decision was refused without a message of the server, like without a connection. + */ + decisionFailed: string, + /** + * What screen readers read while the review loads. + */ + loading: string +}; \ No newline at end of file diff --git a/projects/ngx-approval-requests/api/approval-requests-paths.model.ts b/projects/ngx-approval-requests/api/approval-requests-paths.model.ts new file mode 100644 index 0000000..572703b --- /dev/null +++ b/projects/ngx-approval-requests/api/approval-requests-paths.model.ts @@ -0,0 +1,13 @@ +/** + * The paths below a request, `//`, that decide it. + */ +export type ApprovalRequestsPaths = { + /** + * Approves a request, with a POST of its note. 'approve' by default. + */ + approve: string, + /** + * Rejects a request, with a POST of its note. 'reject' by default. + */ + reject: string +}; \ No newline at end of file diff --git a/projects/ngx-approval-requests/api/approval-requests-query.model.ts b/projects/ngx-approval-requests/api/approval-requests-query.model.ts new file mode 100644 index 0000000..8b11ba6 --- /dev/null +++ b/projects/ngx-approval-requests/api/approval-requests-query.model.ts @@ -0,0 +1,23 @@ +import { ApprovalRequestStatus } from 'zibri-contract'; + +/** + * Which page of the approval requests to load, as `GET /` of the routes takes it. + */ +export type ApprovalRequestsQuery = { + /** + * The page, from 1 on. + */ + page: number, + /** + * How many requests a page has, at most 100. + */ + limit: number, + /** + * Only the requests of this status. Undefined for every status. + */ + status?: ApprovalRequestStatus, + /** + * Only the requests of this action, by its name. Undefined for every action. + */ + action?: string +}; \ No newline at end of file diff --git a/projects/ngx-approval-requests/api/ng-package.json b/projects/ngx-approval-requests/api/ng-package.json new file mode 100644 index 0000000..70e0a80 --- /dev/null +++ b/projects/ngx-approval-requests/api/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} \ No newline at end of file diff --git a/projects/ngx-approval-requests/api/public-api.ts b/projects/ngx-approval-requests/api/public-api.ts new file mode 100644 index 0000000..628817d --- /dev/null +++ b/projects/ngx-approval-requests/api/public-api.ts @@ -0,0 +1,7 @@ +export * from './approval-request.service'; +export * from './approval-requests-config-changes.model'; +export * from './approval-requests-config.model'; +export * from './approval-requests-config.provider'; +export * from './approval-requests-labels.model'; +export * from './approval-requests-paths.model'; +export * from './approval-requests-query.model'; \ No newline at end of file diff --git a/projects/ngx-approval-requests/approval-request/approval-request-changes.component.html b/projects/ngx-approval-requests/approval-request/approval-request-changes.component.html new file mode 100644 index 0000000..d70c853 --- /dev/null +++ b/projects/ngx-approval-requests/approval-request/approval-request-changes.component.html @@ -0,0 +1,8 @@ +@for (row of rows(); track $index) { +
+

{{ row.entity }} {{ row.id }}

+ +
+} @empty { +

{{ emptyLabel() }}

+} diff --git a/projects/ngx-approval-requests/approval-request/approval-request-changes.component.ts b/projects/ngx-approval-requests/approval-request/approval-request-changes.component.ts new file mode 100644 index 0000000..c7cde40 --- /dev/null +++ b/projects/ngx-approval-requests/approval-request/approval-request-changes.component.ts @@ -0,0 +1,25 @@ +import { Component, input, InputSignal } from '@angular/core'; +import { ChangesComponent } from '@service-soft/ngx-change-sets/changes'; + +import { ApprovalRequestRowView } from './approval-request-row-view.model'; + +/** + * The rows an approval request would write, each with the values it changes on it. Only used by the review. + */ +@Component({ + selector: 'ngx-approval-request-changes', + templateUrl: './approval-request-changes.component.html', + imports: [ChangesComponent], + host: { class: 'grid gap-3' } +}) +export class ApprovalRequestChangesComponent { + /** + * The rows. + */ + readonly rows: InputSignal = input.required(); + + /** + * What the review says when the action changes no stored value. + */ + readonly emptyLabel: InputSignal = input.required(); +} \ No newline at end of file diff --git a/projects/ngx-approval-requests/approval-request/approval-request-row-view.model.ts b/projects/ngx-approval-requests/approval-request/approval-request-row-view.model.ts new file mode 100644 index 0000000..2e3a10f --- /dev/null +++ b/projects/ngx-approval-requests/approval-request/approval-request-row-view.model.ts @@ -0,0 +1,19 @@ +import { ApprovalValueChangeModel } from 'zibri-contract'; + +/** + * A row an approval request would write, as the review shows it. + */ +export type ApprovalRequestRowView = { + /** + * The table of the row, like 'task'. + */ + entity: string, + /** + * The id of the row, or the label of a new row. + */ + id: string, + /** + * The values the action changes on it. + */ + changes: ApprovalValueChangeModel[] +}; \ No newline at end of file diff --git a/projects/ngx-approval-requests/approval-request/approval-request-view.model.ts b/projects/ngx-approval-requests/approval-request/approval-request-view.model.ts new file mode 100644 index 0000000..ac09474 --- /dev/null +++ b/projects/ngx-approval-requests/approval-request/approval-request-view.model.ts @@ -0,0 +1,47 @@ +import { BadgeColor } from '@service-soft/ui/badge'; +import { CalloutTone } from '@service-soft/ui/callout'; +import { DataListItem } from '@service-soft/ui/data-list'; + +import { ApprovalRequestRowView } from './approval-request-row-view.model'; + +/** + * An approval request and its decision, as the review shows them. + */ +export type ApprovalRequestView = { + /** + * What the action does, the heading of the review. + */ + summary: string, + /** + * What the status is called. + */ + status: string, + /** + * The color of the badge of the status. + */ + statusColor: BadgeColor, + /** + * Whether it waits for a decision, which the review then asks for. + */ + isPending: boolean, + /** + * What the status means, like that the action ran. + */ + outcome: string, + /** + * The tone of the outcome once it is no longer pending. + */ + outcomeTone: CalloutTone, + /** + * The action, who proposed it, when and why, and when it expires. + */ + items: DataListItem[], + /** + * The rows the action writes, with the values it changes on each. + */ + rows: ApprovalRequestRowView[], + /** + * Who decided it, when, with which note, and the error of its action. Empty while there is no decision. + */ + decisionItems: DataListItem[] +}; \ No newline at end of file diff --git a/projects/ngx-approval-requests/approval-request/approval-request.component.html b/projects/ngx-approval-requests/approval-request/approval-request.component.html new file mode 100644 index 0000000..026190a --- /dev/null +++ b/projects/ngx-approval-requests/approval-request/approval-request.component.html @@ -0,0 +1,45 @@ +
+ @if (loadingFailed()) { + + } + @if (view(); as view) { +
+ {{ view.status }} + {{ view.summary }} +
+ + +
+ {{ labels.changes }} + +
+ +
+ {{ labels.decision }} + @if (view.isPending) { +

{{ view.outcome }}

+ + @if (decisionError(); as message) { +
+ +

{{ message }}

+
+ } +
+ + +
+ } @else { + +
+ +

{{ view.outcome }}

+ @if (view.decisionItems.length) { + + } +
+
+ } +
+ } +
diff --git a/projects/ngx-approval-requests/approval-request/approval-request.component.spec.ts b/projects/ngx-approval-requests/approval-request/approval-request.component.spec.ts new file mode 100644 index 0000000..baa2600 --- /dev/null +++ b/projects/ngx-approval-requests/approval-request/approval-request.component.spec.ts @@ -0,0 +1,247 @@ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component, input, InputSignal } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideApprovalRequestsConfig } from '@service-soft/ngx-approval-requests/api'; +import { DialogTestingUtilities } from 'testing/dialog'; +import { FormTestingUtilities } from 'testing/form'; +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; +import { ApprovalActorKind, ApprovalDecisionModel, ApprovalDecisionType, ApprovalRequestDetailsModel, ApprovalRequestModel, ApprovalRequestStatus, ErrorResponseBody } from 'zibri-contract'; + +import { ApprovalRequestComponent } from './approval-request.component'; + +const REQUEST: ApprovalRequestModel = { + id: 'request-1', + tenantId: 'tenant-1', + action: 'tasks.close', + input: { taskId: 'task-1' }, + reason: 'The release is out', + summary: 'Close the task "Write the release notes"', + changes: [ + { entity: 'task', id: 'task-1', changes: [{ key: 'status', previousValue: 'open', newValue: 'done' }] }, + // eslint-disable-next-line unicorn/no-null -- the api sends null for a row the action creates + { entity: 'comment', id: null, changes: [{ key: 'text', newValue: 'Closed with the release' }] } + ], + preconditions: [{ entity: 'task', id: 'task-1', hash: 'q2X4n7mW1sYc0bJt9pVhR5kLdEaFzU3oGiN8wTe6yMQ' }], + proposedBy: 'task-cleanup', + proposedByKind: ApprovalActorKind.SYSTEM, + proposedAt: new Date('2026-11-24T09:30:00'), + status: ApprovalRequestStatus.PENDING, + expiresAt: new Date('2026-12-01T09:30:00') +}; + +// eslint-disable-next-line unicorn/no-null -- the api answers null while there is no decision +const PENDING: ApprovalRequestDetailsModel = { request: REQUEST, decision: null }; + +const DECISION: ApprovalDecisionModel = { + id: 'decision-1', + tenantId: 'tenant-1', + chainSequence: 1, + chainHash: 'hash', + requestId: 'request-1', + decision: ApprovalDecisionType.APPROVED, + decidedBy: 'user-2', + decidedByKind: ApprovalActorKind.USER, + decidedAt: new Date('2026-11-24T10:00:00'), + note: 'Looks right' +}; + +const APPROVED: ApprovalRequestDetailsModel = { request: { ...REQUEST, status: ApprovalRequestStatus.APPROVED }, decision: DECISION }; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [ApprovalRequestComponent] +}) +class HostComponent { + readonly requestId: InputSignal = input('request-1'); +} + +// what the api sends: json, whose dates are strings. +function toJson(value: unknown): object { + return JSON.parse(JSON.stringify(value)) as object; +} + +async function settle(fixture: ComponentFixture): Promise { + TestBed.tick(); + await new Promise(resolve => setTimeout(resolve)); + await fixture.whenStable(); +} + +async function render(details: ApprovalRequestDetailsModel = PENDING): Promise<[ComponentFixture, HTMLElement]> { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + TestBed.tick(); + TestBed.inject(HttpTestingController).expectOne({ method: 'GET', url: '/api/approval-requests/request-1' }) + .flush(toJson(details)); + await settle(fixture); + return [fixture, fixture.nativeElement as HTMLElement]; +} + +function findDialog(): HTMLDialogElement | undefined { + return [...document.querySelectorAll('dialog[open]')].at(-1) ?? undefined; +} + +// presses a button of the review, and answers the question it asks. +async function decide(fixture: ComponentFixture, root: HTMLElement, button: string, answer: string): Promise { + FormTestingUtilities.click(root.querySelector('section:last-of-type') ?? root, button); + const dialog: HTMLDialogElement = await vi.waitFor(() => { + TestBed.tick(); + const opened: HTMLDialogElement | undefined = findDialog(); + if (opened == undefined) { + throw new Error('No question was asked.'); + } + return opened; + }); + FormTestingUtilities.click(dialog, answer); + await settle(fixture); +} + +function typeNote(root: HTMLElement, note: string): void { + const textarea: HTMLTextAreaElement | null = root.querySelector('textarea'); + if (textarea == undefined) { + throw new Error('There is no note.'); + } + textarea.value = note; + textarea.dispatchEvent(new Event('input')); +} + +// the texts of an element, one after the other, as a screen reader reads its elements. +function getText(element: Element | null): string { + if (element == undefined) { + return ''; + } + const walker: TreeWalker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT); + const texts: string[] = []; + while (walker.nextNode()) { + texts.push(walker.currentNode.textContent ?? ''); + } + return texts.join(' ').replaceAll(/\s+/g, ' ') + .trim(); +} + +describe('ApprovalRequestComponent', () => { + let removeModalDialogs: () => void; + + beforeEach(() => { + removeModalDialogs = DialogTestingUtilities.addModalDialogs(); + TestBed.configureTestingModule({ + providers: [provideHttpClient(), provideHttpClientTesting(), provideApprovalRequestsConfig({ baseUrl: '/api/approval-requests' })] + }); + }); + + afterEach(() => { + TestBed.inject(HttpTestingController).verify(); + removeModalDialogs(); + for (const dialog of document.querySelectorAll('ui-dialog')) { + dialog.remove(); + } + }); + + test('shows what the action does, who proposed it and why, and the values it changes on each row', async () => { + const [, root] = await render(); + + expect(getText(root.querySelector('h1'))).toBe('Close the task "Write the release notes"'); + expect(getText(root.querySelector('ui-badge'))).toBe('Pending'); + expect(getText(root.querySelector('dl'))).toBe([ + 'Action tasks.close', + 'Proposed by task-cleanup (System)', + 'Proposed at 11/24/2026, 09:30 AM', + 'Expires at 12/01/2026, 09:30 AM', + 'Reason The release is out' + ].join(' ')); + expect([...root.querySelectorAll('ngx-changes')].map(changes => [...changes.querySelectorAll('pre')].map(pre => pre.textContent))) + .toEqual([['open', 'done'], ['-', 'Closed with the release']]); + expect([...root.querySelectorAll('section p.text-label')].map(row => getText(row))).toEqual(['task task-1', 'comment new']); + }); + + test('approves the request with the note after confirming, and shows the outcome', async () => { + const [fixture, root] = await render(); + typeNote(root, ' Looks right '); + + await decide(fixture, root, 'Approve', 'Approve'); + const request: TestRequest = TestBed.inject(HttpTestingController).expectOne({ method: 'POST', url: '/api/approval-requests/request-1/approve' }); + expect(request.request.body).toEqual({ note: 'Looks right' }); + request.flush(toJson(APPROVED)); + await settle(fixture); + + expect(getText(root.querySelector('ui-badge'))).toBe('Approved'); + expect(getText(root.querySelector('ui-callout'))).toBe([ + 'Success Approved The action ran.', + 'Decided by user-2 (User)', + 'Decided at 11/24/2026, 10:00 AM', + 'Note Looks right' + ].join(' ')); + expect(root.querySelectorAll('section:last-of-type button')).toHaveLength(0); + // the buttons that had the focus are gone, so the outcome takes it + expect(document.activeElement).toBe(root.querySelector('[tabindex="-1"]')); + }); + + test('shows the message of the api when it refuses the approval, and keeps the request to decide', async () => { + const [fixture, root] = await render(); + + await decide(fixture, root, 'Approve', 'Approve'); + const body: ErrorResponseBody = { + status: 409, + name: 'ConflictError', + message: 'The row task-1 of task changed since the approval request was proposed. Propose the action again.', + paragraphs: ['The row task-1 of task changed since the approval request was proposed. Propose the action again.'] + }; + TestBed.inject(HttpTestingController).expectOne({ method: 'POST', url: '/api/approval-requests/request-1/approve' }) + .flush(body, { status: 409, statusText: 'Conflict' }); + await settle(fixture); + + expect(getText(root.querySelector('[role="alert"]'))).toBe( + 'Error The row task-1 of task changed since the approval request was proposed. Propose the action again.' + ); + expect(getText(root.querySelector('ui-badge'))).toBe('Pending'); + expect([...root.querySelectorAll('section:last-of-type button')].map(button => button.disabled)).toEqual([false, false]); + }); + + test('says that the decision couldn\'t be sent when the api gives no message, like without a connection', async () => { + const [fixture, root] = await render(); + + await decide(fixture, root, 'Reject', 'Reject'); + TestBed.inject(HttpTestingController).expectOne({ method: 'POST', url: '/api/approval-requests/request-1/reject' }) + .error(new ProgressEvent('error'), { status: 0, statusText: 'Unknown Error' }); + await settle(fixture); + + expect(getText(root.querySelector('[role="alert"]'))).toBe('Error The decision couldn\'t be sent. Please try again.'); + }); + + test('neither approves nor rejects without a confirmation', async () => { + const [fixture, root] = await render(); + + await decide(fixture, root, 'Approve', 'Cancel'); + expect(findDialog()).toBeUndefined(); + await decide(fixture, root, 'Reject', 'Cancel'); + + TestBed.inject(HttpTestingController).expectNone(({ method }) => method === 'POST'); + expect(getText(root.querySelector('ui-badge'))).toBe('Pending'); + }); + + test('shows the outcome of a decided request instead of asking for a decision', async () => { + const [, root] = await render({ + request: { ...REQUEST, status: ApprovalRequestStatus.FAILED }, + decision: { ...DECISION, error: 'The task is locked by its project.' } + }); + + expect(root.querySelector('textarea')).toBeNull(); + expect(getText(root.querySelector('ui-callout'))).toBe([ + 'Error Failed The action failed. Nothing it wrote was kept.', + 'Decided by user-2 (User)', + 'Decided at 11/24/2026, 10:00 AM', + 'Note Looks right', + 'Error The task is locked by its project.' + ].join(' ')); + }); + + test('says when the request couldn\'t be loaded', async () => { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + TestBed.tick(); + TestBed.inject(HttpTestingController).expectOne({ method: 'GET', url: '/api/approval-requests/request-1' }) + .flush('Not found', { status: 404, statusText: 'Not Found' }); + await settle(fixture); + + expect(getText((fixture.nativeElement as HTMLElement).querySelector('[role="alert"]'))).toBe('The approval request couldn\'t be loaded.'); + }); +}); \ No newline at end of file diff --git a/projects/ngx-approval-requests/approval-request/approval-request.component.ts b/projects/ngx-approval-requests/approval-request/approval-request.component.ts new file mode 100644 index 0000000..7c54c4d --- /dev/null +++ b/projects/ngx-approval-requests/approval-request/approval-request.component.ts @@ -0,0 +1,259 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { afterNextRender, Component, computed, ElementRef, inject, Injector, input, InputSignal, linkedSignal, LOCALE_ID, resource, ResourceRef, Signal, signal, viewChild, WritableSignal } from '@angular/core'; +import { APPROVAL_REQUESTS_CONFIG, ApprovalRequestsConfig, ApprovalRequestService, ApprovalRequestsLabels } from '@service-soft/ngx-approval-requests/api'; +import { ChangeValueUtilities } from '@service-soft/ngx-change-sets/changes'; +import { ErrorResponseUtilities } from '@service-soft/ngx-error-handling/error-response'; +import { BadgeComponent } from '@service-soft/ui/badge'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent, CalloutTone } from '@service-soft/ui/callout'; +import { DataListComponent, DataListItem } from '@service-soft/ui/data-list'; +import { ConfirmDialogComponent, ConfirmDialogData, DialogService } from '@service-soft/ui/dialog'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { InputTextareaComponent } from '@service-soft/ui/input-textarea'; +import { LoadingDirective } from '@service-soft/ui/loading'; +import { ApprovalActorKind, ApprovalDecisionInputModel, ApprovalDecisionModel, ApprovalRequestDetailsModel, ApprovalRequestStatus, ErrorResponseBody } from 'zibri-contract'; + +import { ApprovalRequestChangesComponent } from './approval-request-changes.component'; +import { ApprovalRequestView } from './approval-request-view.model'; + +// a decided request is told by its outcome; pending is never shown as one. +const OUTCOME_TONES: Record = { + [ApprovalRequestStatus.PENDING]: 'info', + [ApprovalRequestStatus.APPROVED]: 'success', + [ApprovalRequestStatus.REJECTED]: 'neutral', + [ApprovalRequestStatus.EXPIRED]: 'neutral', + [ApprovalRequestStatus.FAILED]: 'error' +}; + +// the sections are headed one level below the review, and a review of level 6 has no level below. +const SECTION_LEVELS: Record = { 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 6 }; + +/** + * The names of who proposed and who decided a request, as the ApprovalRequestService resolves them. + */ +type ActorNames = { + /** + * Who or what proposed it. + */ + proposedBy: string, + /** + * Who or what decided it, undefined while nobody did. + */ + decidedBy: string | undefined +}; + +/** + * The review of an approval request of the api of provideApprovalRequestsConfig: what it does, who or what proposed it + * and why, and the values it would change, each before and after. While it waits for a decision, the user approves or + * rejects it with a note, after confirming either, and then sees the outcome, or the message of the api when it + * refuses the decision, like for a request whose rows changed since it was proposed. Use it as the component of a route + * with the id as the parameter requestId: `{ path: 'approval-requests/:requestId', loadComponent: … }` with + * `withComponentInputBinding()`. + */ +@Component({ + selector: 'ngx-approval-request', + templateUrl: './approval-request.component.html', + imports: [ + ApprovalRequestChangesComponent, + BadgeComponent, + ButtonComponent, + CalloutComponent, + DataListComponent, + HeadingComponent, + InputTextareaComponent, + LoadingDirective + ], + host: { class: 'block' } +}) +export class ApprovalRequestComponent { + private readonly config: ApprovalRequestsConfig = inject(APPROVAL_REQUESTS_CONFIG); + private readonly approvalRequestService: ApprovalRequestService = inject(ApprovalRequestService); + private readonly dialogService: DialogService = inject(DialogService); + private readonly locale: string = inject(LOCALE_ID); + private readonly injector: Injector = inject(Injector); + + private readonly outcome: Signal | undefined> = viewChild>('outcome'); + + /** + * The id of the request to review. + */ + readonly requestId: InputSignal = input.required(); + + /** + * The texts of the review. + */ + protected readonly labels: ApprovalRequestsLabels = this.config.labels; + + /** + * The level of the heading of the review. + */ + protected readonly headingLevel: HeadingLevel = this.config.headingLevel; + + /** + * The level of the headings of its sections, one below. + */ + protected readonly sectionLevel: HeadingLevel = SECTION_LEVELS[this.config.headingLevel]; + + /** + * The note the user sends with the decision. It starts over with another request. + */ + protected readonly note: WritableSignal = linkedSignal({ source: this.requestId, computation: () => '' }); + + /** + * Whether a decision is being sent. + */ + protected readonly deciding: WritableSignal = signal(false); + + /** + * Why the api refused the last decision, its paragraphs one per line. Undefined while it refused none, and with + * another request. + */ + protected readonly decisionError: WritableSignal = linkedSignal({ + source: this.requestId, + computation: () => undefined + }); + + private readonly loaded: ResourceRef = resource({ + params: () => this.requestId(), + loader: async ({ params }) => await this.approvalRequestService.resolveRequest(params) + }); + + /** + * Whether the request is loading. + */ + protected readonly isLoading: Signal = computed(() => this.loaded.isLoading()); + + /** + * Whether the request couldn't be loaded. + */ + protected readonly loadingFailed: Signal = computed(() => this.loaded.error() != undefined); + + // the request as it was loaded, and as a decision answered it afterwards. + private readonly details: WritableSignal = linkedSignal(() => { + return this.loaded.hasValue() ? this.loaded.value() : undefined; + }); + + private readonly actorNames: ResourceRef = resource({ + params: () => this.details(), + loader: async ({ params }) => await this.resolveActorNames(params) + }); + + /** + * The request as the review shows it, undefined until it is loaded. + */ + protected readonly view: Signal = computed(() => { + const details: ApprovalRequestDetailsModel | undefined = this.details(); + return details == undefined ? undefined : this.toView(details); + }); + + /** + * Approves the request with the note, after the user confirmed it. + */ + protected async approve(): Promise { + await this.decide(this.config.approveConfirmDialogData, async (id, decision) => { + return await this.approvalRequestService.approve(id, decision); + }); + } + + /** + * Rejects the request with the note, after the user confirmed it. + */ + protected async reject(): Promise { + await this.decide(this.config.rejectConfirmDialogData, async (id, decision) => { + return await this.approvalRequestService.reject(id, decision); + }); + } + + private async decide( + question: ConfirmDialogData, + send: (id: string, decision: ApprovalDecisionInputModel) => Promise + ): Promise { + const confirmed: boolean | undefined = await this.dialogService.open(ConfirmDialogComponent, question).closed; + if (confirmed !== true) { + return; + } + this.deciding.set(true); + this.decisionError.set(undefined); + try { + const note: string = this.note().trim(); + this.details.set(await send(this.requestId(), note ? { note } : {})); + // the buttons are gone with the pending request, which would leave focus nowhere. + afterNextRender(() => this.outcome()?.nativeElement.focus(), { injector: this.injector }); + } + catch (error) { + // a refusal of the api is the answer to the decision, like a request that changed since it was proposed, or + // a second factor the user didn't give. Anything else is a mistake, which goes on to the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.decisionError.set(this.resolveErrorMessage(error)); + } + finally { + this.deciding.set(false); + } + } + + private resolveErrorMessage(error: HttpErrorResponse): string { + const body: ErrorResponseBody | undefined = ErrorResponseUtilities.findErrorResponseBody(error); + if (body == undefined) { + return this.labels.decisionFailed; + } + return body.paragraphs.length ? body.paragraphs.join('\n') : body.message; + } + + private async resolveActorNames(details: ApprovalRequestDetailsModel | undefined): Promise { + if (details == undefined) { + return undefined; + } + const decision: ApprovalDecisionModel | null = details.decision; + const [proposedBy, decidedBy] = await Promise.all([ + this.approvalRequestService.resolveActorName(details.request.proposedBy, details.request.proposedByKind), + decision == undefined ? undefined : this.approvalRequestService.resolveActorName(decision.decidedBy, decision.decidedByKind) + ]); + return { proposedBy, decidedBy }; + } + + private toView(details: ApprovalRequestDetailsModel): ApprovalRequestView { + const { request, decision } = details; + // the names may come from a request, until then the actor shows that something is still coming. + const names: ActorNames | undefined = this.actorNames.hasValue() ? this.actorNames.value() : undefined; + const items: DataListItem[] = [ + { label: this.labels.action, value: this.config.actions[request.action] ?? request.action }, + { label: this.labels.proposedBy, value: this.getActor(names?.proposedBy, request.proposedByKind) }, + { label: this.labels.proposedAt, value: this.formatDate(request.proposedAt) }, + { label: this.labels.expiresAt, value: this.formatDate(request.expiresAt) }, + { label: this.labels.reason, value: request.reason ?? undefined } + ]; + return { + summary: request.summary, + status: this.labels.statuses[request.status], + statusColor: this.config.statusColors[request.status], + isPending: request.status === ApprovalRequestStatus.PENDING, + outcome: this.labels.outcomes[request.status], + outcomeTone: OUTCOME_TONES[request.status], + items: this.findShownItems(items), + rows: request.changes.map(change => ({ entity: change.entity, id: change.id ?? this.labels.newRow, changes: change.changes })), + decisionItems: decision == undefined + ? [] + : this.findShownItems([ + { label: this.labels.decidedBy, value: this.getActor(names?.decidedBy, decision.decidedByKind) }, + { label: this.labels.decidedAt, value: this.formatDate(decision.decidedAt) }, + { label: this.labels.note, value: decision.note ?? undefined }, + { label: this.labels.error, value: decision.error ?? undefined } + ]) + }; + } + + // the data list shows the label of a value that isn't there, like a request without a reason. + private findShownItems(items: DataListItem[]): DataListItem[] { + return items.filter(item => item.value != undefined); + } + + private getActor(name: string | undefined, kind: ApprovalActorKind): string { + return `${name ?? '…'} (${this.labels.actorKinds[kind]})`; + } + + private formatDate(date: Date): string { + return ChangeValueUtilities.formatDate(date, this.config.dateFormat, this.locale); + } +} \ No newline at end of file diff --git a/projects/ngx-approval-requests/approval-request/approval-request.stories.ts b/projects/ngx-approval-requests/approval-request/approval-request.stories.ts new file mode 100644 index 0000000..12b5ca5 --- /dev/null +++ b/projects/ngx-approval-requests/approval-request/approval-request.stories.ts @@ -0,0 +1,121 @@ +import { HttpErrorResponse, HttpEvent, HttpInterceptorFn, HttpRequest, HttpResponse, provideHttpClient, withInterceptors } from '@angular/common/http'; +import { provideApprovalRequestsConfig } from '@service-soft/ngx-approval-requests/api'; +import { applicationConfig, Meta, StoryObj } from '@storybook/angular'; +import { Observable, of, throwError } from 'rxjs'; +import { ApprovalActorKind, ApprovalDecisionModel, ApprovalDecisionType, ApprovalRequestDetailsModel, ApprovalRequestModel, ApprovalRequestStatus, ErrorResponseBody } from 'zibri-contract'; + +import { ApprovalRequestComponent } from './approval-request.component'; + +const REQUEST_URL: string = '/api/approval-requests/request-1/approve'; + +// a row it changes with every kind of value, and one it creates. +const REQUEST: ApprovalRequestModel = { + id: 'request-1', + tenantId: 'tenant-1', + action: 'tasks.close', + input: { taskId: '0b6d6a7e-61a4-4c2f-9d0e-5f2b8c1e7a90' }, + reason: 'The release is out, so nothing is left to do on it.', + summary: 'Close the task "Write the release notes"', + changes: [ + { + entity: 'task', + id: '0b6d6a7e-61a4-4c2f-9d0e-5f2b8c1e7a90', + changes: [ + { key: 'status', previousValue: 'open', newValue: 'done' }, + { key: 'closedAt', previousValue: undefined, newValue: '2026-11-24T10:00:00' }, + { key: 'labels', previousValue: ['release'], newValue: ['release', 'done'] } + ] + }, + // eslint-disable-next-line unicorn/no-null -- the api sends null for a row the action creates + { entity: 'comment', id: null, changes: [{ key: 'text', newValue: 'Closed with the release.' }] } + ], + preconditions: [], + proposedBy: 'task-cleanup', + proposedByKind: ApprovalActorKind.SYSTEM, + proposedAt: new Date('2026-11-24T09:30:00'), + status: ApprovalRequestStatus.PENDING, + expiresAt: new Date('2026-12-01T09:30:00') +}; + +const DECISION: ApprovalDecisionModel = { + id: 'decision-1', + tenantId: 'tenant-1', + chainSequence: 1, + chainHash: 'hash', + requestId: 'request-1', + decision: ApprovalDecisionType.APPROVED, + decidedBy: 'jane@example.com', + decidedByKind: ApprovalActorKind.USER, + decidedAt: new Date('2026-11-24T10:00:00'), + note: 'Looks right' +}; + +// eslint-disable-next-line unicorn/no-null -- the api answers null while there is no decision +const PENDING: ApprovalRequestDetailsModel = { request: REQUEST, decision: null }; + +const APPROVED: ApprovalRequestDetailsModel = { request: { ...REQUEST, status: ApprovalRequestStatus.APPROVED }, decision: DECISION }; + +const CONFLICT_MESSAGE: string = 'The row 0b6d6a7e-61a4-4c2f-9d0e-5f2b8c1e7a90 of task changed since the approval request was proposed. ' + + 'Propose the action again.'; + +const CONFLICT: ErrorResponseBody = { status: 409, name: 'ConflictError', message: CONFLICT_MESSAGE, paragraphs: [CONFLICT_MESSAGE] }; + +/** + * What the backend of a story answers deciding with. + */ +type DecisionAnswer = (request: HttpRequest) => Observable>; + +// answers the request with the details, and a decision like the routes of the README would. +function provideBackend(details: ApprovalRequestDetailsModel, decide: DecisionAnswer): ReturnType { + const backend: HttpInterceptorFn = request => request.method === 'GET' + ? of(new HttpResponse({ status: 200, body: details })) + : decide(request); + return applicationConfig({ + providers: [provideHttpClient(withInterceptors([backend])), provideApprovalRequestsConfig({ baseUrl: '/api/approval-requests' })] + }); +} + +function answerDecided(request: HttpRequest): Observable> { + const rejected: ApprovalRequestDetailsModel = { + request: { ...REQUEST, status: ApprovalRequestStatus.REJECTED }, + decision: { ...DECISION, decision: ApprovalDecisionType.REJECTED } + }; + return of(new HttpResponse({ status: 200, body: request.url.endsWith('/reject') ? rejected : APPROVED })); +} + +const meta: Meta = { + title: 'Approval requests/Approval request', + component: ApprovalRequestComponent, + render: () => ({ template: '' }) +}; +export default meta; + +type Story = StoryObj; + +// approving or rejecting after confirming shows the outcome. +export const Pending: Story = { + decorators: [provideBackend(PENDING, answerDecided)] +}; + +// approving shows the message of the api, like for a row that changed since. +export const Refused: Story = { + decorators: [provideBackend(PENDING, () => throwError(() => new HttpErrorResponse({ status: 409, error: CONFLICT, url: REQUEST_URL })))] +}; + +export const Approved: Story = { + decorators: [provideBackend(APPROVED, answerDecided)] +}; + +export const Failed: Story = { + decorators: [ + provideBackend({ + request: { ...REQUEST, status: ApprovalRequestStatus.FAILED }, + decision: { ...DECISION, error: 'The task is locked by its project.' } + }, answerDecided) + ] +}; + +export const Expired: Story = { + // eslint-disable-next-line unicorn/no-null -- the api answers null while there is no decision + decorators: [provideBackend({ request: { ...REQUEST, status: ApprovalRequestStatus.EXPIRED }, decision: null }, answerDecided)] +}; \ No newline at end of file diff --git a/projects/ngx-approval-requests/approval-request/ng-package.json b/projects/ngx-approval-requests/approval-request/ng-package.json new file mode 100644 index 0000000..70e0a80 --- /dev/null +++ b/projects/ngx-approval-requests/approval-request/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} \ No newline at end of file diff --git a/projects/ngx-approval-requests/approval-request/public-api.ts b/projects/ngx-approval-requests/approval-request/public-api.ts new file mode 100644 index 0000000..3c793b8 --- /dev/null +++ b/projects/ngx-approval-requests/approval-request/public-api.ts @@ -0,0 +1 @@ +export * from './approval-request.component'; \ No newline at end of file diff --git a/projects/ngx-approval-requests/approval-requests/approval-request-list-item.model.ts b/projects/ngx-approval-requests/approval-requests/approval-request-list-item.model.ts new file mode 100644 index 0000000..0cf1894 --- /dev/null +++ b/projects/ngx-approval-requests/approval-requests/approval-request-list-item.model.ts @@ -0,0 +1,39 @@ +import { BadgeColor } from '@service-soft/ui/badge'; + +/** + * An approval request as the list shows it. + */ +export type ApprovalRequestListItem = { + /** + * The id of the request. + */ + id: string, + /** + * What the action does, which links to the review. + */ + summary: string, + /** + * The commands of the link to the review. + */ + link: string[], + /** + * What the action is called. + */ + action: string, + /** + * What the status is called. + */ + status: string, + /** + * The color of the badge of the status. + */ + statusColor: BadgeColor, + /** + * When it was proposed, formatted. + */ + proposedAt: string, + /** + * When it was proposed, as an ISO string for the datetime of its time element. + */ + proposedAtIso: string +}; \ No newline at end of file diff --git a/projects/ngx-approval-requests/approval-requests/approval-requests.component.html b/projects/ngx-approval-requests/approval-requests/approval-requests.component.html new file mode 100644 index 0000000..eb4554b --- /dev/null +++ b/projects/ngx-approval-requests/approval-requests/approval-requests.component.html @@ -0,0 +1,39 @@ +
+ + @if (actionOptions.length) { + + } +
+@if (requests.error()) { + +} + +
    + @for (request of items(); track request.id) { +
  • +
    + {{ request.status }} + {{ request.action }} + +
    + {{ request.summary }} +
  • + } @empty { +
  • {{ labels.noRequests }}
  • + } +
+ diff --git a/projects/ngx-approval-requests/approval-requests/approval-requests.component.spec.ts b/projects/ngx-approval-requests/approval-requests/approval-requests.component.spec.ts new file mode 100644 index 0000000..70e216e --- /dev/null +++ b/projects/ngx-approval-requests/approval-requests/approval-requests.component.spec.ts @@ -0,0 +1,142 @@ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideRouter } from '@angular/router'; +import { provideApprovalRequestsConfig } from '@service-soft/ngx-approval-requests/api'; +import { FormTestingUtilities } from 'testing/form'; +import { describe, expect, test } from 'vitest'; +import { ApprovalActorKind, ApprovalRequestModel, ApprovalRequestStatus, PaginationResult } from 'zibri-contract'; + +import { ApprovalRequestsComponent } from './approval-requests.component'; + +function createRequest(id: string, action: string, summary: string, status: ApprovalRequestStatus): ApprovalRequestModel { + return { + id, + tenantId: 'tenant-1', + action, + input: {}, + summary, + changes: [], + preconditions: [], + proposedBy: 'task-cleanup', + proposedByKind: ApprovalActorKind.SYSTEM, + proposedAt: new Date('2026-11-24T09:30:00'), + status, + expiresAt: new Date('2026-12-01T09:30:00') + }; +} + +const REQUESTS: ApprovalRequestModel[] = [ + createRequest('request-2', 'tasks.close', 'Close the task "Write the release notes"', ApprovalRequestStatus.PENDING), + createRequest('request-1', 'tasks.archive', 'Archive the project "Website"', ApprovalRequestStatus.PENDING) +]; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [ApprovalRequestsComponent] +}) +class HostComponent {} + +// what the api sends: json, whose dates are strings. +function toJson(value: unknown): object { + return JSON.parse(JSON.stringify(value)) as object; +} + +// answers the request for a page of requests, and renders it. +async function flushRequests( + fixture: ComponentFixture, + page: PaginationResult = { items: REQUESTS, totalAmount: REQUESTS.length } +): Promise { + // a request that is still open keeps the fixture from becoming stable, so it is answered first. + TestBed.tick(); + const request: TestRequest = TestBed.inject(HttpTestingController) + .expectOne(({ method, url }) => method === 'GET' && url === '/api/approval-requests'); + request.flush(toJson(page)); + await fixture.whenStable(); + return request; +} + +async function render(page?: PaginationResult): Promise<[ComponentFixture, HTMLElement, TestRequest]> { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + provideRouter([]), + provideApprovalRequestsConfig({ + baseUrl: '/api/approval-requests', + reviewPath: '/approval-requests', + actions: { 'tasks.close': 'Close a task', 'tasks.label': 'Label a task' } + }) + ] + }); + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + const request: TestRequest = await flushRequests(fixture, page); + return [fixture, fixture.nativeElement as HTMLElement, request]; +} + +function getQuery(request: TestRequest): string { + return request.request.params.toString(); +} + +// opens a select by its label and picks an option, like a user does. +async function choose(fixture: ComponentFixture, root: HTMLElement, label: string, option: string): Promise { + const labelElement: HTMLLabelElement | undefined = [...root.querySelectorAll('label')].find(candidate => candidate.textContent.trim() === label); + const combobox: HTMLElement | null = root.querySelector(`[role="combobox"][aria-labelledby="${labelElement?.id ?? ''}"]`); + combobox?.click(); + await fixture.whenStable(); + [...root.querySelectorAll('[role="option"]')].find(candidate => candidate.textContent.trim() === option) + ?.click(); +} + +describe('ApprovalRequestsComponent', () => { + test('loads the pending requests, and shows each with its status, action and date, linking to its review', async () => { + const [, root, request] = await render(); + + expect(getQuery(request)).toBe('page=1&limit=10&status=PENDING'); + const items: HTMLLIElement[] = [...root.querySelectorAll('li')]; + // the parts of each request, which are separated by a gap instead of spaces. + expect(items.map(item => [...item.querySelectorAll('ui-badge, span, time, a')].map(part => part.textContent.trim()).join(' '))).toEqual([ + 'Pending Close a task 11/24/2026, 09:30 AM Close the task "Write the release notes"', + // an action the config doesn't name shows by its name + 'Pending tasks.archive 11/24/2026, 09:30 AM Archive the project "Website"' + ]); + expect(items[0]?.querySelector('a')?.getAttribute('href')).toBe('/approval-requests/request-2'); + expect(items[0]?.querySelector('time')?.getAttribute('datetime')).toBe(new Date('2026-11-24T09:30:00').toISOString()); + }); + + test('filters by status and action, and starts over at the first page when a filter changes', async () => { + const [fixture, root] = await render({ items: REQUESTS, totalAmount: 25 }); + + FormTestingUtilities.click(root, '3'); + expect(getQuery(await flushRequests(fixture))).toBe('page=3&limit=10&status=PENDING'); + + await choose(fixture, root, 'Status', 'All statuses'); + expect(getQuery(await flushRequests(fixture))).toBe('page=1&limit=10'); + + await choose(fixture, root, 'Status', 'Rejected'); + expect(getQuery(await flushRequests(fixture))).toBe('page=1&limit=10&status=REJECTED'); + + await choose(fixture, root, 'Action', 'Label a task'); + expect(getQuery(await flushRequests(fixture, { items: [], totalAmount: 0 }))).toBe('page=1&limit=10&status=REJECTED&action=tasks.label'); + expect(FormTestingUtilities.getText(root, 'li')).toBe('No approval request matches the filters.'); + expect(root.querySelector('nav')).toBeNull(); + }); + + test('says when the requests couldn\'t be loaded', async () => { + TestBed.configureTestingModule({ + providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([]), provideApprovalRequestsConfig({ baseUrl: '/api/approval-requests' })] + }); + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + TestBed.tick(); + TestBed.inject(HttpTestingController).expectOne(({ url }) => url === '/api/approval-requests') + .flush('Unavailable', { status: 503, statusText: 'Service Unavailable' }); + await fixture.whenStable(); + + const root: HTMLElement = fixture.nativeElement as HTMLElement; + expect(FormTestingUtilities.getText(root, '[role="alert"]')).toBe('The approval requests couldn\'t be loaded.'); + // without actions in the config, there is no filter of the action + expect([...root.querySelectorAll('label')].map(label => label.textContent.trim())).toEqual(['Status']); + }); +}); \ No newline at end of file diff --git a/projects/ngx-approval-requests/approval-requests/approval-requests.component.ts b/projects/ngx-approval-requests/approval-requests/approval-requests.component.ts new file mode 100644 index 0000000..043ee27 --- /dev/null +++ b/projects/ngx-approval-requests/approval-requests/approval-requests.component.ts @@ -0,0 +1,110 @@ +import { Component, computed, inject, linkedSignal, LOCALE_ID, resource, ResourceRef, Signal, signal, WritableSignal } from '@angular/core'; +import { RouterLink } from '@angular/router'; +import { APPROVAL_REQUESTS_CONFIG, ApprovalRequestsConfig, ApprovalRequestService, ApprovalRequestsLabels, ApprovalRequestsQuery } from '@service-soft/ngx-approval-requests/api'; +import { ChangeValueUtilities } from '@service-soft/ngx-change-sets/changes'; +import { BadgeComponent } from '@service-soft/ui/badge'; +import { InputOption } from '@service-soft/ui/input'; +import { InputSelectComponent } from '@service-soft/ui/input-select'; +import { LinkComponent } from '@service-soft/ui/link'; +import { PaginationComponent } from '@service-soft/ui/pagination'; +import { ApprovalRequestModel, ApprovalRequestStatus, PaginationResult } from 'zibri-contract'; + +import { ApprovalRequestListItem } from './approval-request-list-item.model'; + +const EMPTY_PAGE: PaginationResult = { items: [], totalAmount: 0 }; + +/** + * The approval requests of the api of provideApprovalRequestsConfig, the latest proposed first, a page at a time: + * ``. It shows the pending ones at first, and filters by status and, with the actions of the + * config, by action. Each request links to its review, at its id below the reviewPath of the config. + */ +@Component({ + selector: 'ngx-approval-requests', + templateUrl: './approval-requests.component.html', + imports: [BadgeComponent, InputSelectComponent, LinkComponent, PaginationComponent, RouterLink], + host: { class: 'block' } +}) +export class ApprovalRequestsComponent { + private readonly config: ApprovalRequestsConfig = inject(APPROVAL_REQUESTS_CONFIG); + + private readonly approvalRequestService: ApprovalRequestService = inject(ApprovalRequestService); + + private readonly locale: string = inject(LOCALE_ID); + + /** + * The texts of the list. + */ + protected readonly labels: ApprovalRequestsLabels = this.config.labels; + + /** + * How many requests a page has. + */ + protected readonly pageSize: number = this.config.pageSize; + + /** + * The statuses to filter by. + */ + protected readonly statusOptions: InputOption[] = Object.values(ApprovalRequestStatus) + .map(status => ({ label: this.labels.statuses[status], value: status })); + + /** + * The actions to filter by, from the config. Without any, there is no filter of the action. + */ + protected readonly actionOptions: InputOption[] = Object.entries(this.config.actions) + .map(([value, label]) => ({ label, value })); + + /** + * The status whose requests show, undefined for every status. + */ + protected readonly status: WritableSignal = signal(ApprovalRequestStatus.PENDING); + + /** + * The action whose requests show, undefined for every action. + */ + protected readonly action: WritableSignal = signal(undefined); + + /** + * The page that shows. It starts over when a filter changes. + */ + protected readonly page: WritableSignal = linkedSignal({ + source: () => [this.status(), this.action()], + computation: () => 1 + }); + + /** + * The page of requests from the api. + */ + protected readonly requests: ResourceRef> = resource({ + params: (): ApprovalRequestsQuery => ({ page: this.page(), limit: this.pageSize, status: this.status(), action: this.action() }), + loader: async ({ params }) => await this.approvalRequestService.resolveRequests(params), + defaultValue: EMPTY_PAGE + }); + + // reading the value of a resource that failed throws. + private readonly result: Signal> = computed(() => { + return this.requests.hasValue() ? this.requests.value() : EMPTY_PAGE; + }); + + /** + * The requests of the page. + */ + protected readonly items: Signal = computed(() => this.result().items.map(request => this.toItem(request))); + + /** + * How many requests match the filters on all pages together. + */ + protected readonly totalAmount: Signal = computed(() => this.result().totalAmount); + + private toItem(request: ApprovalRequestModel): ApprovalRequestListItem { + return { + id: request.id, + summary: request.summary, + link: this.config.reviewPath ? [this.config.reviewPath, request.id] : [request.id], + action: this.config.actions[request.action] ?? request.action, + status: this.labels.statuses[request.status], + statusColor: this.config.statusColors[request.status], + proposedAt: ChangeValueUtilities.formatDate(request.proposedAt, this.config.dateFormat, this.locale), + proposedAtIso: request.proposedAt.toISOString() + }; + } +} \ No newline at end of file diff --git a/projects/ngx-approval-requests/approval-requests/approval-requests.stories.ts b/projects/ngx-approval-requests/approval-requests/approval-requests.stories.ts new file mode 100644 index 0000000..291a088 --- /dev/null +++ b/projects/ngx-approval-requests/approval-requests/approval-requests.stories.ts @@ -0,0 +1,100 @@ +import { HttpErrorResponse, HttpEvent, HttpInterceptorFn, HttpRequest, HttpResponse, provideHttpClient, withInterceptors } from '@angular/common/http'; +import { provideRouter } from '@angular/router'; +import { provideApprovalRequestsConfig } from '@service-soft/ngx-approval-requests/api'; +import { applicationConfig, Meta, StoryObj } from '@storybook/angular'; +import { Observable, of, throwError } from 'rxjs'; +import { ApprovalActorKind, ApprovalRequestModel, ApprovalRequestStatus, PaginationResult } from 'zibri-contract'; + +import { ApprovalRequestsComponent } from './approval-requests.component'; + +const CLOSE: string = 'tasks.close'; +const LABEL: string = 'tasks.label'; +const SEND: string = 'invoices.send'; + +const ACTIONS: Record = { [CLOSE]: 'Close a task', [LABEL]: 'Label a task', [SEND]: 'Send an invoice' }; + +function createRequest(id: number, action: string, summary: string, status: ApprovalRequestStatus): ApprovalRequestModel { + const proposedAt: Date = new Date(Date.UTC(2026, 10, 24, 9, 30) - (id * 3_600_000)); + return { + id: `request-${id}`, + tenantId: 'tenant-1', + action, + input: {}, + summary, + changes: [], + preconditions: [], + proposedBy: 'user-1', + proposedByKind: ApprovalActorKind.USER, + proposedAt, + status, + expiresAt: new Date(proposedAt.getTime() + (7 * 86_400_000)) + }; +} + +// every status and action, newest first. +const REQUESTS: ApprovalRequestModel[] = [ + createRequest(1, CLOSE, 'Close the task "Write the release notes"', ApprovalRequestStatus.PENDING), + createRequest(2, LABEL, 'Label the task "Fix the login" as urgent', ApprovalRequestStatus.PENDING), + createRequest(3, SEND, 'Send the invoice 2026-0142 to Example Ltd., whose total needs a second look', ApprovalRequestStatus.PENDING), + createRequest(4, CLOSE, 'Close the task "Plan the sprint"', ApprovalRequestStatus.APPROVED), + createRequest(5, LABEL, 'Label the task "Update the docs" as done', ApprovalRequestStatus.REJECTED), + createRequest(6, SEND, 'Send the invoice 2026-0139 to Example Ltd.', ApprovalRequestStatus.FAILED), + createRequest(7, CLOSE, 'Close the task "Old idea"', ApprovalRequestStatus.EXPIRED) +]; + +// more pending requests than fit on a page. +const MANY_REQUESTS: ApprovalRequestModel[] = Array.from({ length: 35 }, (_, index) => { + return createRequest(index + 1, CLOSE, `Close the task "Task ${index + 1}"`, ApprovalRequestStatus.PENDING); +}); + +// answers a page of requests like the routes of the README: filtered, the latest proposed first. +function answerPage(requests: ApprovalRequestModel[], request: HttpRequest): PaginationResult { + const status: string | null = request.params.get('status'); + const action: string | null = request.params.get('action'); + const page: number = Number(request.params.get('page')); + const limit: number = Number(request.params.get('limit')); + const matching: ApprovalRequestModel[] = requests + .filter(candidate => status == undefined || candidate.status === status) + .filter(candidate => action == undefined || candidate.action === action); + return { items: matching.slice((page - 1) * limit, page * limit), totalAmount: matching.length }; +} + +function provideBackend(answer: (request: HttpRequest) => Observable>): ReturnType { + const backend: HttpInterceptorFn = request => answer(request); + return applicationConfig({ + providers: [ + provideHttpClient(withInterceptors([backend])), + provideRouter([]), + provideApprovalRequestsConfig({ baseUrl: '/api/approval-requests', reviewPath: '/approval-requests', actions: ACTIONS }) + ] + }); +} + +function respondWith(requests: ApprovalRequestModel[]): (request: HttpRequest) => Observable> { + return request => of(new HttpResponse({ status: 200, body: answerPage(requests, request) })); +} + +const meta: Meta = { + title: 'Approval requests/Approval requests', + component: ApprovalRequestsComponent, + render: () => ({ template: '' }) +}; +export default meta; + +type Story = StoryObj; + +export const Default: Story = { + decorators: [provideBackend(respondWith(REQUESTS))] +}; + +export const ManyRequests: Story = { + decorators: [provideBackend(respondWith(MANY_REQUESTS))] +}; + +export const NoRequests: Story = { + decorators: [provideBackend(respondWith([]))] +}; + +export const LoadingFailed: Story = { + decorators: [provideBackend(() => throwError(() => new HttpErrorResponse({ status: 503, url: '/api/approval-requests' })))] +}; \ No newline at end of file diff --git a/projects/ngx-approval-requests/approval-requests/ng-package.json b/projects/ngx-approval-requests/approval-requests/ng-package.json new file mode 100644 index 0000000..70e0a80 --- /dev/null +++ b/projects/ngx-approval-requests/approval-requests/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} \ No newline at end of file diff --git a/projects/ngx-approval-requests/approval-requests/public-api.ts b/projects/ngx-approval-requests/approval-requests/public-api.ts new file mode 100644 index 0000000..50f3309 --- /dev/null +++ b/projects/ngx-approval-requests/approval-requests/public-api.ts @@ -0,0 +1 @@ +export * from './approval-requests.component'; \ No newline at end of file diff --git a/projects/ngx-approval-requests/locale/messages.de.xlf b/projects/ngx-approval-requests/locale/messages.de.xlf new file mode 100644 index 0000000..0ac2e3b --- /dev/null +++ b/projects/ngx-approval-requests/locale/messages.de.xlf @@ -0,0 +1,195 @@ + + + + + + Action + Aktion + + + Action + Aktion + + + Policy + Regel + + + System + System + + + User + Benutzer + + + All actions + Alle Aktionen + + + All statuses + Alle Status + + + Approve + Genehmigen + + + Cancel + Abbrechen + + + Approve + Genehmigen + + + The action runs right away, in your name. + Die Aktion wird sofort in Ihrem Namen ausgeführt. + + + Approve this request? + Diese Anfrage genehmigen? + + + Changes + Änderungen + + + Decided at + Entschieden am + + + Decided by + Entschieden von + + + Decision + Entscheidung + + + The decision couldn't be sent. Please try again. + Die Entscheidung konnte nicht gesendet werden. Bitte versuchen Sie es erneut. + + + Error + Fehler + + + Expires at + Läuft ab am + + + Loading the approval request + Die Genehmigungsanfrage wird geladen + + + The approval request couldn't be loaded. + Die Genehmigungsanfrage konnte nicht geladen werden. + + + The approval requests couldn't be loaded. + Die Genehmigungsanfragen konnten nicht geladen werden. + + + new + neu + + + The action changes no stored values. + Die Aktion ändert keine gespeicherten Werte. + + + No approval request matches the filters. + Keine Genehmigungsanfrage passt zu den Filtern. + + + Note + Notiz + + + Sent with your decision, like why you reject it + Wird mit Ihrer Entscheidung gesendet, zum Beispiel warum Sie ablehnen + + + The action ran. + Die Aktion wurde ausgeführt. + + + Nobody decided it in time. The action did not run. + Niemand hat rechtzeitig entschieden. Die Aktion wurde nicht ausgeführt. + + + The action failed. Nothing it wrote was kept. + Die Aktion ist fehlgeschlagen. Nichts, was sie geschrieben hat, wurde behalten. + + + Nothing runs until someone approves it. + Nichts wird ausgeführt, bis jemand die Anfrage genehmigt. + + + The action did not run. + Die Aktion wurde nicht ausgeführt. + + + Pages of the approval requests + Seiten der Genehmigungsanfragen + + + Proposed at + Vorgeschlagen am + + + Proposed by + Vorgeschlagen von + + + Reason + Begründung + + + Reject + Ablehnen + + + Cancel + Abbrechen + + + Reject + Ablehnen + + + The action won't run. This can't be undone. + Die Aktion wird nicht ausgeführt. Das kann nicht rückgängig gemacht werden. + + + Reject this request? + Diese Anfrage ablehnen? + + + Status + Status + + + Approved + Genehmigt + + + Expired + Abgelaufen + + + Failed + Fehlgeschlagen + + + Pending + Offen + + + Rejected + Abgelehnt + + + + diff --git a/projects/ngx-approval-requests/ng-package.json b/projects/ngx-approval-requests/ng-package.json new file mode 100644 index 0000000..3848328 --- /dev/null +++ b/projects/ngx-approval-requests/ng-package.json @@ -0,0 +1,8 @@ +{ + "$schema": "../../node_modules/ng-packagr/ng-package.schema.json", + "assets": ["tailwind.css", "locale/messages.de.xlf", "CHANGELOG.md"], + "dest": "../../dist/ngx-approval-requests", + "lib": { + "entryFile": "src/public-api.ts" + } +} \ No newline at end of file diff --git a/projects/ngx-approval-requests/package.json b/projects/ngx-approval-requests/package.json new file mode 100644 index 0000000..8bef448 --- /dev/null +++ b/projects/ngx-approval-requests/package.json @@ -0,0 +1,37 @@ +{ + "name": "@service-soft/ngx-approval-requests", + "version": "22.4.0", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/Service-Soft/angular-libraries.git", + "directory": "projects/ngx-approval-requests" + }, + "publishConfig": { + "access": "public" + }, + "dependencies": { + "tslib": "^2.3.0" + }, + "exports": { + ".": { + "style": "./tailwind.css" + } + }, + "peerDependencies": { + "@angular/aria": "^22.2.0", + "@angular/common": "^22.2.0", + "@angular/core": "^22.2.0", + "@angular/localize": "^22.2.0", + "@angular/router": "^22.2.0", + "@service-soft/ngx-change-sets": "^22.4.0", + "@service-soft/ngx-error-handling": "^22.4.0", + "@service-soft/ui": "^22.4.0", + "tailwindcss": "^4.3.3", + "zibri-contract": "^3.3.0" + }, + "sideEffects": false, + "translations": { + "de": "./locale/messages.de.xlf" + } +} \ No newline at end of file diff --git a/projects/ngx-approval-requests/src/public-api.ts b/projects/ngx-approval-requests/src/public-api.ts new file mode 100644 index 0000000..5e22aba --- /dev/null +++ b/projects/ngx-approval-requests/src/public-api.ts @@ -0,0 +1,4 @@ +/** + * Every component lives in its own secondary entry point, eg. '@service-soft/ngx-approval-requests/approval-requests'. + */ +export {}; \ No newline at end of file diff --git a/projects/ngx-approval-requests/tailwind.css b/projects/ngx-approval-requests/tailwind.css new file mode 100644 index 0000000..4c7b7e3 --- /dev/null +++ b/projects/ngx-approval-requests/tailwind.css @@ -0,0 +1 @@ +@source "./fesm2022"; diff --git a/projects/ngx-approval-requests/tsconfig.lib.json b/projects/ngx-approval-requests/tsconfig.lib.json new file mode 100644 index 0000000..809fcdd --- /dev/null +++ b/projects/ngx-approval-requests/tsconfig.lib.json @@ -0,0 +1,17 @@ +/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ +/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ +{ + "compilerOptions": { + "declaration": true, + "declarationMap": true, + "outDir": "../../out-tsc/lib", + // the paths of the workspace point to the sources of the other libraries, which the build would then compile + // into this one. Without them, they resolve from node_modules like for a consumer, so ui, ngx-error-handling and + // ngx-change-sets have to be built first. + "paths": {}, + "types": ["@angular/localize"] + }, + "exclude": ["**/*.spec.ts", "**/*.stories.ts"], + "extends": "../../tsconfig.json", + "include": ["**/*.ts"] +} \ No newline at end of file diff --git a/projects/ngx-approval-requests/tsconfig.lib.prod.json b/projects/ngx-approval-requests/tsconfig.lib.prod.json new file mode 100644 index 0000000..ab0b078 --- /dev/null +++ b/projects/ngx-approval-requests/tsconfig.lib.prod.json @@ -0,0 +1,11 @@ +/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ +/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ +{ + "angularCompilerOptions": { + "compilationMode": "partial" + }, + "compilerOptions": { + "declarationMap": false + }, + "extends": "./tsconfig.lib.json" +} \ No newline at end of file diff --git a/projects/ngx-approval-requests/tsconfig.spec.json b/projects/ngx-approval-requests/tsconfig.spec.json new file mode 100644 index 0000000..d1df25e --- /dev/null +++ b/projects/ngx-approval-requests/tsconfig.spec.json @@ -0,0 +1,10 @@ +/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ +/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ +{ + "compilerOptions": { + "outDir": "../../out-tsc/spec", + "types": ["vitest/globals", "@angular/localize"] + }, + "extends": "../../tsconfig.json", + "include": ["**/*.d.ts", "**/*.spec.ts"] +} \ No newline at end of file diff --git a/projects/ngx-auth/CHANGELOG.md b/projects/ngx-auth/CHANGELOG.md new file mode 100644 index 0000000..3048250 --- /dev/null +++ b/projects/ngx-auth/CHANGELOG.md @@ -0,0 +1,26 @@ +# Changelog + +## 22.4.0 + +### Breaking changes +- The peer `zibri-contract` is `^3.3.0`, was `^3.2.0`. +- The login asks the api which login methods it offers, with `GET /login-methods`, each time it shows. An api + without the route (404) keeps the login with a password. +- `AcceptInvitationState` has the new state `'withoutPassword'`, and `AuthPaths`, `AcceptInvitationLabels` and + `LoginLabels` have new keys. Exhaustive switches over the state, and code that builds one of these types completely + by hand, have to add them; the providers take partial configs as before. + +### Features +- Login links: the login offers "Email me a link" next to the password or instead of it, as the api answers, and + `@service-soft/ngx-auth/login-link` logs in with the link. `AuthService.resolveLoginMethods()`, + `requestLoginLink(email)` and `loginWithLink(token)`. Too many requests (429) are shown. +- Invitations without a password: `AuthService.acceptInvitationWithoutPassword(token)`, and the state + `withoutPassword` of `ngx-accept-invitation`, which logs in and continues with the steps of the login. +- `pendingLogin` of `ngx-login`, which continues a login that waits for a step (type `PendingLogin`). +- `@service-soft/ngx-auth/service-accounts`: manages the service accounts of AI assistants and integrations and their + API keys. Needs the optional peer `@angular/aria`. +- The German translation of the texts ships with the package (`locale/messages.de.xlf`). + +### Fixes +- After a login by link or by invitation link, an email code is no longer offered or enrolled as the second factor. +- "Forgot password" is hidden while the api takes no password. diff --git a/projects/ngx-auth/README.md b/projects/ngx-auth/README.md index 7b32a50..ec857f0 100644 --- a/projects/ngx-auth/README.md +++ b/projects/ngx-auth/README.md @@ -1,5 +1,7 @@ # ngx-auth -Logging in for Angular apps against the auth routes of [zibri](https://www.npmjs.com/package/zibri): passwords, a second factor, password resets, and staying logged in with tokens or with cookies. Guards protect routes by login and permission, and an interceptor sends the login with every request to your api and to nothing else. +Logging in for Angular apps against an api with the auth models of [zibri-contract](https://www.npmjs.com/package/zibri-contract): passwords, links sent by email, a second factor, password resets, and staying logged in with tokens or with cookies. Guards protect routes by login and permission, and an interceptor sends the login with every request to your api and to nothing else. + +Any api that answers the routes with these models works. [zibri](https://www.npmjs.com/package/zibri) is one, and this README names its features as the example of what such an api does. Everything works with server-side rendering: on the server nobody is logged in, and nothing is stored or sent. @@ -19,24 +21,26 @@ Everything works with server-side rendering: on the server nobody is logged in, - [Providers](#providers) - [Sessions and email](#sessions-and-email) - [Passwords](#passwords) +- [Login links](#login-links) - [Invitations](#invitations) +- [Service accounts](#service-accounts) - [The pages](#the-pages) - [Translating](#translating) - [Moving from ngx-material-auth](#moving-from-ngx-material-auth) - [License](#license) # Requirements -Angular 22 with the router and `@angular/localize`, which [translates the texts](#translating), and a backend with the `AuthController` of zibri 3.1 or later, 3.2 with `invitationRoutes: true` for [invitations](#invitations). What the routes answer and take, like `CurrentUserProfile`, `UserLogin` and `OtpRegistration`, comes from [zibri-contract](https://www.npmjs.com/package/zibri-contract), the package zibri declares it in. +Angular 22 with the router and `@angular/localize`, which [translates the texts](#translating), and an api whose routes answer and take the models of [zibri-contract](https://www.npmjs.com/package/zibri-contract) 3.3 or later, like `CurrentUserProfile`, `UserLogin` and `OtpRegistration`. With zibri, that is its `AuthController` (3.1 or later), with `invitationRoutes: true` (3.2) for [invitations](#invitations), and its `LoginLinkAuthenticator` and `ServiceAccountController` (3.3) for [login links](#login-links) and [service accounts](#service-accounts). ```sh npm install @service-soft/ngx-auth zibri-contract ng add @angular/localize ``` -[The pages](#the-pages) and [second factors](#second-factors) are built on [@service-soft/ui](https://www.npmjs.com/package/@service-soft/ui). The login and `@service-soft/ngx-auth/two-factor` draw the qr code of an authenticator app with [uqr](https://www.npmjs.com/package/uqr): +[The pages](#the-pages) and [second factors](#second-factors) are built on [@service-soft/ui](https://www.npmjs.com/package/@service-soft/ui). The login and `@service-soft/ngx-auth/two-factor` draw the qr code of an authenticator app with [uqr](https://www.npmjs.com/package/uqr), and the inputs of `@service-soft/ngx-auth/service-accounts` need `@angular/aria`: ```sh -npm install @service-soft/ui uqr +npm install @service-soft/ui uqr @angular/aria ``` # Setup @@ -242,17 +246,69 @@ The links of these emails open `ConfirmEmailComponent` of `@service-soft/ngx-aut # Passwords `requestPasswordReset(email)` mails a link, `verifyPasswordResetToken(token)` says whether its token still works, and `confirmPasswordReset(token, newPassword)` sets the new password. `changePassword(currentPassword, newPassword)` changes the password of the logged in user. +# Login links +With the `LoginLinkAuthenticator` of zibri, a user logs in by a link mailed to their email, without a password: they type their email, and the link in the mail opens a page that logs them in. + +| Where | How | +|---|---| +| The login | The `LoginComponent` offers "Email me a link" next to the password, or in its place, as `GET /login-methods` answers, which zibri serves with `loginMethodsRoute: true` of the `AuthController`. An api without that route takes passwords only, and the login stays as it was. Once a link was asked for, it says that a link is on its way if the email has an account: zibri answers the same for every email, so only a refusal for too many links (`429`) shows its message | +| The page of the link | `LoginLinkComponent` of `@service-soft/ngx-auth/login-link`, see [the pages](#the-pages). It logs in when the user presses its button, never when it loads, so a scanner of a mail provider that opens the link spends nothing. A login that waits for a second factor, or for the first one of a user who has none, goes on with the steps of the `LoginComponent`, and then to `afterLogin`. A link zibri refuses, like one that expired or was used, shows zibri's message and asks for the email to mail a new one | +| In code | `resolveLoginMethods()` answers the `LoginMethods`, `{ password: true, loginLink: false }` for an api without the route. `requestLoginLink(email)` mails a link, and `loginWithLink(token)` logs in with its token and answers a `LoginResult` like `login` | + +A code by email never counts as the second factor of a login by a link, which proved the mailbox already: zibri doesn't offer it, and the login doesn't offer to enroll it. For a user with neither a password nor a second factor, like one an [invitation without a password](#invitations) created, a login by a link is a recent login, and once that is too old, zibri's answer to a route that asks for one says to log in with a new link. + +zibri's `bindToBrowser` makes a link work only in the browser that asked for it, by a cookie. Browsers send that cookie to an api on another origin only with credentials, which the `cookie` strategy sends and the `jwt` strategy doesn't: with `jwt`, bind links only when the api is on the origin of the app. + # Invitations With `invitationRoutes: true` of the `AuthController` of zibri 3.2, zibri mails invitations to an app or to a tenant, whose link is answered here: | Method | Does | |---|---| -| `verifyInvitationToken(token)` | Answers an `InvitationTokenValidity`: whether the link works, whether a new one was mailed for one that ran out, and for a link that works the invited email, its tenant, whether accepting needs a login (`requiresLogin`) and whether it may be declined (`declinable`) | +| `verifyInvitationToken(token)` | Answers an `InvitationTokenValidity`: whether the link works, whether a new one was mailed for one that ran out, and for a link that works the invited email, its tenant, whether accepting needs a login (`requiresLogin`), whether the account it creates gets no password (`withoutPassword`) and whether it may be declined (`declinable`) | | `acceptInvitation(token, password?)` | Accepts with the password of the account the invitation creates, or, without one, as the logged in account of the invited email | +| `acceptInvitationWithoutPassword(token)` | Accepts an invitation that creates its account without a password, which logs the new account in, and answers a `LoginResult` like `login`. Later, the user logs in with a [link sent by email](#login-links) | | `declineInvitation(token)` | Declines it, which needs no login | zibri finds an invitation by its token in every tenant, so the requests name none, and a link zibri refuses ends no login. The [`AcceptInvitationComponent`](#the-pages) does all of it. +# Service accounts +`ServiceAccountsComponent` of `@service-soft/ngx-auth/service-accounts` manages the accounts of AI assistants and integrations, which never log in and call the api with their API keys, for the `ServiceAccountController` of zibri 3.3 or any api answering the same models of zibri-contract. Give it the url of the routes, what can be chosen for an account and, for an api with the MCP server of zibri, the url of the route of its tools: + +```ts +// app.config.ts +import { provideServiceAccountsConfig } from '@service-soft/ngx-auth/service-accounts'; + +export const appConfig: ApplicationConfig = { + providers: [ + provideServiceAccountsConfig({ + baseUrl: 'https://api.example.com/service-accounts', + mcpToolsBaseUrl: 'https://api.example.com/service-account-tools', + roles: [{ label: 'User', value: 'user' }], + tenantRoles: [{ label: 'Member', value: 'member' }], + permissions: [{ label: 'Read tasks', value: 'tasks.read' }, { label: 'Propose changes of tasks', value: 'tasks.propose' }] + }) + ] +}; +``` + +```html + +``` + +It lists every service account by name with its roles, its roles in the tenant the user acts in and its API keys: their permissions, whether they act in that tenant only or in every tenant of the account, when they expire, were last used and were created, never their secret. With `mcpToolsBaseUrl` it shows the MCP tools each account's roles open in the tenant, by their title and name, and whether they read or propose changes a person approves. With `canManage`, like with `service-accounts.manage`, it creates an account from its name and roles, changes its roles, and adds a key from its name, its permissions, the day it expires, whether it acts only in the tenant the user acts in, which is on by default, and whether it requires DPoP, which an MCP client leaves off. The secret of a new key shows once, with a button that copies it and a warning that it won't show again, until the user is done with it. Revoking a key and deleting an account, which revokes its keys, ask first. What the api refuses, like a role the user may not hand out, shows its message. + +| Route | Sent for | Needs in zibri | +|---|---|---| +| `GET {baseUrl}` | The list | `service-accounts.read` | +| `POST {baseUrl}` | Creating an account | `service-accounts.manage` | +| `PUT {baseUrl}/:id/roles` | Changing its roles | `service-accounts.manage` | +| `POST {baseUrl}/:id/api-keys` | Adding a key | `service-accounts.manage`, and a [second factor](#a-second-factor-for-a-request) or a recent login | +| `DELETE {baseUrl}/:id/api-keys/:apiKeyId` | Revoking a key | `service-accounts.manage` | +| `DELETE {baseUrl}/:id` | Deleting an account | `service-accounts.manage` | +| `GET {mcpToolsBaseUrl}/:id` | The MCP tools of an account | `service-accounts.read` | + +The permissions are platform permissions, `ZIBRI_SERVICE_ACCOUNT_PLATFORM_PERMISSIONS` of zibri-contract, and giving or taking a role takes the permission for that as well, which zibri checks. The interceptor of `provideAuth` sends the login and the tenant the user acts in with every request, and asks for the second factor adding a key takes. The `ServiceAccountsService` sends the same requests from code of your own. `provideServiceAccountsConfig` also changes `canManage`, the default of the input, `dateTimeFormat`, `headingLevel`, 2 by default, and the `labels`. + # The pages Ready pages for these, built on [@service-soft/ui](https://www.npmjs.com/package/@service-soft/ui), each in its own entry point, so an app only loads the ones it uses: @@ -267,6 +323,11 @@ const routes: Routes = [ path: 'reset-password/:token', loadComponent: () => import('@service-soft/ngx-auth/confirm-password-reset').then(m => m.ConfirmPasswordResetComponent) }, + { + path: 'login-link/:token', + loadComponent: () => import('@service-soft/ngx-auth/login-link').then(m => m.LoginLinkComponent), + canActivate: [notLoggedInGuard] + }, // no guard: accepting works logged out and logged in { path: 'accept-invitation/:token', @@ -277,23 +338,26 @@ const routes: Routes = [ | Component | Does | |---|---| -| `LoginComponent` | The email and password, then the code of a second factor, the first second factor of a user who has none, or a new password, when the login waits for one. Codes by email or text message are sent when the user picks the method, and once more on request. Opens the `returnUrl` the `loggedInGuard` adds, or `afterLogin` | +| `LoginComponent` | The email and password, then the code of a second factor, the first second factor of a user who has none, or a new password, when the login waits for one. Codes by email or text message are sent when the user picks the method, and once more on request. Offers a [login link](#login-links) next to the password or in its place, as the api answers. Opens the `returnUrl` the `loggedInGuard` adds, or `afterLogin`. Its input `pendingLogin` continues a login that waits for a step, like one a page of your own started | +| `LoginLinkComponent` | The page of a [login link](#login-links): zibri adds the token to the `loginLinkUrl` of its `LOGIN_LINK_OPTIONS` as the last segment, so set that to the url of this route, like `https://app.example.com/login-link`. Logs in on a press of its button, through the steps of the `LoginComponent` when the login waits for one, and opens `afterLogin`. A link that doesn't work anymore shows zibri's message, and offers to mail a new one | | `RequestPasswordResetComponent` | Has zibri mail a link to reset the password | | `ConfirmPasswordResetComponent` | The page of that link: zibri adds the token to its `CONFIRM_PASSWORD_RESET_URL` as the last segment, so set that to the url of this route, like `https://app.example.com/reset-password`. Checks the link in the browser, and offers a new one when it doesn't work anymore | | `ChangePasswordComponent` | The current and a new password, for the page of the user's account, with a `h2` heading | -| `AcceptInvitationComponent` | The page of the link of an [invitation](#invitations): zibri adds the token to the `acceptInvitationUrl` of its `INVITATION_OPTIONS` as the last segment, so set that to the url of this route, like `https://app.example.com/accept-invitation`. Checks the link in the browser, and says when it doesn't work, and when a new one was mailed. An invitation that creates its account asks for its password, then links to the login. One to an email with an account links to the login while nobody is logged in, and back here once they are; offers logging out to another account; and accepts with one button as that account, which then acts in the tenant of the invitation. A decline button shows next to accepting when the invitation may be declined | +| `AcceptInvitationComponent` | The page of the link of an [invitation](#invitations): zibri adds the token to the `acceptInvitationUrl` of its `INVITATION_OPTIONS` as the last segment, so set that to the url of this route, like `https://app.example.com/accept-invitation`. Checks the link in the browser, and says when it doesn't work, and when a new one was mailed. An invitation that creates its account asks for its password, then links to the login. One that creates its account without a password (`withoutPassword`) asks for none: accepting logs the user in, through the steps of the `LoginComponent` when the login waits for one, like a second factor to enroll, and opens `afterLogin`. One to an email with an account links to the login while nobody is logged in, and back here once they are; offers logging out to another account; and accepts with one button as that account, which then acts in the tenant of the invitation. A decline button shows next to accepting when the invitation may be declined | A refused attempt shows the message of zibri, in the language of the request, and keeps what the user typed. Each page has a `provideXConfig`, like `provideLoginConfig`, for its texts and options. Values you leave out keep their defaults, so a translation can change single labels: | Option | Default | |---|---| | `labels` | English texts, see [translating](#translating). The texts of the second factor are those of `provideSecondFactorConfig`, see [second factors](#second-factors) | -| `requestPasswordResetRoute` of the login and the confirm page | `'/request-password-reset'`. Undefined hides the link of the login, for an app without passwords to reset | +| `requestPasswordResetRoute` of the login and the confirm page | `'/request-password-reset'`. Undefined hides the link of the login, for an app without passwords to reset. The login hides it as well while the api takes no password | | `newPasswordMinLength` | — the `minLength` of zibri's password policy, so the browser checks it before sending | ## Translating The default texts are `$localize` with an id of their own, like `@@ngx-auth.login.title`, so `ng extract-i18n` puts them into the messages of your app, and you translate them like its own texts. The library needs `@angular/localize` for that, `ng add @angular/localize`, also in an app of one language. A build with `localize` fills the texts in, so no part of `@angular/localize` reaches the browser. The defaults are made once a config is injected, so translations an app loads at runtime with `loadTranslations` apply as well. A text of `provideXConfig` replaces the default in every language. So translate a default in your messages, and change it in the config only to say something else: a default the config replaces stays in your messages, though nothing shows it. The messages zibri refuses a request with come in the language of the request, from zibri. +German ships with the library: `locale/messages.de.xlf` of the package is an XLIFF 1.2 file with a German target for each of its texts, and its `package.json` names it in `"translations": { "de": "./locale/messages.de.xlf" }`. A merge of the translations of an app's dependencies reads that field and fills these targets into the German messages of the app, so German needs no translation of your own. Only the texts your app uses end up there, since its `ng extract-i18n` decides which units its messages have. Other languages you translate in your messages. + # Moving from ngx-material-auth - The package is `@service-soft/ngx-auth`, and it works with zibri instead of lbx-jwt: the routes, bodies and errors are zibri's. - `JwtAuthService` with its generics and abstract urls is `AuthService`, which you extend only for the types. The urls are the `apiUrl` and `paths` of `provideAuth`, which also replaces `NGX_AUTH_SERVICE`. diff --git a/projects/ngx-auth/accept-invitation/accept-invitation-config.model.ts b/projects/ngx-auth/accept-invitation/accept-invitation-config.model.ts index 7f857f6..a989948 100644 --- a/projects/ngx-auth/accept-invitation/accept-invitation-config.model.ts +++ b/projects/ngx-auth/accept-invitation/accept-invitation-config.model.ts @@ -15,13 +15,18 @@ export type AcceptInvitationLabels = { */ invalid: string, /** - * Shown when the link ran out and zibri mailed a new one to the invited email. + * Shown when the link ran out and the api mailed a new one to the invited email. */ renewed: string, /** * The label of the input of the password of the account the invitation creates. */ password: string, + /** + * Shown for an invitation that creates its account without a password: accepting logs the user in, and later they + * log in with a link sent by email. + */ + withoutPassword: string, /** * The button that accepts the invitation. */ @@ -63,7 +68,7 @@ export type AcceptInvitationLabels = { */ declined: string, /** - * Shown when a request failed without a message of zibri, like without a connection. + * Shown when a request failed without a message of the api, like without a connection. */ failed: string }; @@ -78,7 +83,7 @@ export type AcceptInvitationConfig = { labels: AcceptInvitationLabels, /** * The least number of characters of the password of the account an invitation creates, the minLength of the - * password policy of zibri. Without it, zibri says what is too short. + * password policy of the api. Without it, the api says what is too short. */ newPasswordMinLength: number | undefined }; \ No newline at end of file diff --git a/projects/ngx-auth/accept-invitation/accept-invitation-config.provider.ts b/projects/ngx-auth/accept-invitation/accept-invitation-config.provider.ts index 73a3d2a..60c46bb 100644 --- a/projects/ngx-auth/accept-invitation/accept-invitation-config.provider.ts +++ b/projects/ngx-auth/accept-invitation/accept-invitation-config.provider.ts @@ -17,6 +17,7 @@ function getDefaultAcceptInvitationConfig(): AcceptInvitationConfig { invalid: $localize`:@@ngx-auth.accept-invitation.invalid:This link doesn't work. It ran out, or was used or revoked already.`, renewed: $localize`:@@ngx-auth.accept-invitation.renewed:This link ran out. A new one was mailed to the invited address.`, password: $localize`:@@ngx-auth.accept-invitation.password:Password`, + withoutPassword: $localize`:@@ngx-auth.accept-invitation.withoutPassword:Accepting logs you in, without a password. Later, you log in with a link sent to your email.`, accept: $localize`:@@ngx-auth.accept-invitation.accept:Accept invitation`, decline: $localize`:@@ngx-auth.accept-invitation.decline:Decline`, loginRequired: $localize`:@@ngx-auth.accept-invitation.loginRequired:Log in as the invited account to accept the invitation.`, diff --git a/projects/ngx-auth/accept-invitation/accept-invitation-password.component.ts b/projects/ngx-auth/accept-invitation/accept-invitation-password.component.ts index bc3c33f..f5946de 100644 --- a/projects/ngx-auth/accept-invitation/accept-invitation-password.component.ts +++ b/projects/ngx-auth/accept-invitation/accept-invitation-password.component.ts @@ -23,7 +23,7 @@ export class AcceptInvitationPasswordComponent { readonly labels: InputSignal = input.required(); /** - * The least number of characters of the password, or undefined to leave it to zibri. + * The least number of characters of the password, or undefined to leave it to the api. */ readonly minLength: InputSignal = input.required(); diff --git a/projects/ngx-auth/accept-invitation/accept-invitation-state.type.ts b/projects/ngx-auth/accept-invitation/accept-invitation-state.type.ts index 808a145..d8c7d1e 100644 --- a/projects/ngx-auth/accept-invitation/accept-invitation-state.type.ts +++ b/projects/ngx-auth/accept-invitation/accept-invitation-state.type.ts @@ -1,7 +1,7 @@ /** * Where the page of an invitation stands: checking the link, refusing a link that doesn't work, asking for the - * password of the account it creates, asking to log in or to log out of another account, offering to accept, or - * done. + * password of the account it creates, offering to accept one that creates its account without a password, asking to + * log in or to log out of another account, offering to accept, or done. */ export type AcceptInvitationState - = 'verifying' | 'invalid' | 'password' | 'loginRequired' | 'otherAccount' | 'accept' | 'accepted' | 'declined'; \ No newline at end of file + = 'verifying' | 'invalid' | 'password' | 'withoutPassword' | 'loginRequired' | 'otherAccount' | 'accept' | 'accepted' | 'declined'; \ No newline at end of file diff --git a/projects/ngx-auth/accept-invitation/accept-invitation.component.html b/projects/ngx-auth/accept-invitation/accept-invitation.component.html index a01c236..27e3948 100644 --- a/projects/ngx-auth/accept-invitation/accept-invitation.component.html +++ b/projects/ngx-auth/accept-invitation/accept-invitation.component.html @@ -1,33 +1,41 @@ - -

{{ labels.title }}

-@for (paragraph of paragraphs(); track $index) { -

{{ paragraph }}

-} -@if (state() === 'password') { - -} -
- @for (action of actions(); track action.label) { - @if (action.kind === 'link') { - {{ action.label }} - } - @else { - - } +@if (pendingLogin(); as pending) { + + @defer (on immediate) { + + } +} @else { + +

{{ labels.title }}

+ @for (paragraph of paragraphs(); track $index) { +

{{ paragraph }}

} -
- - -

{{ status() }}

\ No newline at end of file +
+ @for (action of actions(); track action.label) { + @if (action.kind === 'link') { + {{ action.label }} + } + @else { + + } + } +
+ + +

{{ status() }}

+} \ No newline at end of file diff --git a/projects/ngx-auth/accept-invitation/accept-invitation.component.spec.ts b/projects/ngx-auth/accept-invitation/accept-invitation.component.spec.ts index 9b82301..9b633f6 100644 --- a/projects/ngx-auth/accept-invitation/accept-invitation.component.spec.ts +++ b/projects/ngx-auth/accept-invitation/accept-invitation.component.spec.ts @@ -7,7 +7,7 @@ import { RouterTestingHarness } from '@angular/router/testing'; import { AuthData, authInterceptor, AuthService, provideAuth } from '@service-soft/ngx-auth/auth'; import { FormTestingUtilities } from 'testing/form'; import { afterEach, describe, expect, test, vi } from 'vitest'; -import { CurrentUserProfile, InvitationTokenValidity } from 'zibri-contract'; +import { AcceptInvitationInput, CurrentUserProfile, InvitationTokenValidity, JwtAuthData, SecondFactorRequiredErrorBody } from 'zibri-contract'; import { AcceptInvitationComponent } from './accept-invitation.component'; @@ -21,9 +21,34 @@ class AppAuthService extends AuthService {} class PageComponent {} // a link of an invitation that works, to tenant-b. -const VALID: InvitationTokenValidity = { isValid: true, renewed: false, email: 'ada@example.com', tenantId: 'tenant-b', requiresLogin: true, declinable: true }; - -const ADA: CurrentUserProfile = { id: 'user-1', email: 'Ada@example.com', memberships: [{ tenantId: 'tenant-a', permissions: [] }], platformPermissions: [] }; +const VALID: InvitationTokenValidity = { + isValid: true, + renewed: false, + email: 'ada@example.com', + tenantId: 'tenant-b', + requiresLogin: true, + declinable: true, + withoutPassword: false +}; + +// an invitation that creates its account without a password, which accepting logs in. +const WITHOUT_PASSWORD: InvitationTokenValidity = { ...VALID, requiresLogin: false, withoutPassword: true }; + +const ADA: CurrentUserProfile = { id: 'user-1', email: 'Ada@example.com', kind: 'person', memberships: [{ tenantId: 'tenant-a', permissions: [] }], platformPermissions: [] }; + +// the account an invitation without a password created. +const NEW_MEMBER: CurrentUserProfile = { id: 'user-2', email: 'ada@example.com', kind: 'person', memberships: [{ tenantId: 'tenant-b', permissions: [] }], platformPermissions: [] }; + +// what zibri answers a login of the new account with. +function createJwtData(): JwtAuthData { + const expirationDate: string = new Date(Date.now() + HOUR).toISOString(); + return { + userId: 'user-2', + roles: ['user'], + accessToken: { value: 'access-2', expirationDate }, + refreshToken: { value: 'refresh-2', expirationDate } + }; +} // a jwt login of another visit, which the AuthService finds in the browser. function storeLogin(user: CurrentUserProfile): void { @@ -94,13 +119,66 @@ describe('AcceptInvitationComponent', () => { await vi.waitFor(() => expect(document.activeElement?.getAttribute('href')).toBe('/login')); }); + test('accepts an invitation without a password with one button, which logs the new account in', async () => { + const [root, harness, backend] = await open(WITHOUT_PASSWORD); + await vi.waitFor(() => expect(root.textContent).toContain('Accepting logs you in, without a password.')); + expect(FormTestingUtilities.findInput(root, 'password')).toBeNull(); + + FormTestingUtilities.click(root, 'Accept invitation'); + const accept: TestRequest = await expectRequest(backend, 'accept-invitation?strategy=jwt'); + const input: AcceptInvitationInput = { token: 'invitation-1' }; + expect(accept.request.body).toEqual(input); + accept.flush(createJwtData()); + (await vi.waitFor(() => backend.expectOne(`${API}/me`))).flush(NEW_MEMBER); + + await vi.waitFor(() => expect(TestBed.inject(Router).url).toBe('/')); + const authService: AppAuthService = TestBed.inject(AppAuthService); + expect(authService.loggedIn()).toBe(true); + // the one membership of the new account + expect(authService.activeTenantId()).toBe('tenant-b'); + await harness.fixture.whenStable(); + }); + + test('has the new account enroll a second factor other than codes by email, when its login needs one', async () => { + const [root, harness, backend] = await open(WITHOUT_PASSWORD); + await vi.waitFor(() => expect(root.textContent).toContain('Accept invitation')); + + FormTestingUtilities.click(root, 'Accept invitation'); + const refusal: SecondFactorRequiredErrorBody = { + status: 401, + name: 'SecondFactorRequiredError', + message: 'A second factor is required.', + paragraphs: ['A second factor is required.'], + ticket: 'ticket-1', + methods: [] + }; + (await expectRequest(backend, 'accept-invitation?strategy=jwt')).flush(refusal, { status: 401, statusText: 'Unauthorized' }); + + await vi.waitFor(() => expect(FormTestingUtilities.getText(root, 'h1')).toBe('Set up a second factor')); + // the link of the invitation proved the mailbox already + expect([...root.querySelectorAll('li')].map(item => item.textContent.trim())) + .toEqual(['Authenticator app', 'Codes by text message', 'Passkeys']); + FormTestingUtilities.click(root, 'Authenticator app'); + const enroll: TestRequest = await expectRequest(backend, 'login/2fa/registration/request?method=otp'); + expect(enroll.request.headers.get('x-login-ticket')).toBe('ticket-1'); + enroll.flush({ qrCodeUrl: 'otpauth://totp/Example:ada', secret: 'SECRET' }); + await vi.waitFor(() => expect(FormTestingUtilities.findInput(root, 'code')).not.toBeNull()); + FormTestingUtilities.type(root, 'code', '111111'); + await harness.fixture.whenStable(); + FormTestingUtilities.click(root, 'Turn on'); + (await expectRequest(backend, 'login/2fa/registration/confirm?strategy=jwt&method=otp')).flush(createJwtData()); + (await vi.waitFor(() => backend.expectOne(`${API}/me`))).flush(NEW_MEMBER); + + await vi.waitFor(() => expect(TestBed.inject(Router).url).toBe('/')); + }); + test('says that a link doesn\'t work, and that a new one was mailed when it was renewed', async () => { - const [invalid] = await open({ isValid: false, renewed: false, requiresLogin: false, declinable: false }); + const [invalid] = await open({ isValid: false, renewed: false, requiresLogin: false, declinable: false, withoutPassword: false }); await vi.waitFor(() => expect(invalid.textContent).toContain('This link doesn\'t work.')); expect(invalid.querySelector('button')).toBeNull(); TestBed.resetTestingModule(); - const [renewed] = await open({ isValid: false, renewed: true, requiresLogin: false, declinable: false }); + const [renewed] = await open({ isValid: false, renewed: true, requiresLogin: false, declinable: false, withoutPassword: false }); await vi.waitFor(() => expect(renewed.textContent).toContain('A new one was mailed to the invited address.')); }); diff --git a/projects/ngx-auth/accept-invitation/accept-invitation.component.ts b/projects/ngx-auth/accept-invitation/accept-invitation.component.ts index 5730534..7ba63ce 100644 --- a/projects/ngx-auth/accept-invitation/accept-invitation.component.ts +++ b/projects/ngx-auth/accept-invitation/accept-invitation.component.ts @@ -1,6 +1,7 @@ import { afterNextRender, Component, computed, ElementRef, inject, Injector, Signal, signal, viewChild, viewChildren, WritableSignal } from '@angular/core'; import { ActivatedRoute, Router, RouterLink } from '@angular/router'; -import { AUTH_CONFIG, AuthConfig, AuthErrorUtilities, AuthService } from '@service-soft/ngx-auth/auth'; +import { AUTH_CONFIG, AuthConfig, AuthErrorUtilities, AuthService, LoginResult } from '@service-soft/ngx-auth/auth'; +import { LoginComponent, type PendingLogin } from '@service-soft/ngx-auth/login'; import { ButtonComponent } from '@service-soft/ui/button'; import { InvitationTokenValidity } from 'zibri-contract'; @@ -11,18 +12,20 @@ import { AcceptInvitationPasswordComponent } from './accept-invitation-password. import { AcceptInvitationState } from './accept-invitation-state.type'; /** - * The page the link of an invitation opens, which accepts or declines it. Zibri adds the token to the - * acceptInvitationUrl of its INVITATION_OPTIONS as the last segment, so its route reads it as the parameter token, - * without a guard, as accepting works logged out and logged in: + * The page the link of an invitation opens, which accepts or declines it. The api adds the token to the link as the + * last segment, like zibri to the acceptInvitationUrl of its INVITATION_OPTIONS, so its route reads it as the + * parameter token, without a guard, as accepting works logged out and logged in: * `{ path: 'accept-invitation/:token', component: AcceptInvitationComponent }`. It checks the link once it shows in the - * browser. An invitation that creates its account asks for its password, and leads on to the login. One to an email + * browser. An invitation that creates its account asks for its password, and leads on to the login. One that creates + * its account without a password accepts with one button, which logs the user in, through the steps of the + * LoginComponent when the login waits for one, like a second factor to enroll, and opens afterLogin. One to an email * with an account asks to log in as it, and accepts with one button, after which the user acts in the tenant of the * invitation. Its texts come from provideAcceptInvitationConfig. */ @Component({ selector: 'ngx-accept-invitation', templateUrl: './accept-invitation.component.html', - imports: [AcceptInvitationPasswordComponent, ButtonComponent, RouterLink], + imports: [AcceptInvitationPasswordComponent, ButtonComponent, RouterLink, LoginComponent], host: { class: 'block' } @@ -59,10 +62,15 @@ export class AcceptInvitationComponent { protected readonly labels: AcceptInvitationLabels = this.config.labels; /** - * What zibri answered about the link, undefined until it did. + * What the api answered about the link, undefined until it did. */ protected readonly validity: WritableSignal = signal(undefined); + /** + * The login accepting without a password started while it waits for a step, like a second factor to enroll. + */ + protected readonly pendingLogin: WritableSignal = signal(undefined); + /** * Where the page stands. It follows the login, like a logout in another tab. */ @@ -79,7 +87,7 @@ export class AcceptInvitationComponent { return 'invalid'; } if (!validity.requiresLogin) { - return 'password'; + return validity.withoutPassword ? 'withoutPassword' : 'password'; } if (!this.authService.loggedIn()) { return 'loginRequired'; @@ -110,7 +118,7 @@ export class AcceptInvitationComponent { protected readonly actions: Signal = computed(() => this.resolveActions(this.state())); /** - * What zibri answered a refused request with, empty while nothing was refused. + * What the api answered a refused request with, empty while nothing was refused. */ protected readonly errorParagraphs: WritableSignal = signal([]); @@ -177,6 +185,9 @@ export class AcceptInvitationComponent { case 'otherAccount': { return this.labels.otherAccount; } + case 'withoutPassword': { + return this.labels.withoutPassword; + } case 'verifying': case 'password': case 'accept': @@ -203,6 +214,15 @@ export class AcceptInvitationComponent { case 'accept': { return [{ kind: 'button', label: this.labels.accept, variant: 'filled', run: async () => await this.accept() }, ...decline]; } + case 'withoutPassword': { + const accept: AcceptInvitationActionView = { + kind: 'button', + label: this.labels.accept, + variant: 'filled', + run: async () => await this.acceptWithoutPassword() + }; + return [accept, ...decline]; + } case 'accepted': { // an account with its new password logs in first, a logged in one goes on into the app const next: AcceptInvitationActionView = this.validity()?.requiresLogin === false @@ -219,6 +239,33 @@ export class AcceptInvitationComponent { } } + // accepts an invitation that creates its account without a password, which logs the new account in. + private async acceptWithoutPassword(): Promise { + const validity: InvitationTokenValidity | undefined = this.validity(); + const token: string | null = this.token; + if (this.sending || validity == undefined || token == undefined) { + return; + } + this.sending = true; + this.errorParagraphs.set([]); + try { + const result: LoginResult = await this.authService.acceptInvitationWithoutPassword(token); + if (result.type === 'loggedIn') { + // the new account has the one membership of the invitation, which it acts in without choosing it + await this.router.navigateByUrl(this.routes.afterLogin); + return; + } + // the link of the invitation proved the mailbox, like a login link, so a code by email is no second factor + this.pendingLogin.set({ result, email: validity.email, emailCodesCount: false }); + } + catch (error) { + this.errorParagraphs.set(AuthErrorUtilities.findErrorParagraphs(error) ?? [this.labels.failed]); + } + finally { + this.sending = false; + } + } + // logs out of the other account, and leads on to the login, which comes back to this page. private async logout(): Promise { const returnUrl: string = this.router.url; @@ -251,7 +298,7 @@ export class AcceptInvitationComponent { private async verify(): Promise { if (this.token == undefined) { - this.validity.set({ isValid: false, renewed: false, requiresLogin: false, declinable: false }); + this.validity.set({ isValid: false, renewed: false, requiresLogin: false, declinable: false, withoutPassword: false }); return; } try { diff --git a/projects/ngx-auth/accept-invitation/accept-invitation.stories.ts b/projects/ngx-auth/accept-invitation/accept-invitation.stories.ts index c59fa6b..62cfdee 100644 --- a/projects/ngx-auth/accept-invitation/accept-invitation.stories.ts +++ b/projects/ngx-auth/accept-invitation/accept-invitation.stories.ts @@ -1,5 +1,5 @@ import { provideHttpClient, withInterceptors } from '@angular/common/http'; -import { Component, EnvironmentProviders, inject, OnInit, Provider, Service } from '@angular/core'; +import { Component, inject, OnInit, Provider, Service } from '@angular/core'; import { provideRouter, Router, RouterOutlet, withDisabledInitialNavigation } from '@angular/router'; import { AuthData, authInterceptor, AuthService, provideAuth } from '@service-soft/ngx-auth/auth'; import { applicationConfig, Meta, StoryObj } from '@storybook/angular'; @@ -18,24 +18,17 @@ const VALID: InvitationTokenValidity = { email: 'ada@example.com', tenantId: 'tenant-b', requiresLogin: true, - declinable: true + declinable: true, + withoutPassword: false }; // zibri, as far as the page gets: the link of the story and what it answers about it. -function answerWith(validity: InvitationTokenValidity): (Provider | EnvironmentProviders)[] { - return [ - // the page reads the token from its route, which the story opens itself instead of the url of storybook - provideRouter([{ path: 'accept-invitation/:token', component: AcceptInvitationComponent }], withDisabledInitialNavigation()), - provideHttpClient(withInterceptors([ - authInterceptor, - HttpTestingUtilities.answerWith({ - 'POST /api/auth/verify-invitation-token': { status: 200, body: validity }, - 'POST /api/auth/accept-invitation': { status: 204 }, - 'POST /api/auth/decline-invitation': { status: 204 } - }) - ])), - provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }) - ]; +function answerWith(validity: InvitationTokenValidity): Provider { + return HttpTestingUtilities.provideAnswers({ + 'POST /api/auth/verify-invitation-token': { status: 200, body: validity }, + 'POST /api/auth/accept-invitation': { status: 204 }, + 'POST /api/auth/decline-invitation': { status: 204 } + }); } // a login of another visit, which the AuthService finds in the browser when the app starts, or none. @@ -48,7 +41,7 @@ function startLoggedInAs(email: string | undefined): () => Promise { userId: 'user-1', roles: ['user'], expiresAt: new Date(Date.now() + 3_600_000).toISOString(), - user: { id: 'user-1', email, memberships: [], platformPermissions: [] } + user: { id: 'user-1', email, kind: 'person', memberships: [], platformPermissions: [] } }; localStorage.setItem('authData', JSON.stringify(login)); } @@ -74,7 +67,17 @@ const meta: Meta = { title: 'Auth/Accept invitation', component: InvitationLinkComponent, loaders: [startLoggedInAs(undefined)], - decorators: [applicationConfig({ providers: answerWith(VALID) })] + decorators: [ + applicationConfig({ + providers: [ + // the page reads the token from its route, which the story opens itself instead of the url of storybook + provideRouter([{ path: 'accept-invitation/:token', component: AcceptInvitationComponent }], withDisabledInitialNavigation()), + provideHttpClient(withInterceptors([authInterceptor])), + provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }), + answerWith(VALID) + ] + }) + ] }; export default meta; @@ -82,7 +85,12 @@ type Story = StoryObj; // an invitation that creates its account, which asks for its password. export const NewAccount: Story = { - decorators: [applicationConfig({ providers: answerWith({ ...VALID, requiresLogin: false }) })] + decorators: [applicationConfig({ providers: [answerWith({ ...VALID, requiresLogin: false })] })] +}; + +// an invitation that creates its account without a password, which accepting logs in. +export const WithoutPassword: Story = { + decorators: [applicationConfig({ providers: [answerWith({ ...VALID, requiresLogin: false, withoutPassword: true })] })] }; export const LoginRequired: Story = {}; @@ -95,10 +103,13 @@ export const LoggedInAsSomebodyElse: Story = { loaders: [startLoggedInAs('grace@example.com')] }; +// a link that doesn't work, of which zibri tells nothing else. +const INVALID: InvitationTokenValidity = { isValid: false, renewed: false, requiresLogin: false, declinable: false, withoutPassword: false }; + export const LinkDoesNotWork: Story = { - decorators: [applicationConfig({ providers: answerWith({ isValid: false, renewed: false, requiresLogin: false, declinable: false }) })] + decorators: [applicationConfig({ providers: [answerWith(INVALID)] })] }; export const LinkRenewed: Story = { - decorators: [applicationConfig({ providers: answerWith({ isValid: false, renewed: true, requiresLogin: false, declinable: false }) })] + decorators: [applicationConfig({ providers: [answerWith({ ...INVALID, renewed: true })] })] }; \ No newline at end of file diff --git a/projects/ngx-auth/auth/any-level-permission.model.ts b/projects/ngx-auth/auth/any-level-permission.model.ts index 03fc827..1c31d1c 100644 --- a/projects/ngx-auth/auth/any-level-permission.model.ts +++ b/projects/ngx-auth/auth/any-level-permission.model.ts @@ -1,6 +1,6 @@ /** - * A permission that the user may have at either level, like `@Auth.hasAnyLevelPermission` of zibri takes it: in the - * tenant, or by their own roles. Either is enough. + * A permission that the user may have at either level: in the tenant, or by their own roles. Either is enough, like + * `@Auth.hasAnyLevelPermission` of zibri takes it. */ export type AnyLevelPermission = { /** diff --git a/projects/ngx-auth/auth/auth-config.model.ts b/projects/ngx-auth/auth/auth-config.model.ts index f722ee8..8d2b02e 100644 --- a/projects/ngx-auth/auth/auth-config.model.ts +++ b/projects/ngx-auth/auth/auth-config.model.ts @@ -7,7 +7,7 @@ import { AuthStrategyName } from './auth-strategy-name.type'; import { SecondFactorPrompt } from './second-factor-prompt.service'; /** - * How the app logs in at zibri. + * How the app logs in at the api. */ export type AuthConfig = { /** @@ -20,8 +20,8 @@ export type AuthConfig = { strategy: AuthStrategyName, /** * Whether the tokens of a jwt login are bound to a key of this browser (DPoP, RFC 9449), which every request proves - * it holds, so stolen tokens are of no use anywhere else. Zibri binds a login to the key its request proves, and - * with its jwt strategy's `requireDpop` refuses one without. Only for the jwt strategy. + * it holds, so stolen tokens are of no use anywhere else. The api binds a login to the key its request proves, and + * may refuse one without, like zibri with its jwt strategy's `requireDpop`. Only for the jwt strategy. */ dpop: boolean, /** diff --git a/projects/ngx-auth/auth/auth-config.provider.ts b/projects/ngx-auth/auth/auth-config.provider.ts index 849d585..a776b6e 100644 --- a/projects/ngx-auth/auth/auth-config.provider.ts +++ b/projects/ngx-auth/auth/auth-config.provider.ts @@ -39,6 +39,8 @@ const DEFAULT_PATHS: AuthPaths = { verifyPasswordResetToken: '/verify-password-reset-token', confirmPasswordReset: '/confirm-password-reset', changePassword: '/change-password', + requestLoginLink: '/request-login-link', + loginMethods: '/login-methods', verifyInvitationToken: '/verify-invitation-token', acceptInvitation: '/accept-invitation', declineInvitation: '/decline-invitation' @@ -68,7 +70,7 @@ const DEFAULT_ROUTES: AuthRoutes = { const DEFAULT_REFRESH_BEFORE_EXPIRY_IN_MS: number = 30_000; /** - * How the app logs in at zibri. Set it with provideAuth. + * How the app logs in at the api. Set it with provideAuth. */ export const AUTH_CONFIG: InjectionToken = new InjectionToken('AUTH_CONFIG', { providedIn: 'root', diff --git a/projects/ngx-auth/auth/auth-error-body.model.ts b/projects/ngx-auth/auth/auth-error-body.model.ts index 2a2aa9a..ff56762 100644 --- a/projects/ngx-auth/auth/auth-error-body.model.ts +++ b/projects/ngx-auth/auth/auth-error-body.model.ts @@ -1,5 +1,5 @@ /** - * What the auth reads of the error body of zibri: its name, and what a login that waits for a step answers with. + * What the auth reads of the error body of the api: its name, and what a login that waits for a step answers with. */ export type AuthErrorBody = { /** diff --git a/projects/ngx-auth/auth/auth-error.utilities.ts b/projects/ngx-auth/auth/auth-error.utilities.ts index d129238..51da3ec 100644 --- a/projects/ngx-auth/auth/auth-error.utilities.ts +++ b/projects/ngx-auth/auth/auth-error.utilities.ts @@ -3,13 +3,13 @@ import { HttpErrorResponse, HttpStatusCode } from '@angular/common/http'; import { AuthErrorBody } from './auth-error-body.model'; /** - * Utilities for the errors zibri answers auth requests with. + * Utilities for the errors the api answers auth requests with. */ export abstract class AuthErrorUtilities { /** * Finds what the auth reads of the body of a failed request. * @param error - What the request failed with. - * @returns The name, ticket and methods of the body, or undefined for an error that isn't one of zibri's. + * @returns The name, ticket and methods of the body, or undefined for an error that isn't one of the api's. */ static findErrorBody(error: unknown): AuthErrorBody | undefined { if (!(error instanceof HttpErrorResponse)) { @@ -35,19 +35,19 @@ export abstract class AuthErrorUtilities { } /** - * Finds the name of the error zibri answered a request with, like 'SecondFactorMissingError'. + * Finds the name of the error the api answered a request with, like 'SecondFactorMissingError'. * @param error - What the request failed with. - * @returns The name, or undefined for an error that isn't one of zibri's. + * @returns The name, or undefined for an error that isn't one of the api's. */ static findErrorName(error: unknown): string | undefined { return this.findErrorBody(error)?.name; } /** - * Finds the message zibri answered a request with, in the paragraphs it was written as and in the language of the - * request, like a wrong password or too many attempts. + * Finds the message the api answered a request with, in the paragraphs it was written as and in the language of + * the request, like a wrong password or too many attempts. * @param error - What the request failed with. - * @returns The paragraphs, or undefined for an error that isn't one of zibri's. + * @returns The paragraphs, or undefined for an error that isn't one of the api's. */ static findErrorParagraphs(error: unknown): string[] | undefined { const paragraphs: string[] | undefined = this.findErrorBody(error)?.paragraphs; @@ -65,4 +65,14 @@ export abstract class AuthErrorUtilities { return error instanceof HttpErrorResponse && (error.status === 0 || error.status === HttpStatusCode.GatewayTimeout); } + + /** + * Whether the server refused a request for too many attempts, with a 429, like when somebody asks for links too + * often. Its message says so. + * @param error - What the request failed with. + * @returns True for a 429. + */ + static isTooManyRequests(error: unknown): boolean { + return error instanceof HttpErrorResponse && error.status === HttpStatusCode.TooManyRequests; + } } \ No newline at end of file diff --git a/projects/ngx-auth/auth/auth-guards.spec.ts b/projects/ngx-auth/auth/auth-guards.spec.ts index 2129a84..3ea873e 100644 --- a/projects/ngx-auth/auth/auth-guards.spec.ts +++ b/projects/ngx-auth/auth/auth-guards.spec.ts @@ -44,6 +44,7 @@ class PageComponent {} const PROFILE: CurrentUserProfile = { id: 'user-1', email: 'ada@example.com', + kind: 'person', memberships: [ { tenantId: 'tenant-a', permissions: ['invoices.read'] }, { tenantId: 'tenant-b', permissions: ['invoices.read', 'invoices.export', 'members.read'] } diff --git a/projects/ngx-auth/auth/auth-headers.model.ts b/projects/ngx-auth/auth/auth-headers.model.ts index d374450..1b0af8c 100644 --- a/projects/ngx-auth/auth/auth-headers.model.ts +++ b/projects/ngx-auth/auth/auth-headers.model.ts @@ -1,5 +1,5 @@ /** - * The names of the headers zibri reads and sends for auth. + * The names of the headers the api reads and sends for auth. */ export type AuthHeaders = { /** diff --git a/projects/ngx-auth/auth/auth-paths.model.ts b/projects/ngx-auth/auth/auth-paths.model.ts index 3d8fb86..3165755 100644 --- a/projects/ngx-auth/auth/auth-paths.model.ts +++ b/projects/ngx-auth/auth/auth-paths.model.ts @@ -1,5 +1,5 @@ /** - * The paths of the auth routes below the apiUrl, as the AuthController of zibri serves them. + * The paths of the auth routes below the apiUrl, as the api serves them, like the AuthController of zibri. */ export type AuthPaths = { /** @@ -126,6 +126,14 @@ export type AuthPaths = { * Changes the password of the logged in user. */ changePassword: string, + /** + * Mails a link to log in with. With the `LoginLinkAuthenticator` among the authenticators of the AuthController. + */ + requestLoginLink: string, + /** + * The ways the login route takes: a password, a link sent by email. With `loginMethodsRoute` of the AuthController. + */ + loginMethods: string, /** * Whether the token of the link of an invitation still works, and how it is accepted. With `invitationRoutes` of * the AuthController. diff --git a/projects/ngx-auth/auth/auth-strategy-name.type.ts b/projects/ngx-auth/auth/auth-strategy-name.type.ts index 74f2bbe..cd9f9db 100644 --- a/projects/ngx-auth/auth/auth-strategy-name.type.ts +++ b/projects/ngx-auth/auth/auth-strategy-name.type.ts @@ -1,5 +1,5 @@ /** - * How the browser stays logged in at zibri: with tokens it sends itself (`jwt`), or with httpOnly cookies the browser + * How the browser stays logged in at the api: with tokens it sends itself (`jwt`), or with httpOnly cookies the browser * sends and a csrf token (`cookie`). */ export type AuthStrategyName = 'jwt' | 'cookie'; \ No newline at end of file diff --git a/projects/ngx-auth/auth/auth.interceptor.ts b/projects/ngx-auth/auth/auth.interceptor.ts index 932135e..f52815e 100644 --- a/projects/ngx-auth/auth/auth.interceptor.ts +++ b/projects/ngx-auth/auth/auth.interceptor.ts @@ -33,8 +33,8 @@ const LOGIN_KEEPING_ERRORS: string[] = [ /** * Sends the login with every request to the origins of provideAuth, and nothing to any other: the access token of a * jwt login, refreshed when it runs out, or the cookies and the csrf token of a cookie login. With `dpop: true`, every - * request to zibri carries the DPoP proof of the key of the browser, and the access token goes with the DPoP scheme; - * a proof refused for the nonce zibri wants is sent once more with it. Asks the user for a second factor when a + * request to the api carries the DPoP proof of the key of the browser, and the access token goes with the DPoP scheme; + * a proof refused for the nonce the api wants is sent once more with it. Asks the user for a second factor when a * request needs one, and sends it again with it. Ends the login of this browser when the server * refuses it with one of the logoutStatuses and a refresh doesn't help. Register it with * `provideHttpClient(withInterceptors([authInterceptor]))`. @@ -81,8 +81,8 @@ export const authInterceptor: HttpInterceptorFn = (request, next) => { type Send = (attempt: HttpRequest, retried: boolean) => Observable>; /** - * Sends a request with the DPoP proof of its method, url and access token, keeps the nonce zibri answers with, and - * sends it once more with a new proof when zibri refused the proof for a nonce it lacked. + * Sends a request with the DPoP proof of its method, url and access token, keeps the nonce the api answers with, and + * sends it once more with a new proof when the api refused the proof for a nonce it lacked. * @param dpop - The DpopService. * @param baseUrl - The url a relative url of a request is relative to. * @param request - The request, with its Authorization if it has one. @@ -119,8 +119,8 @@ function sendWithProof( } /** - * Whether zibri refused a proof for the nonce it lacked: in the body of a route of the auth, or in the challenge of a - * route that takes the access token. + * Whether the api refused a proof for the nonce it lacked: in the body of a route of the auth, or in the challenge of + * a route that takes the access token. * @param refusal - What the server answered. * @returns True for a missing or expired nonce. */ diff --git a/projects/ngx-auth/auth/auth.provider.ts b/projects/ngx-auth/auth/auth.provider.ts index 611eedb..350f453 100644 --- a/projects/ngx-auth/auth/auth.provider.ts +++ b/projects/ngx-auth/auth/auth.provider.ts @@ -5,7 +5,7 @@ import { provideAuthConfig } from './auth-config.provider'; import { AuthService } from './auth.service'; /** - * Sets up logging in at zibri: the AuthService of the app, which extends AuthService with its own roles and + * Sets up logging in at the api: the AuthService of the app, which extends AuthService with its own roles and * permissions, and where and how to log in. Provide it in the application config, and register the authInterceptor * with provideHttpClient. * @param service - The AuthService of the app. diff --git a/projects/ngx-auth/auth/auth.service.spec.ts b/projects/ngx-auth/auth/auth.service.spec.ts index c7aeec7..f9a5327 100644 --- a/projects/ngx-auth/auth/auth.service.spec.ts +++ b/projects/ngx-auth/auth/auth.service.spec.ts @@ -46,6 +46,7 @@ class AppAuthService extends AuthService { const PROFILE: CurrentUserProfile = { id: 'user-1', email: 'ada@example.com', + kind: 'person', memberships: [ { tenantId: 'tenant-a', permissions: ['invoices.read'] }, { tenantId: 'tenant-b', permissions: ['invoices.read', 'invoices.export'] } diff --git a/projects/ngx-auth/auth/auth.service.ts b/projects/ngx-auth/auth/auth.service.ts index 9b41d81..dba75f0 100644 --- a/projects/ngx-auth/auth/auth.service.ts +++ b/projects/ngx-auth/auth/auth.service.ts @@ -1,9 +1,9 @@ import { DOCUMENT, isPlatformBrowser } from '@angular/common'; -import { HttpClient, HttpContext, HttpHeaders } from '@angular/common/http'; +import { HttpClient, HttpContext, HttpErrorResponse, HttpHeaders, HttpStatusCode } from '@angular/common/http'; import { computed, DestroyRef, inject, Injector, PLATFORM_ID, runInInjectionContext, Signal, signal, Type, WritableSignal } from '@angular/core'; import { ActivatedRouteSnapshot, Router } from '@angular/router'; import { firstValueFrom, Observable } from 'rxjs'; -import { AcceptInvitationInput, CookieAuthData, CsrfToken, CurrentUserProfile, EmailConfirmation, FederatedLinkIdentityStart, InvitationTokenValidity, JwtAuthData, LogoutResult, PasskeyTicketCredentials, PasswordResetTokenValidity, TwoFactorRegistrations, UserLogin } from 'zibri-contract'; +import { AcceptInvitationInput, CookieAuthData, CsrfToken, CurrentUserProfile, EmailConfirmation, FederatedLinkIdentityStart, InvitationTokenValidity, JwtAuthData, LoginLinkCredentials, LoginMethods, LogoutResult, PasskeyTicketCredentials, PasswordResetTokenValidity, RequestLoginLinkInput, TwoFactorRegistrations, UserLogin } from 'zibri-contract'; import { AnyLevelPermission } from './any-level-permission.model'; import { AuthConfig } from './auth-config.model'; @@ -48,7 +48,7 @@ type OwnRequestOptions = { }; /** - * Logs the user in and out at zibri, keeps the login of this browser and tells what the user may do. Extend it with + * Logs the user in and out at the api, keeps the login of this browser and tells what the user may do. Extend it with * the roles and permissions of your app, and set it up with provideAuth: * `@Service() export class AppAuthService extends AuthService {}`. */ @@ -141,6 +141,48 @@ export abstract class AuthService< )); } + /** + * Resolves the ways the login route takes, so a login offers a link sent by email next to the password, or in its + * place. + * @returns Whether it takes a password and a link. An api without the route of the login methods takes passwords + * only, as it did before the route existed. + */ + async resolveLoginMethods(): Promise { + try { + return await firstValueFrom(this.http.get(this.resolveUrl('loginMethods'), this.resolveOwnOptions())); + } + catch (error) { + // zibri serves the route only with loginMethodsRoute, which an app turns on + if (error instanceof HttpErrorResponse && error.status === HttpStatusCode.NotFound) { + return { password: true, loginLink: false }; + } + throw error; + } + } + + /** + * Mails a link to log in with. Answers the same whether the address has an account or not, so say that a link is on + * its way if it has one. Rejects with a 429 when links were asked for too often, whose message says so. + * @param email - The email of the account. + */ + async requestLoginLink(email: string): Promise { + const input: RequestLoginLinkInput = { email }; + await firstValueFrom(this.http.post(this.resolveUrl('requestLoginLink'), input, this.resolveOwnOptions())); + } + + /** + * Logs the user in with the token of a link requestLoginLink mailed, which works once. Call it on a press of a + * button, not when the page of the link loads, so a scanner of a mail provider that opens it spends nothing. + * @param token - The token of the link. + * @param authenticator - The name of the authenticator of the links. + * @returns Whether the user is logged in, or what the login waits for. A code by email never counts as its second + * factor, since the link proved the same mailbox. + */ + async loginWithLink(token: string, authenticator: string = 'login-link'): Promise { + const credentials: LoginLinkCredentials = { token }; + return await this.login(credentials, authenticator); + } + /** * Sends the code of a second factor while a login waits for it, like by email or text message. * @param ticket - The ticket of the login. @@ -186,8 +228,8 @@ export abstract class AuthService< } /** - * Logs out at zibri and on this browser, and sends the user to the afterLogout route, or to the provider the login - * was started at, which ends its login too. Asks beforeLogout of the config first, which may keep the user logged in. + * Logs out at the api and on this browser, and sends the user to the afterLogout route, or to the provider the + * login was started at, which ends its login too. Asks beforeLogout of the config first, which may keep the user logged in. */ async logout(): Promise { const data: AuthData | undefined = this.data(); @@ -363,8 +405,8 @@ export abstract class AuthService< } /** - * Resolves whether the token of the link of an invitation still works, and how the invitation is accepted. Zibri - * finds the invitation by its token in every tenant, so the request names none. + * Resolves whether the token of the link of an invitation still works, and how the invitation is accepted. The + * api finds the invitation by its token in every tenant, so the request names none. * @param token - The token of the link. * @returns Whether it works, whether a new link was mailed for an expired one, and for a link that works the invited * email, its tenant, whether accepting needs a login and whether it may be declined. @@ -391,6 +433,22 @@ export abstract class AuthService< await firstValueFrom(this.http.post(this.resolveUrl('acceptInvitation'), input, this.resolveOwnOptions(headers))); } + /** + * Accepts an invitation whose validity says `withoutPassword`, which creates its account without a password and + * logs it in. Later, the user logs in with a link sent by email. + * @param token - The token of the link. + * @returns Whether the user is logged in, or what the login waits for, like a second factor to enroll. A code by + * email never counts as its second factor, since the link proved the same mailbox. + */ + async acceptInvitationWithoutPassword(token: string): Promise { + const input: AcceptInvitationInput = { token }; + return await this.resolveLoginStep(this.http.post | CookieAuthData>( + this.resolveUrl('acceptInvitation', { strategy: this.config.strategy }), + input, + this.resolveOwnOptions() + )); + } + /** * Declines an invitation with the token of its link, when its validity says it may be declined. * @param token - The token of the link. @@ -420,11 +478,11 @@ export abstract class AuthService< } /** - * Starts the enrollment of a two factor method for the logged in user. Zibri asks for their second factor when + * Starts the enrollment of a two factor method for the logged in user. The api asks for their second factor when * they have one, which the interceptor asks the user for. * @param method - The name of the method, like 'otp'. * @param data - What the method starts with, like the SmsRegistrationRequestData of 'sms'. - * @returns What zibri answers, like the OtpRegistration of 'otp' or the RecoveryCodeRegistration of + * @returns What the api answers, like the OtpRegistration of 'otp' or the RecoveryCodeRegistration of * 'recovery-code', or undefined for a method that sends a code. */ async requestTwoFactorRegistration(method: string, data?: object): Promise { @@ -444,7 +502,8 @@ export abstract class AuthService< } /** - * Removes an enrolled two factor method. Zibri asks for the second factor, which the interceptor asks the user for. + * Removes an enrolled two factor method. The api asks for the second factor, which the interceptor asks the user + * for. * @param method - The name of the method, like 'otp'. */ async removeTwoFactorRegistration(method: string): Promise { @@ -456,7 +515,7 @@ export abstract class AuthService< * @param ticket - The ticket of the login. * @param method - The name of the method, like 'otp'. * @param data - What the method starts with, like the SmsRegistrationRequestData of 'sms'. - * @returns What zibri answers, like requestTwoFactorRegistration. + * @returns What the api answers, like requestTwoFactorRegistration. */ async requestTwoFactorRegistrationAtLogin(ticket: string, method: string, data?: object): Promise { return await this.sendTwoFactorRegistrationRequest( @@ -472,8 +531,8 @@ export abstract class AuthService< * @param ticket - The ticket of the login. * @param method - The name of the method, like 'otp'. * @param data - What confirms it, like confirmTwoFactorRegistration takes. - * @returns Whether the user is logged in, or what the login waits for next, like a new password. An auth service of - * the app's own in zibri may only enroll the method, and the login then waits for its next code. + * @returns Whether the user is logged in, or what the login waits for next, like a new password. The api may only + * enroll the method, like an auth service of your own in zibri, and the login then waits for its next code. */ async confirmTwoFactorRegistrationAtLogin(ticket: string, method: string, data: object): Promise { return await this.resolveLoginStep( @@ -496,7 +555,7 @@ export abstract class AuthService< /** * Logs the user in with a passkey of their device, which names the account, so the user types nothing. - * @param authenticator - The name of the passkey authenticator of zibri. + * @param authenticator - The name of the passkey authenticator of the api, like a `PasskeyAuthenticator` of zibri. * @returns Whether the user is logged in, or what the login waits for. * @throws {DOMException} A NotAllowedError when the user cancelled, see PasskeyUtilities.isCancelled. */ @@ -515,7 +574,7 @@ export abstract class AuthService< * PasskeyUtilities.isAutofillAvailable, and abort it before anything else asks for a passkey, which the browser * refuses while it waits. * @param abortSignal - Aborts the waiting request. - * @param authenticator - The name of the passkey authenticator of zibri. + * @param authenticator - The name of the passkey authenticator of the api, like a `PasskeyAuthenticator` of zibri. * @returns Whether the user is logged in, or what the login waits for. * @throws {DOMException} An AbortError once the signal aborted it, see PasskeyUtilities.isCancelled. */ @@ -549,10 +608,10 @@ export abstract class AuthService< } /** - * Has the user create a passkey for a new account, which needs no password. Your own registration route of zibri - * creates the user with the ticket and logs them in. + * Has the user create a passkey for a new account, which needs no password. Your own registration route of the + * api creates the user with the ticket and logs them in. * @param name - The name the device lists the account under, like the email the user registers with. - * @param authenticator - The name of the passkey authenticator of zibri. + * @param authenticator - The name of the passkey authenticator of the api, like a `PasskeyAuthenticator` of zibri. * @returns The ticket of the registration. * @throws {DOMException} A NotAllowedError when the user cancelled, see PasskeyUtilities.isCancelled. */ @@ -572,13 +631,13 @@ export abstract class AuthService< /** * Sends the browser to log in at a provider, like Google. The login is handed back by code: the browser lands on - * redirectTo with a `code`, which completeProviderLogin logs in with, or on zibri's registrationUrl with a `ticket` - * for a first login, or on its errorUrl with an `error`. + * redirectTo with a `code`, which completeProviderLogin logs in with, or on the registrationUrl of the api with a + * `ticket` for a first login, or on its errorUrl with an `error`. * @param authenticator - The name of the authenticator of the provider, like 'google'. - * @param redirectTo - Where the browser lands with the code, an absolute url that zibri allows. + * @param redirectTo - Where the browser lands with the code, an absolute url that the api allows. * @param returnUrl - Where the app goes once the user is logged in, like the page they wanted. - * @param scopes - The scopes of the provider's apis to ask for as well, whose tokens zibri keeps for the user. Each - * has to be one of the `apiScopes` of the authenticator. + * @param scopes - The scopes of the provider's apis to ask for as well, whose tokens the api keeps for the user. + * Each has to be one of the `apiScopes` of the authenticator. */ async startProviderLogin(authenticator: string, redirectTo: string, returnUrl?: string, scopes: string[] = []): Promise { this.document.location.assign(await this.resolveProviderLoginUrl(authenticator, redirectTo, returnUrl, scopes)); @@ -587,10 +646,10 @@ export abstract class AuthService< /** * Resolves where startProviderLogin sends the browser, and keeps the login in this tab. * @param authenticator - The name of the authenticator of the provider, like 'google'. - * @param redirectTo - Where the browser lands with the code, an absolute url that zibri allows. + * @param redirectTo - Where the browser lands with the code, an absolute url that the api allows. * @param returnUrl - Where the app goes once the user is logged in, like the page they wanted. * @param scopes - The scopes of the provider's apis to ask for as well. - * @returns The url of zibri that starts the login at the provider. + * @returns The url of the api that starts the login at the provider. */ async resolveProviderLoginUrl(authenticator: string, redirectTo: string, returnUrl?: string, scopes: string[] = []): Promise { // a verifier only this tab knows, so a code that lands in another browser logs nobody in @@ -641,10 +700,10 @@ export abstract class AuthService< } /** - * Sends the browser to a provider to connect it to the account of the logged in user. Zibri asks for their second - * factor or a recent login first, which the interceptor asks the user for. + * Sends the browser to a provider to connect it to the account of the logged in user. The api asks for their + * second factor or a recent login first, which the interceptor asks the user for. * @param authenticator - The name of the authenticator of the provider, like 'google'. - * @param redirectTo - Where the browser lands once it is connected, an absolute url that zibri allows. + * @param redirectTo - Where the browser lands once it is connected, an absolute url that the api allows. * @param forLogin - Whether the user logs in with it, or only grants access to the provider's apis. * @param scopes - The scopes of the provider's apis to ask for. */ @@ -655,7 +714,7 @@ export abstract class AuthService< /** * Resolves where startProviderLink sends the browser. * @param authenticator - The name of the authenticator of the provider, like 'google'. - * @param redirectTo - Where the browser lands once it is connected, an absolute url that zibri allows. + * @param redirectTo - Where the browser lands once it is connected, an absolute url that the api allows. * @param forLogin - Whether the user logs in with it, or only grants access to the provider's apis. * @param scopes - The scopes of the provider's apis to ask for. * @returns The url at the provider, which is good once and for a short time. @@ -669,10 +728,10 @@ export abstract class AuthService< } /** - * Has the user create a passkey that logs in to their account. Zibri asks for their second factor or a recent login - * first, which the interceptor asks the user for. + * Has the user create a passkey that logs in to their account. The api asks for their second factor or a recent + * login first, which the interceptor asks the user for. * @param name - The name the device lists the account under, like the email of the user. - * @param authenticator - The name of the passkey authenticator of zibri. + * @param authenticator - The name of the passkey authenticator of the api, like a `PasskeyAuthenticator` of zibri. * @throws {DOMException} A NotAllowedError when the user cancelled, see PasskeyUtilities.isCancelled. */ async addPasskey(name: string, authenticator: string = 'passkey'): Promise { @@ -693,8 +752,8 @@ export abstract class AuthService< } /** - * Unlinks an identity from the logged in user, like an account at a provider or a passkey. Zibri asks for their - * second factor or a recent login first, which the interceptor asks the user for. + * Unlinks an identity from the logged in user, like an account at a provider or a passkey. The api asks for + * their second factor or a recent login first, which the interceptor asks the user for. * @param identityId - The id of the identity. */ async unlinkIdentity(identityId: string): Promise { @@ -722,16 +781,16 @@ export abstract class AuthService< } /** - * Mails the logged in user a link to verify their email. While an earlier link still works, zibri mails nothing. + * Mails the logged in user a link to verify their email. While an earlier link still works, the api mails nothing. */ async requestEmailVerification(): Promise { await firstValueFrom(this.http.post(this.resolveUrl('requestEmailVerification'), undefined)); } /** - * Mails a link to the email the logged in user wants to change to, and to their current one when the - * previousAddressConfirms of zibri asks it to approve. First, zibri asks for the second factor or a recent login, - * which the interceptor asks the user for. The email stays until the links were followed. + * Mails a link to the email the logged in user wants to change to, and to their current one when the api asks it + * to approve, like zibri with its previousAddressConfirms. First, the api asks for the second factor or a recent + * login, which the interceptor asks the user for. The email stays until the links were followed. * @param newEmail - The email to change to. */ async requestEmailChange(newEmail: string): Promise { @@ -850,7 +909,7 @@ export abstract class AuthService< } /** - * Keeps the csrf token a response of zibri renewed, which it does whenever it renews the session. + * Keeps the csrf token a response of the api renewed, which it does whenever it renews the session. * @param headers - The headers of the response. */ readCsrfToken(headers: HttpHeaders): void { @@ -907,7 +966,7 @@ export abstract class AuthService< const data: JwtAuthData | CookieAuthData | null = await firstValueFrom(request); if (data == undefined) { if (withoutAnswer == undefined) { - throw new Error('zibri answered the login without its auth data.'); + throw new Error('The api answered the login without its auth data.'); } return withoutAnswer; } diff --git a/projects/ngx-auth/auth/dpop.service.ts b/projects/ngx-auth/auth/dpop.service.ts index c09cf5b..7263b69 100644 --- a/projects/ngx-auth/auth/dpop.service.ts +++ b/projects/ngx-auth/auth/dpop.service.ts @@ -30,7 +30,7 @@ export class DpopService { /** * Resolves the proof of a request, the value of its `DPoP` header: a jwt of the method and the url, signed with - * the key, with the hash of the access token it sends and the last nonce of zibri. + * the key, with the hash of the access token it sends and the last nonce of the api. * @param method - The method of the request. * @param url - The absolute url of the request, whose query and fragment the proof leaves out. * @param accessToken - The access token the request sends, if any. @@ -58,7 +58,7 @@ export class DpopService { } /** - * Keeps the nonce zibri answered with, if it answered one, for the next proofs. + * Keeps the nonce the api answered with, if it answered one, for the next proofs. * @param headers - The headers of the answer. * @returns Whether it answered a new nonce. */ diff --git a/projects/ngx-auth/auth/linked-identity-details.model.ts b/projects/ngx-auth/auth/linked-identity-details.model.ts index 80db71b..f51af25 100644 --- a/projects/ngx-auth/auth/linked-identity-details.model.ts +++ b/projects/ngx-auth/auth/linked-identity-details.model.ts @@ -1,5 +1,5 @@ /** - * What zibri lists of an identity linked to the user, as far as the auth reads it. + * What the api lists of an identity linked to the user, as far as the auth reads it. */ export type LinkedIdentityDetails = { /** @@ -11,7 +11,7 @@ export type LinkedIdentityDetails = { */ forLogin?: boolean, /** - * The scopes of the provider's apis it granted, for an identity at a provider. Empty when zibri keeps no tokens. + * The scopes of the provider's apis it granted, for an identity at a provider. Empty when the api keeps no tokens. */ grantedScopes?: string[], /** diff --git a/projects/ngx-auth/auth/linked-identity.model.ts b/projects/ngx-auth/auth/linked-identity.model.ts index d79ba36..8a6ca97 100644 --- a/projects/ngx-auth/auth/linked-identity.model.ts +++ b/projects/ngx-auth/auth/linked-identity.model.ts @@ -3,7 +3,7 @@ import { LinkedIdentity as ZibriLinkedIdentity } from 'zibri-contract'; import { LinkedIdentityDetails } from './linked-identity-details.model'; /** - * An identity linked to the user, as `GET /identities` of zibri lists it: an account at a provider, or a passkey, with - * the details of it this library shows. + * An identity linked to the user, as `GET /identities` of the api lists it: an account at a provider, or a passkey, + * with the details of it this library shows. */ export type LinkedIdentity = ZibriLinkedIdentity; \ No newline at end of file diff --git a/projects/ngx-auth/auth/passkey.utilities.ts b/projects/ngx-auth/auth/passkey.utilities.ts index 14afee7..699f361 100644 --- a/projects/ngx-auth/auth/passkey.utilities.ts +++ b/projects/ngx-auth/auth/passkey.utilities.ts @@ -1,15 +1,15 @@ import { Base64UrlUtilities } from './base64-url.utilities'; /** - * Utilities for passkeys, with the WebAuthn api of the browser: zibri sends the options as json, and takes the answer - * of the device as json. + * Utilities for passkeys, with the WebAuthn api of the browser: the api sends the options as json, and takes the + * answer of the device as json. */ export abstract class PasskeyUtilities { /** * Has the browser use a passkey, which the user picks and confirms on their device. With the mediation * 'conditional', the browser offers the passkeys in the autofill of an input with `autocomplete="username webauthn"` * instead of a dialog, and the request waits until the user picks one there, or the signal aborts it. - * @param options - The options zibri answered with, like the challenge. + * @param options - The options the api answered with, like the challenge. * @param mediation - How the browser asks, a dialog by default. * @param signal - Aborts the request, like a waiting one of the autofill before a dialog asks. * @returns The answer of the device. @@ -45,7 +45,7 @@ export abstract class PasskeyUtilities { /** * Has the browser create a passkey, which the user confirms on their device. - * @param options - The options zibri answered with, like the challenge and the name of the account. + * @param options - The options the api answered with, like the challenge and the name of the account. * @returns The answer of the device. * @throws {DOMException} A NotAllowedError when the user cancelled or no passkey was created. */ @@ -62,7 +62,7 @@ export abstract class PasskeyUtilities { } /** - * Encodes the answer of a device as the header of a second factor, base64url encoded json as zibri reads it. + * Encodes the answer of a device as the header of a second factor, base64url encoded json as the api reads it. * @param answer - The answer of the device. * @returns The value of the header. */ diff --git a/projects/ngx-auth/auth/permission.guard.ts b/projects/ngx-auth/auth/permission.guard.ts index 101fed0..e7fe53e 100644 --- a/projects/ngx-auth/auth/permission.guard.ts +++ b/projects/ngx-auth/auth/permission.guard.ts @@ -11,9 +11,9 @@ import { AuthService } from './auth.service'; * Lets only a user with the permissions of the route open it, which its data names as an AuthRouteData: * `{ canActivate: [permissionGuard], data: { permission: 'invoices.export' } }`. The tenant permission is checked in * the active tenant, or in the tenantId of the data. An anyLevelPermission passes with either of its permissions. With - * several of permission, platformPermission and anyLevelPermission, the user needs all of them, as a route of zibri - * with several decorators does; with none, nobody opens it. A logged in user without them goes to the forbidden route, - * and stays logged in; everybody else goes to the login route. + * several of permission, platformPermission and anyLevelPermission, the user needs all of them, like a route of + * zibri with several decorators does; with none, nobody opens it. A logged in user without them goes to the forbidden + * route, and stays logged in; everybody else goes to the login route. * @param route - The route, with the permissions in its data. * @param state - The state of the router, with the url the user wanted. * @returns Whether the route opens, or where the user goes instead. diff --git a/projects/ngx-auth/change-password/change-password-config.model.ts b/projects/ngx-auth/change-password/change-password-config.model.ts index 527958a..f551cf5 100644 --- a/projects/ngx-auth/change-password/change-password-config.model.ts +++ b/projects/ngx-auth/change-password/change-password-config.model.ts @@ -23,7 +23,7 @@ export type ChangePasswordLabels = { */ changed: string, /** - * Shown when the request failed without a message of zibri, like without a connection. + * Shown when the request failed without a message of the api, like without a connection. */ failed: string }; @@ -37,8 +37,8 @@ export type ChangePasswordConfig = { */ labels: ChangePasswordLabels, /** - * The least number of characters of a new password, the minLength of the password policy of zibri. Without it, - * zibri says what is too short. + * The least number of characters of a new password, the minLength of the password policy of the api. Without it, + * the api says what is too short. */ newPasswordMinLength: number | undefined }; \ No newline at end of file diff --git a/projects/ngx-auth/change-password/change-password.component.ts b/projects/ngx-auth/change-password/change-password.component.ts index f7b5531..743b546 100644 --- a/projects/ngx-auth/change-password/change-password.component.ts +++ b/projects/ngx-auth/change-password/change-password.component.ts @@ -57,7 +57,7 @@ export class ChangePasswordComponent { protected readonly newPasswordErrorShown: WritableSignal = signal(false); /** - * What zibri answered a refused request with, empty while nothing was refused. + * What the api answered a refused request with, empty while nothing was refused. */ protected readonly errorParagraphs: WritableSignal = signal([]); diff --git a/projects/ngx-auth/change-password/change-password.stories.ts b/projects/ngx-auth/change-password/change-password.stories.ts index 13a660f..e38f7a0 100644 --- a/projects/ngx-auth/change-password/change-password.stories.ts +++ b/projects/ngx-auth/change-password/change-password.stories.ts @@ -1,5 +1,5 @@ import { provideHttpClient, withInterceptors } from '@angular/common/http'; -import { afterNextRender, Component, ElementRef, EnvironmentProviders, inject, Provider, Service } from '@angular/core'; +import { afterNextRender, Component, ElementRef, inject, Provider, Service } from '@angular/core'; import { provideRouter } from '@angular/router'; import { authInterceptor, AuthService, provideAuth } from '@service-soft/ngx-auth/auth'; import { applicationConfig, Meta, StoryObj } from '@storybook/angular'; @@ -12,15 +12,8 @@ import { ChangePasswordComponent } from './change-password.component'; class StoryAuthService extends AuthService {} // zibri, as far as the form gets: it answers the change with the answer of the story. -function answerChangeWith(change: FakeAnswer): (Provider | EnvironmentProviders)[] { - return [ - provideRouter([]), - provideHttpClient(withInterceptors([ - authInterceptor, - HttpTestingUtilities.answerWith({ 'POST /api/auth/change-password': change }) - ])), - provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }) - ]; +function answerChangeWith(change: FakeAnswer): Provider { + return HttpTestingUtilities.provideAnswers({ 'POST /api/auth/change-password': change }); } // changes the password once the form shows, like a user would. @@ -43,7 +36,16 @@ class ChangePasswordAttemptComponent { const meta: Meta = { title: 'Auth/Change password', component: ChangePasswordComponent, - decorators: [applicationConfig({ providers: answerChangeWith({ status: 204 }) })], + decorators: [ + applicationConfig({ + providers: [ + provideRouter([]), + provideHttpClient(withInterceptors([authInterceptor])), + provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }), + answerChangeWith({ status: 204 }) + ] + }) + ], render: () => ({ template: '', moduleMetadata: { imports: [ChangePasswordAttemptComponent] } }) }; export default meta; @@ -59,10 +61,12 @@ export const Changed: Story = {}; export const Refused: Story = { decorators: [ applicationConfig({ - providers: answerChangeWith({ - status: 403, - body: { status: 403, name: 'ForbiddenError', message: 'Wrong password.', paragraphs: ['The current password is wrong.'] } - }) + providers: [ + answerChangeWith({ + status: 403, + body: { status: 403, name: 'ForbiddenError', message: 'Wrong password.', paragraphs: ['The current password is wrong.'] } + }) + ] }) ] }; \ No newline at end of file diff --git a/projects/ngx-auth/confirm-email/confirm-email-config.model.ts b/projects/ngx-auth/confirm-email/confirm-email-config.model.ts index 74a9b2a..6246b8b 100644 --- a/projects/ngx-auth/confirm-email/confirm-email-config.model.ts +++ b/projects/ngx-auth/confirm-email/confirm-email-config.model.ts @@ -27,7 +27,7 @@ export type ConfirmEmailLabels = { */ login: string, /** - * Shown when the request failed without a message of zibri, like without a connection. + * Shown when the request failed without a message of the api, like without a connection. */ failed: string }; diff --git a/projects/ngx-auth/confirm-email/confirm-email.component.ts b/projects/ngx-auth/confirm-email/confirm-email.component.ts index 4ebaac9..e47bb8e 100644 --- a/projects/ngx-auth/confirm-email/confirm-email.component.ts +++ b/projects/ngx-auth/confirm-email/confirm-email.component.ts @@ -22,8 +22,9 @@ type NextLink = { }; /** - * The page the link of an email of zibri opens, which verifies the email or confirms a change of it. The token is the - * last segment zibri adds to its confirmEmailUrl, so its route reads it as the parameter token: + * The page the link of an email of the api opens, which verifies the email or confirms a change of it. The token is + * the last segment the api adds to the link, like zibri to its confirmEmailUrl, so its route reads it as the parameter + * token: * `{ path: 'verify-email/:token', component: ConfirmEmailComponent }`. It confirms the link once it shows in the * browser, and leads on into the app or to the login. Its texts come from provideConfirmEmailConfig. */ @@ -48,12 +49,12 @@ export class ConfirmEmailComponent { protected readonly labels: ConfirmEmailLabels = inject(CONFIRM_EMAIL_CONFIG).labels; /** - * What following the link did, empty until zibri answered. + * What following the link did, empty until the api answered. */ protected readonly message: WritableSignal = signal(''); /** - * What zibri answered a refused link with, empty while nothing was refused. + * What the api answered a refused link with, empty while nothing was refused. */ protected readonly errorParagraphs: WritableSignal = signal([]); diff --git a/projects/ngx-auth/confirm-email/confirm-email.stories.ts b/projects/ngx-auth/confirm-email/confirm-email.stories.ts index 32cf6e8..895e25c 100644 --- a/projects/ngx-auth/confirm-email/confirm-email.stories.ts +++ b/projects/ngx-auth/confirm-email/confirm-email.stories.ts @@ -1,5 +1,5 @@ import { provideHttpClient, withInterceptors } from '@angular/common/http'; -import { Component, EnvironmentProviders, inject, Provider, Service } from '@angular/core'; +import { Component, inject, Provider, Service } from '@angular/core'; import { provideRouter, Router, RouterOutlet, withDisabledInitialNavigation } from '@angular/router'; import { authInterceptor, AuthService, provideAuth } from '@service-soft/ngx-auth/auth'; import { applicationConfig, Meta, StoryObj } from '@storybook/angular'; @@ -12,16 +12,8 @@ import { ConfirmEmailComponent } from './confirm-email.component'; class StoryAuthService extends AuthService {} // zibri, as far as the page gets: it answers the link of the story. -function answerWith(confirmation: EmailConfirmation): (Provider | EnvironmentProviders)[] { - return [ - // the page reads the token from its route, which the story opens itself instead of the url of storybook - provideRouter([{ path: 'verify-email/:token', component: ConfirmEmailComponent }], withDisabledInitialNavigation()), - provideHttpClient(withInterceptors([ - authInterceptor, - HttpTestingUtilities.answerWith({ 'POST /api/auth/confirm-email': { status: 200, body: confirmation } }) - ])), - provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }) - ]; +function answerWith(confirmation: EmailConfirmation): Provider { + return HttpTestingUtilities.provideAnswers({ 'POST /api/auth/confirm-email': { status: 200, body: confirmation } }); } // opens the link of the email. @@ -39,7 +31,17 @@ class EmailLinkComponent { const meta: Meta = { title: 'Auth/Confirm email', component: EmailLinkComponent, - decorators: [applicationConfig({ providers: answerWith({ purpose: 'verification', completed: true }) })] + decorators: [ + applicationConfig({ + providers: [ + // the page reads the token from its route, which the story opens itself instead of the url of storybook + provideRouter([{ path: 'verify-email/:token', component: ConfirmEmailComponent }], withDisabledInitialNavigation()), + provideHttpClient(withInterceptors([authInterceptor])), + provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }), + answerWith({ purpose: 'verification', completed: true }) + ] + }) + ] }; export default meta; @@ -48,5 +50,5 @@ type Story = StoryObj; export const Verified: Story = {}; export const ChangeWaitsForOtherLink: Story = { - decorators: [applicationConfig({ providers: answerWith({ purpose: 'change', completed: false }) })] + decorators: [applicationConfig({ providers: [answerWith({ purpose: 'change', completed: false })] })] }; \ No newline at end of file diff --git a/projects/ngx-auth/confirm-password-reset/confirm-password-reset-config.model.ts b/projects/ngx-auth/confirm-password-reset/confirm-password-reset-config.model.ts index b00896b..523a46c 100644 --- a/projects/ngx-auth/confirm-password-reset/confirm-password-reset-config.model.ts +++ b/projects/ngx-auth/confirm-password-reset/confirm-password-reset-config.model.ts @@ -31,7 +31,7 @@ export type ConfirmPasswordResetLabels = { */ login: string, /** - * Shown when a request failed without a message of zibri, like without a connection. + * Shown when a request failed without a message of the api, like without a connection. */ failed: string }; @@ -49,8 +49,8 @@ export type ConfirmPasswordResetConfig = { */ requestPasswordResetRoute: string, /** - * The least number of characters of a new password, the minLength of the password policy of zibri. Without it, - * zibri says what is too short. + * The least number of characters of a new password, the minLength of the password policy of the api. Without it, + * the api says what is too short. */ newPasswordMinLength: number | undefined }; \ No newline at end of file diff --git a/projects/ngx-auth/confirm-password-reset/confirm-password-reset.component.ts b/projects/ngx-auth/confirm-password-reset/confirm-password-reset.component.ts index 1df3923..bff3942 100644 --- a/projects/ngx-auth/confirm-password-reset/confirm-password-reset.component.ts +++ b/projects/ngx-auth/confirm-password-reset/confirm-password-reset.component.ts @@ -10,8 +10,8 @@ import { CONFIRM_PASSWORD_RESET_CONFIG } from './confirm-password-reset-config.p import { PasswordResetState } from './password-reset-state.type'; /** - * The page the link of a password reset opens, which sets a new password. Zibri adds the token to the - * CONFIRM_PASSWORD_RESET_URL as the last segment, so its route reads it as the parameter token: + * The page the link of a password reset opens, which sets a new password. The api adds the token to the link as the + * last segment, like zibri to its CONFIRM_PASSWORD_RESET_URL, so its route reads it as the parameter token: * `{ path: 'reset-password/:token', component: ConfirmPasswordResetComponent }`. It checks the link once it shows in the * browser, and offers a new one when it doesn't work anymore. Changing the password ends every login of the user. * Its texts come from provideConfirmPasswordResetConfig. @@ -63,7 +63,7 @@ export class ConfirmPasswordResetComponent { protected readonly newPassword: WritableSignal = signal(''); /** - * What zibri answered a refused request with, empty while nothing was refused. + * What the api answered a refused request with, empty while nothing was refused. */ protected readonly errorParagraphs: WritableSignal = signal([]); diff --git a/projects/ngx-auth/confirm-password-reset/confirm-password-reset.stories.ts b/projects/ngx-auth/confirm-password-reset/confirm-password-reset.stories.ts index 9782623..ac03153 100644 --- a/projects/ngx-auth/confirm-password-reset/confirm-password-reset.stories.ts +++ b/projects/ngx-auth/confirm-password-reset/confirm-password-reset.stories.ts @@ -1,5 +1,5 @@ import { provideHttpClient, withInterceptors } from '@angular/common/http'; -import { Component, DestroyRef, ElementRef, EnvironmentProviders, inject, input, InputSignal, OnInit, Provider, Service } from '@angular/core'; +import { Component, DestroyRef, ElementRef, inject, input, InputSignal, OnInit, Provider, Service } from '@angular/core'; import { provideRouter, Router, RouterOutlet, withDisabledInitialNavigation } from '@angular/router'; import { authInterceptor, AuthService, provideAuth } from '@service-soft/ngx-auth/auth'; import { applicationConfig, Meta, StoryObj } from '@storybook/angular'; @@ -12,19 +12,11 @@ import { ConfirmPasswordResetComponent } from './confirm-password-reset.componen class StoryAuthService extends AuthService {} // zibri, as far as the page gets: the link of the story works or doesn't. -function answerWith(isValid: boolean): (Provider | EnvironmentProviders)[] { - return [ - // the page reads the token from its route, which the story opens itself instead of the url of storybook - provideRouter([{ path: 'reset-password/:token', component: ConfirmPasswordResetComponent }], withDisabledInitialNavigation()), - provideHttpClient(withInterceptors([ - authInterceptor, - HttpTestingUtilities.answerWith({ - 'POST /api/auth/verify-password-reset-token': { status: 200, body: { isValid } }, - 'POST /api/auth/confirm-password-reset': { status: 204 } - }) - ])), - provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }) - ]; +function answerWith(isValid: boolean): Provider { + return HttpTestingUtilities.provideAnswers({ + 'POST /api/auth/verify-password-reset-token': { status: 200, body: { isValid } }, + 'POST /api/auth/confirm-password-reset': { status: 204 } + }); } // opens the link of the email, and sets a new password once the page asks for it when the story says so. @@ -62,7 +54,17 @@ class PasswordResetLinkComponent implements OnInit { const meta: Meta = { title: 'Auth/Confirm password reset', component: PasswordResetLinkComponent, - decorators: [applicationConfig({ providers: answerWith(true) })] + decorators: [ + applicationConfig({ + providers: [ + // the page reads the token from its route, which the story opens itself instead of the url of storybook + provideRouter([{ path: 'reset-password/:token', component: ConfirmPasswordResetComponent }], withDisabledInitialNavigation()), + provideHttpClient(withInterceptors([authInterceptor])), + provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }), + answerWith(true) + ] + }) + ] }; export default meta; @@ -71,7 +73,7 @@ type Story = StoryObj; export const Default: Story = {}; export const LinkDoesNotWork: Story = { - decorators: [applicationConfig({ providers: answerWith(false) })] + decorators: [applicationConfig({ providers: [answerWith(false)] })] }; export const Changed: Story = { diff --git a/projects/ngx-auth/email/email-settings-config.model.ts b/projects/ngx-auth/email/email-settings-config.model.ts index 60d15fc..f09813f 100644 --- a/projects/ngx-auth/email/email-settings-config.model.ts +++ b/projects/ngx-auth/email/email-settings-config.model.ts @@ -35,7 +35,7 @@ export type EmailSettingsLabels = { */ changeRequested: (newEmail: string) => string, /** - * Shown when a request failed without a message of zibri, like without a connection. + * Shown when a request failed without a message of the api, like without a connection. */ failed: string }; diff --git a/projects/ngx-auth/email/email-settings.component.ts b/projects/ngx-auth/email/email-settings.component.ts index ab15483..e7d2013 100644 --- a/projects/ngx-auth/email/email-settings.component.ts +++ b/projects/ngx-auth/email/email-settings.component.ts @@ -10,9 +10,9 @@ import { EMAIL_SETTINGS_CONFIG } from './email-settings-config.provider'; /** * The email of the logged in user, for the page of their account: whether it is verified, a link to verify it, and - * changing it, which zibri mails a link for. To change it, zibri wants the second factor or a recent login, which the - * interceptor asks the user for with the secondFactorPrompt. Its heading is a h2, below the heading of that page. Its - * texts come from provideEmailSettingsConfig. + * changing it, which the api mails a link for. To change it, the api wants the second factor or a recent login, which + * the interceptor asks the user for with the secondFactorPrompt. Its heading is a h2, below the heading of that page. + * Its texts come from provideEmailSettingsConfig. */ @Component({ selector: 'ngx-email-settings', @@ -59,7 +59,7 @@ export class EmailSettingsComponent { protected readonly newEmailErrorShown: WritableSignal = signal(false); /** - * What zibri answered the last refused request with, empty while nothing was refused. + * What the api answered the last refused request with, empty while nothing was refused. */ protected readonly errorParagraphs: WritableSignal = signal([]); diff --git a/projects/ngx-auth/email/email-settings.stories.ts b/projects/ngx-auth/email/email-settings.stories.ts index b56f756..9b7f5a0 100644 --- a/projects/ngx-auth/email/email-settings.stories.ts +++ b/projects/ngx-auth/email/email-settings.stories.ts @@ -31,8 +31,9 @@ const meta: Meta = { applicationConfig({ providers: [ provideRouter([]), - provideHttpClient(withInterceptors([authInterceptor, HttpTestingUtilities.answerWith({})])), - provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }) + provideHttpClient(withInterceptors([authInterceptor])), + provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }), + HttpTestingUtilities.provideAnswers({}) ] }) ] diff --git a/projects/ngx-auth/identities/connectable-provider.model.ts b/projects/ngx-auth/identities/connectable-provider.model.ts index e74798a..a3c3ca7 100644 --- a/projects/ngx-auth/identities/connectable-provider.model.ts +++ b/projects/ngx-auth/identities/connectable-provider.model.ts @@ -3,7 +3,7 @@ */ export type ConnectableProvider = { /** - * The name of its authenticator in zibri. + * The name of its authenticator in the api. */ authenticator: string, /** diff --git a/projects/ngx-auth/identities/identities-config.model.ts b/projects/ngx-auth/identities/identities-config.model.ts index dd5b79e..119e41b 100644 --- a/projects/ngx-auth/identities/identities-config.model.ts +++ b/projects/ngx-auth/identities/identities-config.model.ts @@ -53,7 +53,7 @@ export type IdentitiesLabels = { */ removed: string, /** - * Shown when a request failed without a message of zibri, like without a connection. + * Shown when a request failed without a message of the api, like without a connection. */ failed: string }; @@ -67,12 +67,12 @@ export type IdentitiesConfig = { */ labels: IdentitiesLabels, /** - * The providers the user can connect, which zibri needs to allow the page as a redirect. + * The providers the user can connect, which the api needs to allow the page as a redirect. */ providers: IdentityProvider[], /** - * The name of the passkey authenticator of zibri, which offers to add a passkey, or undefined for an app without - * one. + * The name of the passkey authenticator of the api, like a `PasskeyAuthenticator` of zibri, which offers to add a + * passkey, or undefined for an app without one. */ passkeyAuthenticator: string | undefined }; \ No newline at end of file diff --git a/projects/ngx-auth/identities/identities.component.ts b/projects/ngx-auth/identities/identities.component.ts index 0fda44f..a28cdd4 100644 --- a/projects/ngx-auth/identities/identities.component.ts +++ b/projects/ngx-auth/identities/identities.component.ts @@ -14,8 +14,9 @@ import { IdentityRow } from './identity-row.model'; /** * The ways to log in of the logged in user, for the page of their account, besides their password: the providers they * connected and their passkeys. Connects a provider, adds a passkey, and removes one after asking. To change them, - * zibri wants the second factor or a recent login, which the interceptor asks the user for with the secondFactorPrompt. - * Its heading is a h2, below the heading of that page. The providers and texts come from provideIdentitiesConfig. + * the api wants the second factor or a recent login, which the interceptor asks the user for with the + * secondFactorPrompt. Its heading is a h2, below the heading of that page. The providers and texts come from + * provideIdentitiesConfig. */ @Component({ selector: 'ngx-identities', @@ -51,7 +52,7 @@ export class IdentitiesComponent { protected readonly labels: IdentitiesLabels = this.config.labels; /** - * What zibri answered the last refused request with, empty while nothing was refused. + * What the api answered the last refused request with, empty while nothing was refused. */ protected readonly errorParagraphs: WritableSignal = signal([]); @@ -74,7 +75,7 @@ export class IdentitiesComponent { }))); /** - * The providers the user hasn't connected yet, once zibri said which ones they have. + * The providers the user hasn't connected yet, once the api said which ones they have. */ protected readonly connectableProviders: Signal = computed(() => { const identities: LinkedIdentity[] | undefined = this.identities(); @@ -114,7 +115,7 @@ export class IdentitiesComponent { /** * Has the device create a passkey that logs in, listed under the email of the user. - * @param authenticator - The name of the passkey authenticator of zibri. + * @param authenticator - The name of the passkey authenticator of the api. */ protected async addPasskey(authenticator: string): Promise { await this.run(async () => { diff --git a/projects/ngx-auth/identities/identities.stories.ts b/projects/ngx-auth/identities/identities.stories.ts index 392a0fb..84d45a8 100644 --- a/projects/ngx-auth/identities/identities.stories.ts +++ b/projects/ngx-auth/identities/identities.stories.ts @@ -1,5 +1,5 @@ import { provideHttpClient, withInterceptors } from '@angular/common/http'; -import { EnvironmentProviders, Provider, Service } from '@angular/core'; +import { Provider, Service } from '@angular/core'; import { provideRouter } from '@angular/router'; import { authInterceptor, AuthService, LinkedIdentity, provideAuth } from '@service-soft/ngx-auth/auth'; import { applicationConfig, Meta, StoryObj } from '@storybook/angular'; @@ -12,22 +12,8 @@ import { IdentitiesComponent } from './identities.component'; class StoryAuthService extends AuthService {} // zibri, as far as the page gets: the user of the story has these identities. -function answerIdentitiesWith(identities: LinkedIdentity[]): (Provider | EnvironmentProviders)[] { - return [ - provideRouter([]), - provideHttpClient(withInterceptors([ - authInterceptor, - HttpTestingUtilities.answerWith({ 'GET /api/auth/identities': { status: 200, body: identities } }) - ])), - provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }), - provideIdentitiesConfig({ - providers: [ - { authenticator: 'google', name: 'Google', apiAccess: [{ label: 'Allow access to your calendar', scopes: ['calendar'] }] }, - { authenticator: 'github', name: 'GitHub' } - ], - passkeyAuthenticator: 'passkey' - }) - ]; +function answerIdentitiesWith(identities: LinkedIdentity[]): Provider { + return HttpTestingUtilities.provideAnswers({ 'GET /api/auth/identities': { status: 200, body: identities } }); } const meta: Meta = { @@ -35,10 +21,22 @@ const meta: Meta = { component: IdentitiesComponent, decorators: [ applicationConfig({ - providers: answerIdentitiesWith([ - { authenticator: 'google', identity: { id: 'identity-1', forLogin: true } }, - { authenticator: 'passkey', identity: { id: 'identity-2', createdAt: '2026-11-11T10:00:00.000Z' } } - ]) + providers: [ + provideRouter([]), + provideHttpClient(withInterceptors([authInterceptor])), + provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }), + provideIdentitiesConfig({ + providers: [ + { authenticator: 'google', name: 'Google', apiAccess: [{ label: 'Allow access to your calendar', scopes: ['calendar'] }] }, + { authenticator: 'github', name: 'GitHub' } + ], + passkeyAuthenticator: 'passkey' + }), + answerIdentitiesWith([ + { authenticator: 'google', identity: { id: 'identity-1', forLogin: true } }, + { authenticator: 'passkey', identity: { id: 'identity-2', createdAt: '2026-11-11T10:00:00.000Z' } } + ]) + ] }) ] }; @@ -49,5 +47,5 @@ type Story = StoryObj; export const Default: Story = {}; export const NoneLinked: Story = { - decorators: [applicationConfig({ providers: answerIdentitiesWith([]) })] + decorators: [applicationConfig({ providers: [answerIdentitiesWith([])] })] }; \ No newline at end of file diff --git a/projects/ngx-auth/identities/identity-api-access.model.ts b/projects/ngx-auth/identities/identity-api-access.model.ts index 2d0be53..44fb95d 100644 --- a/projects/ngx-auth/identities/identity-api-access.model.ts +++ b/projects/ngx-auth/identities/identity-api-access.model.ts @@ -7,7 +7,8 @@ export type IdentityApiAccess = { */ label: string, /** - * The scopes of the provider's apis it needs. Each has to be one of the `apiScopes` of the authenticator in zibri. + * The scopes of the provider's apis it needs. Each has to be one of the `apiScopes` of its authenticator in the + * api. */ scopes: string[] }; \ No newline at end of file diff --git a/projects/ngx-auth/identities/identity-provider.model.ts b/projects/ngx-auth/identities/identity-provider.model.ts index 83fb5e4..7d24766 100644 --- a/projects/ngx-auth/identities/identity-provider.model.ts +++ b/projects/ngx-auth/identities/identity-provider.model.ts @@ -5,7 +5,7 @@ import { IdentityApiAccess } from './identity-api-access.model'; */ export type IdentityProvider = { /** - * The name of its authenticator in zibri, like 'google'. + * The name of its authenticator in the api, like 'google'. */ authenticator: string, /** diff --git a/projects/ngx-auth/identities/identity-row.model.ts b/projects/ngx-auth/identities/identity-row.model.ts index af32624..1ee545e 100644 --- a/projects/ngx-auth/identities/identity-row.model.ts +++ b/projects/ngx-auth/identities/identity-row.model.ts @@ -9,7 +9,7 @@ export type IdentityRow = { */ id: string, /** - * The name of its authenticator in zibri. + * The name of its authenticator in the api. */ authenticator: string, /** diff --git a/projects/ngx-auth/locale/messages.de.xlf b/projects/ngx-auth/locale/messages.de.xlf new file mode 100644 index 0000000..59fde25 --- /dev/null +++ b/projects/ngx-auth/locale/messages.de.xlf @@ -0,0 +1,903 @@ + + + + + + Accept invitation + Einladung annehmen + + + The invitation was accepted. + Die Einladung wurde angenommen. + + + Your account is ready. Log in with your password. + Ihr Konto ist bereit. Melden Sie sich mit Ihrem Passwort an. + + + Continue + Weiter + + + Decline + Ablehnen + + + The invitation was declined. + Die Einladung wurde abgelehnt. + + + Something went wrong. Please try again. + Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut. + + + This link doesn't work. It ran out, or was used or revoked already. + Dieser Link funktioniert nicht. Er ist abgelaufen, wurde bereits verwendet oder wurde widerrufen. + + + You are invited as + Sie sind eingeladen als + + + Log in + Anmelden + + + Log in as the invited account to accept the invitation. + Melden Sie sich mit dem eingeladenen Konto an, um die Einladung anzunehmen. + + + Log out + Abmelden + + + You are logged in with another account. Log out, and log in as the invited one to accept the invitation. + Sie sind mit einem anderen Konto angemeldet. Melden Sie sich ab und mit dem eingeladenen Konto wieder an, um die Einladung anzunehmen. + + + Password + Passwort + + + This link ran out. A new one was mailed to the invited address. + Dieser Link ist abgelaufen. Ein neuer wurde an die eingeladene Adresse gesendet. + + + Invitation + Einladung + + + Accepting logs you in, without a password. Later, you log in with a link sent to your email. + Wenn Sie annehmen, werden Sie ohne Passwort angemeldet. Später melden Sie sich mit einem Link an, den wir an Ihre E-Mail-Adresse senden. + + + Your password was changed. Your other devices were logged out. + Ihr Passwort wurde geändert. Ihre anderen Geräte wurden abgemeldet. + + + Current password + Aktuelles Passwort + + + Something went wrong. Please try again. + Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut. + + + New password + Neues Passwort + + + Change password + Passwort ändern + + + Change your password + Passwort ändern + + + Your email address was changed. + Ihre E-Mail-Adresse wurde geändert. + + + Continue + Weiter + + + Something went wrong. Please try again. + Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut. + + + Log in + Anmelden + + + Your email address + Ihre E-Mail-Adresse + + + Your email address is verified. + Ihre E-Mail-Adresse ist bestätigt. + + + Thank you. The change waits for you to follow the link we sent to your other email address as well. + Vielen Dank. Die Änderung wird wirksam, sobald Sie auch dem Link folgen, den wir an Ihre andere E-Mail-Adresse gesendet haben. + + + Your password was changed. Log in with your new password. + Ihr Passwort wurde geändert. Melden Sie sich mit Ihrem neuen Passwort an. + + + Something went wrong. Please try again. + Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut. + + + This link doesn't work anymore. It ran out, or was used already. + Dieser Link funktioniert nicht mehr. Er ist abgelaufen oder wurde bereits verwendet. + + + Log in + Anmelden + + + New password + Neues Passwort + + + Get a new link + Neuen Link anfordern + + + Save password + Passwort speichern + + + Choose a new password + Neues Passwort wählen + + + Change email address + E-Mail-Adresse ändern + + + We sent a link to . Your email address changes once you followed it. + Wir haben einen Link an gesendet. Ihre E-Mail-Adresse ändert sich, sobald Sie ihm gefolgt sind. + + + Something went wrong. Please try again. + Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut. + + + New email address + Neue E-Mail-Adresse + + + not verified yet + noch nicht bestätigt + + + Send a link to verify it + Link zur Bestätigung senden + + + Email address + E-Mail-Adresse + + + We sent you a link to verify your email address. + Wir haben Ihnen einen Link zur Bestätigung Ihrer E-Mail-Adresse gesendet. + + + verified + bestätigt + + + Add a passkey + Passkey hinzufügen + + + Cancel + Abbrechen + + + Connect + verbinden + + + Something went wrong. Please try again. + Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut. + + + for its apis only + nur für Schnittstellen + + + Passkey + Passkey + + + Passkey added. + Passkey hinzugefügt. + + + added on + hinzugefügt am + + + Remove + Entfernen + + + You can't log in this way anymore. Keep another way to log in, like your password. + Sie können sich auf diese Weise nicht mehr anmelden. Behalten Sie eine andere Möglichkeit zur Anmeldung, etwa Ihr Passwort. + + + Remove this way to log in? + Diese Anmeldemöglichkeit entfernen? + + + Removed. + Entfernt. + + + Ways to log in + Anmeldemöglichkeiten + + + Email + E-Mail + + + Something went wrong. Please try again. + Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut. + + + This link doesn't work. Ask for a new one. + Dieser Link funktioniert nicht. Fordern Sie einen neuen an. + + + Log in + Anmelden + + + If that email has an account, a new link to log in is on its way. + Falls zu dieser E-Mail-Adresse ein Konto gehört, ist ein neuer Link zur Anmeldung unterwegs. + + + Log in with the link from your email. It works once. + Melden Sie sich mit dem Link aus Ihrer E-Mail an. Er ist nur einmal gültig. + + + Email me a new link + Neuen Link per E-Mail senden + + + Log in + Anmelden + + + Back + Zurück + + + Change password + Passwort ändern + + + Email + E-Mail + + + Your second factor is on. Confirm it once more to log in, with the next code. + Ihr zweiter Faktor ist eingeschaltet. Bestätigen Sie ihn zur Anmeldung noch einmal, mit dem nächsten Code. + + + Your account needs a second factor before you can log in. Choose how you want to confirm it's you. + Ihr Konto benötigt einen zweiten Faktor, bevor Sie sich anmelden können. Wählen Sie, wie Sie bestätigen möchten, dass Sie es sind. + + + Set up a second factor + Zweiten Faktor einrichten + + + Something went wrong. Please try again. + Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut. + + + Forgot your password? + Passwort vergessen? + + + Log in + Anmelden + + + If that email has an account, a link to log in is on its way. + Falls zu dieser E-Mail-Adresse ein Konto gehört, ist ein Link zur Anmeldung unterwegs. + + + Log in with a passkey + Mit Passkey anmelden + + + New password + Neues Passwort + + + Password + Passwort + + + Your password has to be changed before you can go on. + Ihr Passwort muss geändert werden, bevor Sie fortfahren können. + + + Choose a new password + Neues Passwort wählen + + + Email me a link + Link per E-Mail senden + + + Confirm it's you + Bestätigen Sie, dass Sie es sind + + + Log in + Anmelden + + + Back + Zurück + + + Back to the login + Zurück zur Anmeldung + + + This account at the provider is connected to another user already. + Dieses Konto beim Anbieter ist bereits mit einem anderen Benutzer verbunden. + + + You didn't allow the login at the provider. + Sie haben die Anmeldung beim Anbieter nicht erlaubt. + + + The login took too long, or was started in another browser. Please try again. + Die Anmeldung hat zu lange gedauert oder wurde in einem anderen Browser begonnen. Bitte versuchen Sie es erneut. + + + Logging in didn't work. Please try again later. + Die Anmeldung hat nicht funktioniert. Bitte versuchen Sie es später erneut. + + + The answer of the provider couldn't be checked. Please try again. + Die Antwort des Anbieters konnte nicht geprüft werden. Bitte versuchen Sie es erneut. + + + This account at the provider can't be used to log in. + Dieses Konto beim Anbieter kann nicht zur Anmeldung verwendet werden. + + + The account of this login doesn't exist anymore. + Das Konto dieser Anmeldung existiert nicht mehr. + + + The provider didn't answer as expected. Please try again later. + Der Anbieter hat nicht wie erwartet geantwortet. Bitte versuchen Sie es später erneut. + + + You can't log in with this account right now. + Sie können sich mit diesem Konto derzeit nicht anmelden. + + + Logging in didn't work + Die Anmeldung hat nicht funktioniert + + + Back to the login + Zurück zur Anmeldung + + + Email + E-Mail + + + Something went wrong. Please try again. + Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut. + + + Enter the email of your account, and we send you a link to choose a new password. + Geben Sie die E-Mail-Adresse Ihres Kontos ein, und wir senden Ihnen einen Link, mit dem Sie ein neues Passwort wählen können. + + + Send link + Link senden + + + If an account belongs to this email, we sent it a link. It only works for a short time. + Falls zu dieser E-Mail-Adresse ein Konto gehört, haben wir einen Link an sie gesendet. Er ist nur kurze Zeit gültig. + + + Reset your password + Passwort zurücksetzen + + + Code + Code + + + We sent you a code. + Wir haben Ihnen einen Code gesendet. + + + Confirm + Bestätigen + + + Get a code by email + Code per E-Mail erhalten + + + Enter the code we sent to your email. + Geben Sie den Code ein, den wir an Ihre E-Mail-Adresse gesendet haben. + + + Codes by email + Codes per E-Mail + + + Use your authenticator app + Authenticator-App verwenden + + + Enter the code your authenticator app shows. + Geben Sie den Code ein, den Ihre Authenticator-App anzeigt. + + + Authenticator app + Authenticator-App + + + Use a passkey + Passkey verwenden + + + Use a passkey of this device, or your security key. + Verwenden Sie einen Passkey dieses Geräts oder Ihren Sicherheitsschlüssel. + + + Passkeys + Passkeys + + + Use a recovery code + Wiederherstellungscode verwenden + + + Enter one of the recovery codes you saved. + Geben Sie einen der Wiederherstellungscodes ein, die Sie gespeichert haben. + + + Recovery codes + Wiederherstellungscodes + + + Get a code by text message + Code per SMS erhalten + + + Enter the code we sent to your phone. + Geben Sie den Code ein, den wir an Ihr Telefon gesendet haben. + + + Codes by text message + Codes per SMS + + + We sent you a new code. + Wir haben Ihnen einen neuen Code gesendet. + + + None of your second factors can be used here. + Keiner Ihrer zweiten Faktoren kann hier verwendet werden. + + + Send a new code + Neuen Code senden + + + Use passkey + Passkey verwenden + + + Acts in + Handelt in + + + Add an API key + API-Schlüssel hinzufügen + + + The API key was created. + Der API-Schlüssel wurde erstellt. + + + Name of the key + Name des Schlüssels + + + What sends it, like the assistant of the team + Was ihn sendet, etwa der Assistent des Teams + + + API keys + API-Schlüssel + + + Only in the tenant you act in + Nur im Mandanten, in dem Sie handeln + + + Otherwise the key acts in every tenant the account is a member of + Sonst handelt der Schlüssel in jedem Mandanten, in dem das Konto Mitglied ist + + + Cancel + Abbrechen + + + Change the roles + Rollen ändern + + + The key was copied. + Der Schlüssel wurde kopiert. + + + Copy the key + Schlüssel kopieren + + + The key couldn't be copied. Select it and copy it yourself. + Der Schlüssel konnte nicht kopiert werden. Markieren und kopieren Sie ihn selbst. + + + Create a service account + Dienstkonto erstellen + + + The service account was created. + Das Dienstkonto wurde erstellt. + + + Created + Erstellt + + + Delete + Löschen + + + Delete the service account ? + Dienstkonto löschen? + + + Its API keys are revoked, and everything that sends one of them is refused. What it proposed, like approval requests, stays for a person to decide. + Seine API-Schlüssel werden widerrufen, und alles, was einen davon sendet, wird abgewiesen. Was es vorgeschlagen hat, etwa Genehmigungsanfragen, bleibt, damit eine Person darüber entscheidet. + + + The service account was deleted. + Das Dienstkonto wurde gelöscht. + + + Accounts of AI assistants and integrations. They never log in, and call the api with their API keys. + Konten von KI-Assistenten und Integrationen. Sie melden sich nie an und rufen die API mit ihren API-Schlüsseln auf. + + + Done + Fertig + + + Every tenant of the account + Jeder Mandant des Kontos + + + Expires + Läuft ab + + + The key stops working at the end of the day. Leave it empty for a key that works until it is revoked. + Der Schlüssel funktioniert bis zum Ende des Tages. Lassen Sie das Feld leer für einen Schlüssel, der funktioniert, bis er widerrufen wird. + + + Something went wrong. Please try again. + Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut. + + + Last used + Zuletzt verwendet + + + Loading + Wird geladen + + + The service accounts couldn't be loaded. + Die Dienstkonten konnten nicht geladen werden. + + + MCP tools it can use + MCP-Tools, die es nutzen kann + + + By its roles in the tenant you act in. A key that lists fewer permissions opens fewer of them. + Nach seinen Rollen im Mandanten, in dem Sie handeln. Ein Schlüssel mit weniger Berechtigungen öffnet weniger davon. + + + The tools couldn't be loaded. + Die Tools konnten nicht geladen werden. + + + Name + Name + + + What it is for, like assistant: lowercase letters, digits and hyphens between them + Wofür es ist, etwa assistent: Kleinbuchstaben, Ziffern und Bindestriche dazwischen + + + Never + Nie + + + Never + Nie + + + It has no API key yet. + Es hat noch keinen API-Schlüssel. + + + Its roles open none of the tools. + Seine Rollen öffnen keines der Tools. + + + There are no service accounts yet. + Es gibt noch keine Dienstkonten. + + + None + Keine + + + Another tenant only + Nur ein anderer Mandant + + + Permissions + Berechtigungen + + + What the key may do, as far as the roles of the account allow it + Was der Schlüssel darf, soweit die Rollen des Kontos es erlauben + + + Reads + Liest + + + Only for tokens bound to a key of the client (DPoP) + Nur für Tokens, die an einen Schlüssel des Clients gebunden sind (DPoP) + + + Such a key is only exchanged for tokens, and never taken in a header. Leave it off for an MCP client, which sends the key itself. + Ein solcher Schlüssel wird nur gegen Tokens getauscht und nie in einem Header angenommen. Lassen Sie es für einen MCP-Client aus, der den Schlüssel selbst sendet. + + + Revoke + Widerrufen + + + Revoke the API key ? + API-Schlüssel widerrufen? + + + Everything that sends the key is refused from then on. Its client needs a new key to call again. + Alles, was den Schlüssel sendet, wird ab dann abgewiesen. Sein Client braucht einen neuen Schlüssel, um wieder aufzurufen. + + + The API key was revoked. + Der API-Schlüssel wurde widerrufen. + + + Roles + Rollen + + + Its own roles, which apply in every tenant + Seine eigenen Rollen, die in jedem Mandanten gelten + + + The roles of were saved. + Die Rollen von wurden gespeichert. + + + Save + Speichern + + + The API key + Der API-Schlüssel + + + Copy the key now and keep it where its client reads it. You won't see it again: only a hash of it is stored. + Kopieren Sie den Schlüssel jetzt und hinterlegen Sie ihn dort, wo sein Client ihn liest. Sie sehen ihn nicht wieder: Gespeichert wird nur ein Hash davon. + + + Roles in this tenant + Rollen in diesem Mandanten + + + What it may do in the tenant you act in + Was es im Mandanten darf, in dem Sie handeln + + + This tenant only + Nur dieser Mandant + + + Service accounts + Dienstkonten + + + Proposes changes, which a person approves + Schlägt Änderungen vor, die eine Person genehmigt + + + Cancel + Abbrechen + + + Something went wrong. Please try again. + Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut. + + + last used on + zuletzt verwendet am + + + Logged out there. + Dort abgemeldet. + + + Log out + Abmelden + + + Log out everywhere + Überall abmelden + + + You are logged out on every device, this one too. + Sie werden auf allen Geräten abgemeldet, auch auf diesem. + + + Log out everywhere? + Überall abmelden? + + + this device + dieses Gerät + + + Where you're logged in + Wo Sie angemeldet sind + + + Unknown browser + Unbekannter Browser + + + Cancel + Abbrechen + + + Enter one of the codes, to show that you saved them. + Geben Sie einen der Codes ein, um zu zeigen, dass Sie sie gespeichert haben. + + + Create passkey + Passkey erstellen + + + Your device asks you to confirm the passkey, like with your fingerprint, your face or its PIN. + Ihr Gerät bittet Sie, den Passkey zu bestätigen, etwa mit Ihrem Fingerabdruck, Ihrem Gesicht oder seiner PIN. + + + Confirm it's you + Bestätigen Sie, dass Sie es sind + + + Something went wrong. Please try again. + Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut. + + + Get new codes + Neue Codes erhalten + + + Off + Aus + + + On + An + + + Phone number + Telefonnummer + + + With the country code, like +49 151 12345678. + Mit Ländervorwahl, etwa +49 151 12345678. + + + QR code for your authenticator app + QR-Code für Ihre Authenticator-App + + + Try again + Erneut versuchen + + + Save these codes somewhere safe, like in a password manager. Each one works once, when you can't use your other second factors. You won't see them again. + Bewahren Sie diese Codes an einem sicheren Ort auf, etwa in einem Passwort-Manager. Jeder Code funktioniert einmal, wenn Sie Ihre anderen zweiten Faktoren nicht verwenden können. Sie werden die Codes nicht noch einmal sehen. + + + Scan the QR code with your authenticator app, then enter the code it shows. + Scannen Sie den QR-Code mit Ihrer Authenticator-App und geben Sie dann den Code ein, den sie anzeigt. + + + Can't scan it? Enter this key in the app instead: + Scannen nicht möglich? Geben Sie stattdessen diesen Schlüssel in der App ein: + + + Send code + Code senden + + + Set up + Einrichten + + + Two-factor authentication + Zwei-Faktor-Authentifizierung + + + Turn off + Ausschalten + + + Your account is less safe with fewer second factors. + Mit weniger zweiten Faktoren ist Ihr Konto weniger sicher. + + + Turn off this second factor? + Diesen zweiten Faktor ausschalten? + + + Turn on + Einschalten + + + Turned off. + Ausgeschaltet. + + + Turned on. + Eingeschaltet. + + + + diff --git a/projects/ngx-auth/login-link/login-link-config-changes.model.ts b/projects/ngx-auth/login-link/login-link-config-changes.model.ts new file mode 100644 index 0000000..70fbd44 --- /dev/null +++ b/projects/ngx-auth/login-link/login-link-config-changes.model.ts @@ -0,0 +1,12 @@ +import { LoginLinkConfig, LoginLinkLabels } from './login-link-config.model'; + +/** + * The values to change in the config of the page a link to log in with opens. Everything is optional, including every + * single label. + */ +export type LoginLinkConfigChanges = Partial> & { + /** + * The labels to change. + */ + labels?: Partial +}; \ No newline at end of file diff --git a/projects/ngx-auth/login-link/login-link-config.model.ts b/projects/ngx-auth/login-link/login-link-config.model.ts new file mode 100644 index 0000000..18e0e9d --- /dev/null +++ b/projects/ngx-auth/login-link/login-link-config.model.ts @@ -0,0 +1,49 @@ +/** + * The texts of the page a link to log in with opens. The texts of the steps a login can wait for, like a second factor, + * come from provideLoginConfig and provideSecondFactorConfig. + */ +export type LoginLinkLabels = { + /** + * The heading of the page. + */ + title: string, + /** + * Says what the button does, above it. + */ + message: string, + /** + * The button that logs in with the link. + */ + login: string, + /** + * The label of the email input, which a new link is mailed to once the link doesn't work. + */ + email: string, + /** + * The button that mails a new link. + */ + requestLoginLink: string, + /** + * Shown once a new link was asked for. The api answers the same for an email without an account, so it says that a + * link is on its way if there is one. + */ + loginLinkSent: string, + /** + * Shown when the address of the page holds no link. + */ + invalid: string, + /** + * Shown when a request failed without a message of the api, like without a connection. + */ + failed: string +}; + +/** + * How the page a link to log in with opens looks and works. + */ +export type LoginLinkConfig = { + /** + * The texts of the page. + */ + labels: LoginLinkLabels +}; \ No newline at end of file diff --git a/projects/ngx-auth/login-link/login-link-config.provider.ts b/projects/ngx-auth/login-link/login-link-config.provider.ts new file mode 100644 index 0000000..7933210 --- /dev/null +++ b/projects/ngx-auth/login-link/login-link-config.provider.ts @@ -0,0 +1,49 @@ +import { inject, InjectionToken, Provider } from '@angular/core'; + +import { LoginLinkConfigChanges } from './login-link-config-changes.model'; +import { LoginLinkConfig } from './login-link-config.model'; + +/** + * How the page a link to log in with opens looks and works when nothing changes it. Its texts are $localize, which an + * app translates like its own, and resolved once the config is injected, so translations an app loads at runtime apply + * as well. + * @returns The default config. + */ +function getDefaultLoginLinkConfig(): LoginLinkConfig { + return { + labels: { + title: $localize`:@@ngx-auth.login-link.title:Log in`, + message: $localize`:@@ngx-auth.login-link.message:Log in with the link from your email. It works once.`, + login: $localize`:@@ngx-auth.login-link.login:Log in`, + email: $localize`:@@ngx-auth.login-link.email:Email`, + requestLoginLink: $localize`:@@ngx-auth.login-link.requestLoginLink:Email me a new link`, + loginLinkSent: $localize`:@@ngx-auth.login-link.loginLinkSent:If that email has an account, a new link to log in is on its way.`, + invalid: $localize`:@@ngx-auth.login-link.invalid:This link doesn't work. Ask for a new one.`, + failed: $localize`:@@ngx-auth.login-link.failed:Something went wrong. Please try again.` + } + }; +} + +/** + * How the page a link to log in with opens looks and works. Change it with provideLoginLinkConfig. + */ +export const LOGIN_LINK_CONFIG: InjectionToken = new InjectionToken('LOGIN_LINK_CONFIG', { + providedIn: 'root', + factory: () => getDefaultLoginLinkConfig() +}); + +/** + * Changes how the page a link to log in with opens looks and works, like its texts to translate them. Values you leave + * out keep the ones of the parent injector, including single labels. + * @param config - The values to change. + * @returns The provider for LOGIN_LINK_CONFIG. + */ +export function provideLoginLinkConfig(config: LoginLinkConfigChanges): Provider { + return { + provide: LOGIN_LINK_CONFIG, + useFactory: (): LoginLinkConfig => { + const parent: LoginLinkConfig = inject(LOGIN_LINK_CONFIG, { skipSelf: true, optional: true }) ?? getDefaultLoginLinkConfig(); + return { ...parent, ...config, labels: { ...parent.labels, ...config.labels } }; + } + }; +} \ No newline at end of file diff --git a/projects/ngx-auth/login-link/login-link.component.html b/projects/ngx-auth/login-link/login-link.component.html new file mode 100644 index 0000000..7dc7513 --- /dev/null +++ b/projects/ngx-auth/login-link/login-link.component.html @@ -0,0 +1,25 @@ +@if (pendingLogin(); as pending) { + + +} @else { +

{{ labels.title }}

+ @if (!refused()) { +

{{ labels.message }}

+ } + + + @if (refused()) { + + +
+
+ } @else { +
+ } +

{{ status() }}

+} \ No newline at end of file diff --git a/projects/ngx-auth/login-link/login-link.component.spec.ts b/projects/ngx-auth/login-link/login-link.component.spec.ts new file mode 100644 index 0000000..6a7498f --- /dev/null +++ b/projects/ngx-auth/login-link/login-link.component.spec.ts @@ -0,0 +1,191 @@ +import { provideHttpClient, withInterceptors } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component, Service } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideRouter, Router } from '@angular/router'; +import { RouterTestingHarness } from '@angular/router/testing'; +import { authInterceptor, AuthService, provideAuth } from '@service-soft/ngx-auth/auth'; +import { FormTestingUtilities } from 'testing/form'; +import { HttpTestingUtilities } from 'testing/http'; +import { afterEach, describe, expect, test, vi } from 'vitest'; +import { CurrentUserProfile, ErrorResponseBody, JwtAuthData, LoginLinkCredentials, LoginMethods, RequestLoginLinkInput, SecondFactorRequiredErrorBody } from 'zibri-contract'; + +import { LoginLinkComponent } from './login-link.component'; + +const API: string = 'https://api.example.com/auth'; +const HOUR: number = 3_600_000; + +@Service() +class AppAuthService extends AuthService {} + +@Component({ selector: 'ngx-page', template: '' }) +class PageComponent {} + +const ADA: CurrentUserProfile = { id: 'user-1', email: 'ada@example.com', kind: 'person', memberships: [], platformPermissions: [] }; + +// what zibri answers a link that expired. +const EXPIRED: ErrorResponseBody = { + status: 401, + name: 'UnauthorizedError', + message: 'This login link expired. Ask for a new one.', + paragraphs: ['This login link expired. Ask for a new one.'] +}; + +function createJwtData(): JwtAuthData { + const expirationDate: string = new Date(Date.now() + HOUR).toISOString(); + return { + userId: 'user-1', + roles: ['user'], + accessToken: { value: 'access-1', expirationDate }, + refreshToken: { value: 'refresh-1', expirationDate } + }; +} + +// what zibri answers a login by a link that waits for a second factor, of the methods that count for it. +function requireSecondFactor(methods: string[]): SecondFactorRequiredErrorBody { + return { + status: 401, + name: 'SecondFactorRequiredError', + message: 'A second factor is required.', + paragraphs: ['A second factor is required.'], + ticket: 'ticket-1', + methods + }; +} + +// opens the link of the email, which zibri ends with the token. +async function open(): Promise<[HTMLElement, RouterTestingHarness, HttpTestingController]> { + TestBed.configureTestingModule({ + providers: [ + provideRouter([ + { path: 'login-link/:token', component: LoginLinkComponent }, + { path: '**', component: PageComponent } + ]), + provideHttpClient(withInterceptors([authInterceptor])), + provideHttpClientTesting(), + provideAuth(AppAuthService, { apiUrl: API, strategy: 'jwt' }) + ] + }); + const harness: RouterTestingHarness = await RouterTestingHarness.create('/login-link/link-1'); + await harness.fixture.whenStable(); + return [harness.fixture.nativeElement as HTMLElement, harness, TestBed.inject(HttpTestingController)]; +} + +async function expectRequest(backend: HttpTestingController, method: string, path: string): Promise { + return await vi.waitFor(() => backend.expectOne({ method, url: `${API}/${path}` })); +} + +// presses the button of the page, which sends the token of the link. +async function logIn(root: HTMLElement, backend: HttpTestingController): Promise { + FormTestingUtilities.click(root, 'Log in'); + const login: TestRequest = await expectRequest(backend, 'POST', 'login?authenticator=login-link&strategy=jwt'); + const credentials: LoginLinkCredentials = { token: 'link-1' }; + expect(login.request.body).toEqual(credentials); + return login; +} + +async function answerCurrentUser(backend: HttpTestingController): Promise { + (await expectRequest(backend, 'GET', 'me')).flush(ADA); +} + +describe('LoginLinkComponent', () => { + afterEach(() => { + localStorage.clear(); + TestBed.inject(HttpTestingController).verify(); + }); + + test('logs in with the link only once the button is pressed, and opens afterLogin', async () => { + const [root, , backend] = await open(); + expect(FormTestingUtilities.getText(root, 'h1')).toBe('Log in'); + // a scanner of a mail provider that opens the link spends nothing + backend.expectNone(() => true); + + (await logIn(root, backend)).flush(createJwtData()); + await answerCurrentUser(backend); + + await vi.waitFor(() => expect(TestBed.inject(Router).url).toBe('/')); + expect(TestBed.inject(AppAuthService).loggedIn()).toBe(true); + }); + + test('shows the message zibri refuses an expired link with, and mails a new one', async () => { + const [root, harness, backend] = await open(); + + (await logIn(root, backend)).flush(EXPIRED, { status: 401, statusText: 'Unauthorized' }); + + await vi.waitFor(() => expect(FormTestingUtilities.getText(root, '[role="alert"]')).toBe('This login link expired. Ask for a new one.')); + expect(root.textContent).not.toContain('Log in with the link'); + // the button the user pressed is gone, so the focus moves on to the email of a new link + await vi.waitFor(() => expect(document.activeElement).toBe(FormTestingUtilities.findInput(root, 'email'))); + expect(TestBed.inject(AppAuthService).loggedIn()).toBe(false); + + FormTestingUtilities.type(root, 'email', 'ada@example.com'); + await harness.fixture.whenStable(); + FormTestingUtilities.click(root, 'Email me a new link'); + const request: TestRequest = await expectRequest(backend, 'POST', 'request-login-link'); + const input: RequestLoginLinkInput = { email: 'ada@example.com' }; + expect(request.request.body).toEqual(input); + HttpTestingUtilities.flushNoContent(request); + + await vi.waitFor(() => expect(FormTestingUtilities.getText(root, '[role="status"]')) + .toBe('If that email has an account, a new link to log in is on its way.')); + expect(FormTestingUtilities.getText(root, '[role="alert"]')).toBe(''); + }); + + test('shows the message of too many links, and keeps the button of a link zibri didn\'t answer', async () => { + const [root, harness, backend] = await open(); + + // without an answer, the link may still work + (await logIn(root, backend)).error(new ProgressEvent('error'), { status: 0, statusText: 'Unknown Error' }); + await vi.waitFor(() => expect(FormTestingUtilities.getText(root, '[role="alert"]')).toBe('Something went wrong. Please try again.')); + (await logIn(root, backend)).flush(EXPIRED, { status: 401, statusText: 'Unauthorized' }); + await vi.waitFor(() => expect(FormTestingUtilities.findInput(root, 'email')).not.toBeNull()); + + FormTestingUtilities.type(root, 'email', 'ada@example.com'); + await harness.fixture.whenStable(); + FormTestingUtilities.click(root, 'Email me a new link'); + const tooMany: ErrorResponseBody = { status: 429, name: 'TooManyRequestsError', message: 'Too many', paragraphs: ['Too many attempts. Try again in a minute.'] }; + (await expectRequest(backend, 'POST', 'request-login-link')).flush(tooMany, { status: 429, statusText: 'Too Many Requests' }); + + await vi.waitFor(() => expect(FormTestingUtilities.getText(root, '[role="alert"]')).toBe('Too many attempts. Try again in a minute.')); + expect(FormTestingUtilities.getText(root, '[role="status"]')).toBe(''); + }); + + test('continues with the second factor the login waits for, and opens afterLogin', async () => { + const [root, harness, backend] = await open(); + + (await logIn(root, backend)).flush(requireSecondFactor(['otp']), { status: 401, statusText: 'Unauthorized' }); + + await vi.waitFor(() => expect(FormTestingUtilities.getText(root, 'h1')).toBe('Confirm it\'s you')); + expect(document.activeElement).toBe(FormTestingUtilities.findInput(root, 'code')); + FormTestingUtilities.type(root, 'code', '123456'); + await harness.fixture.whenStable(); + FormTestingUtilities.click(root, 'Confirm'); + const confirm: TestRequest = await expectRequest(backend, 'POST', 'login/2fa/confirm?strategy=jwt'); + expect(confirm.request.headers.get('x-login-ticket')).toBe('ticket-1'); + expect(confirm.request.headers.get('x-authorization-otp')).toBe('123456'); + confirm.flush(createJwtData()); + await answerCurrentUser(backend); + + await vi.waitFor(() => expect(TestBed.inject(Router).url).toBe('/')); + }); + + test('has a user without a second factor enroll one other than codes by email, and goes back to the login', async () => { + const [root, harness, backend] = await open(); + + (await logIn(root, backend)).flush(requireSecondFactor([]), { status: 401, statusText: 'Unauthorized' }); + + await vi.waitFor(() => expect(FormTestingUtilities.getText(root, 'h1')).toBe('Set up a second factor')); + // the link proved the mailbox already + expect([...root.querySelectorAll('li')].map(item => item.textContent.trim())) + .toEqual(['Authenticator app', 'Codes by text message', 'Passkeys']); + + // like after the ticket ran out: the login asks the api how to log in, which is with a link only here + FormTestingUtilities.click(root, 'Back'); + const loginMethods: LoginMethods = { password: false, loginLink: true }; + (await expectRequest(backend, 'GET', 'login-methods')).flush(loginMethods); + await vi.waitFor(() => expect(FormTestingUtilities.findInput(root, 'password')).toBeNull()); + await harness.fixture.whenStable(); + expect(FormTestingUtilities.getText(root, 'h1')).toBe('Log in'); + expect(root.textContent).toContain('Email me a link'); + }); +}); \ No newline at end of file diff --git a/projects/ngx-auth/login-link/login-link.component.ts b/projects/ngx-auth/login-link/login-link.component.ts new file mode 100644 index 0000000..18453c5 --- /dev/null +++ b/projects/ngx-auth/login-link/login-link.component.ts @@ -0,0 +1,137 @@ +import { afterNextRender, Component, inject, Injector, Signal, signal, viewChild, WritableSignal } from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; +import { AUTH_CONFIG, AuthErrorUtilities, AuthService, LoginResult } from '@service-soft/ngx-auth/auth'; +import { LoginComponent, PendingLogin } from '@service-soft/ngx-auth/login'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { FormComponent } from '@service-soft/ui/form'; +import { InputStringComponent } from '@service-soft/ui/input-string'; + +import { LoginLinkLabels } from './login-link-config.model'; +import { LOGIN_LINK_CONFIG } from './login-link-config.provider'; + +/** + * The page a link to log in with opens, which logs in with it. The api adds the token to the link as the last segment, + * like zibri to the loginLinkUrl of its LOGIN_LINK_OPTIONS, so its route reads it as the parameter token: + * `{ path: 'login-link/:token', component: LoginLinkComponent, canActivate: [notLoggedInGuard] }`. It logs in once the + * user presses its button, never when it loads, so a scanner of a mail provider that opens the link spends nothing. + * When the login waits for a step, like a second factor or the first one of a user who has none, it continues with the + * steps of the LoginComponent. Once logged in, it opens afterLogin of provideAuth. A link that doesn't work anymore shows + * what the api answered, and offers to mail a new one. Its texts come from provideLoginLinkConfig, the ones of the + * steps from provideLoginConfig. + */ +@Component({ + selector: 'ngx-login-link', + templateUrl: './login-link.component.html', + imports: [FormComponent, InputStringComponent, ButtonComponent, LoginComponent], + host: { + class: 'block' + } +}) +export class LoginLinkComponent { + private readonly authService: AuthService = inject(AuthService); + + private readonly router: Router = inject(Router); + + private readonly injector: Injector = inject(Injector); + + private readonly afterLogin: string = inject(AUTH_CONFIG).routes.afterLogin; + + private readonly token: string | null = inject(ActivatedRoute).snapshot.paramMap.get('token'); + + private readonly emailInput: Signal = viewChild('emailInput'); + + // a second click while the request is on its way would spend the link twice. + private sending: boolean = false; + + /** + * The texts of the page. + */ + protected readonly labels: LoginLinkLabels = inject(LOGIN_LINK_CONFIG).labels; + + /** + * Whether the link doesn't work, which offers a new one instead of logging in. + */ + protected readonly refused: WritableSignal = signal(this.token == undefined); + + /** + * The login the link started while it waits for a step, like a second factor. + */ + protected readonly pendingLogin: WritableSignal = signal(undefined); + + /** + * The email the user typed, for a new link. + */ + protected readonly email: WritableSignal = signal(''); + + /** + * What the api answered a refused request with, empty while nothing was refused. + */ + protected readonly errorParagraphs: WritableSignal = signal(this.token == undefined ? [this.labels.invalid] : []); + + /** + * What the last request did, which screen readers announce. + */ + protected readonly status: WritableSignal = signal(''); + + /** + * Logs in with the link. + */ + protected async login(): Promise { + const token: string | null = this.token; + if (this.sending || token == undefined) { + return; + } + this.sending = true; + this.errorParagraphs.set([]); + try { + const result: LoginResult = await this.authService.loginWithLink(token); + if (result.type === 'loggedIn') { + await this.router.navigateByUrl(this.afterLogin); + return; + } + // the link proved the mailbox, so a code by email is no second factor of this login + this.pendingLogin.set({ result, emailCodesCount: false }); + } + catch (error) { + this.errorParagraphs.set(AuthErrorUtilities.findErrorParagraphs(error) ?? [this.labels.failed]); + // without an answer, or for too many attempts, the link may still work + if (!AuthErrorUtilities.isNetworkError(error) && !AuthErrorUtilities.isTooManyRequests(error)) { + this.refused.set(true); + // the button the user pressed is gone, and the focus with it + afterNextRender(() => this.emailInput()?.focus(), { injector: this.injector }); + } + } + finally { + this.sending = false; + } + } + + /** + * Mails a new link to the email. Says that it is on its way whatever the api answers, which is the same for an + * email without an account, unless it refused too many links. + */ + protected async requestLoginLink(): Promise { + if (this.sending) { + return; + } + this.sending = true; + this.errorParagraphs.set([]); + // screen readers announce the text again for a link asked for again + this.status.set(''); + try { + await this.authService.requestLoginLink(this.email()); + this.status.set(this.labels.loginLinkSent); + } + catch (error) { + // any other refusal says as little as the answer for an unknown email, so it is not shown either + if (AuthErrorUtilities.isTooManyRequests(error) || AuthErrorUtilities.isNetworkError(error)) { + this.errorParagraphs.set(AuthErrorUtilities.findErrorParagraphs(error) ?? [this.labels.failed]); + return; + } + this.status.set(this.labels.loginLinkSent); + } + finally { + this.sending = false; + } + } +} \ No newline at end of file diff --git a/projects/ngx-auth/login-link/login-link.stories.ts b/projects/ngx-auth/login-link/login-link.stories.ts new file mode 100644 index 0000000..9c3ce57 --- /dev/null +++ b/projects/ngx-auth/login-link/login-link.stories.ts @@ -0,0 +1,116 @@ +import { provideHttpClient, withInterceptors } from '@angular/common/http'; +import { Component, DestroyRef, ElementRef, inject, input, InputSignal, OnInit, Provider, Service } from '@angular/core'; +import { provideRouter, Router, RouterOutlet, withDisabledInitialNavigation } from '@angular/router'; +import { authInterceptor, AuthService, provideAuth } from '@service-soft/ngx-auth/auth'; +import { applicationConfig, Meta, StoryObj } from '@storybook/angular'; +import { FormTestingUtilities } from 'testing/form'; +import { FakeAnswer, HttpTestingUtilities } from 'testing/http'; +import { ErrorResponseBody, SecondFactorRequiredErrorBody } from 'zibri-contract'; + +import { LoginLinkComponent } from './login-link.component'; + +@Service() +class StoryAuthService extends AuthService {} + +// zibri, as far as the page gets: it answers the login with the link with the answer of the story. +function answerLoginWith(login: FakeAnswer): Provider { + return HttpTestingUtilities.provideAnswers({ 'POST /api/auth/login': login, 'POST /api/auth/request-login-link': { status: 204 } }); +} + +// what zibri answers a link that expired. +const EXPIRED: ErrorResponseBody = { + status: 401, + name: 'UnauthorizedError', + message: 'This login link expired. Ask for a new one.', + paragraphs: ['This login link expired. Ask for a new one.'] +}; + +// what zibri answers a login by a link that waits for a second factor, of the methods the user enrolled. +function requireSecondFactor(methods: string[]): FakeAnswer { + const body: SecondFactorRequiredErrorBody = { + status: 401, + name: 'SecondFactorRequiredError', + message: 'A second factor is required.', + paragraphs: ['A second factor is required.'], + ticket: 'ticket-1', + methods + }; + return { status: 401, body }; +} + +// opens the link of the email, and presses what the story says once it shows, like a user would. +@Component({ + selector: 'ngx-login-link-opener', + template: '', + imports: [RouterOutlet] +}) +class LoginLinkOpenerComponent implements OnInit { + private readonly router: Router = inject(Router); + + private readonly root: HTMLElement = inject>(ElementRef).nativeElement; + + private readonly destroyRef: DestroyRef = inject(DestroyRef); + + readonly logIn: InputSignal = input(false); + + readonly requestNewLink: InputSignal = input(false); + + ngOnInit(): void { + let loggedIn: boolean = false; + // the button and the form only show once the page rendered, and the answer of zibri came + const observer: MutationObserver = new MutationObserver(() => { + if (this.logIn() && !loggedIn && this.root.querySelector('button') != undefined) { + loggedIn = true; + FormTestingUtilities.click(this.root, 'Log in'); + } + if (this.requestNewLink() && FormTestingUtilities.findInput(this.root, 'email') != undefined) { + observer.disconnect(); + FormTestingUtilities.type(this.root, 'email', 'ada@example.com'); + FormTestingUtilities.click(this.root, 'Email me a new link'); + } + }); + observer.observe(this.root, { childList: true, subtree: true }); + this.destroyRef.onDestroy(() => observer.disconnect()); + void this.router.navigateByUrl('/login-link/story-token', { skipLocationChange: true }); + } +} + +const meta: Meta = { + title: 'Auth/Login link', + component: LoginLinkOpenerComponent, + decorators: [ + applicationConfig({ + providers: [ + // the page reads the token from its route, which the story opens itself instead of the url of storybook + provideRouter([{ path: 'login-link/:token', component: LoginLinkComponent }], withDisabledInitialNavigation()), + provideHttpClient(withInterceptors([authInterceptor])), + provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }), + answerLoginWith({ status: 401, body: EXPIRED }) + ] + }) + ] +}; +export default meta; + +type Story = StoryObj; + +export const Default: Story = {}; + +export const Expired: Story = { + args: { logIn: true } +}; + +export const NewLinkRequested: Story = { + args: { logIn: true, requestNewLink: true } +}; + +export const SecondFactor: Story = { + args: { logIn: true }, + decorators: [applicationConfig({ providers: [answerLoginWith(requireSecondFactor(['otp', 'recovery-code']))] })] +}; + +// a user without a second factor, whose account needs one: codes by email don't count after a link. +export const Enrollment: Story = { + args: { logIn: true }, + decorators: [applicationConfig({ providers: [answerLoginWith(requireSecondFactor([]))] })] +}; \ No newline at end of file diff --git a/projects/ngx-auth/login-link/ng-package.json b/projects/ngx-auth/login-link/ng-package.json new file mode 100644 index 0000000..70e0a80 --- /dev/null +++ b/projects/ngx-auth/login-link/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} \ No newline at end of file diff --git a/projects/ngx-auth/login-link/public-api.ts b/projects/ngx-auth/login-link/public-api.ts new file mode 100644 index 0000000..6672193 --- /dev/null +++ b/projects/ngx-auth/login-link/public-api.ts @@ -0,0 +1,4 @@ +export * from './login-link-config-changes.model'; +export * from './login-link-config.model'; +export * from './login-link-config.provider'; +export * from './login-link.component'; \ No newline at end of file diff --git a/projects/ngx-auth/login/login-config.model.ts b/projects/ngx-auth/login/login-config.model.ts index 3ba85c5..bce6294 100644 --- a/projects/ngx-auth/login/login-config.model.ts +++ b/projects/ngx-auth/login/login-config.model.ts @@ -25,6 +25,15 @@ export type LoginLabels = { * The link to the page that sends a link to reset the password. */ forgotPassword: string, + /** + * The button that mails a link to log in with, when the api takes one. + */ + requestLoginLink: string, + /** + * Shown once a link to log in with was asked for. The api answers the same for an email without an account, so it + * says that a link is on its way if there is one. + */ + loginLinkSent: string, /** * The button that logs in with a passkey. */ @@ -34,7 +43,7 @@ export type LoginLabels = { */ secondFactorTitle: string, /** - * Shown when zibri enrolled the first second factor without completing the login, which then waits for its next + * Shown when the api enrolled the first second factor without completing the login, which then waits for its next * code, like with an auth service of the app's own. */ enrolledMessage: string, @@ -67,7 +76,7 @@ export type LoginLabels = { */ changePassword: string, /** - * Shown when a request failed without a message of zibri, like without a connection. + * Shown when a request failed without a message of the api, like without a connection. */ failed: string }; @@ -87,18 +96,18 @@ export type LoginConfig = { */ requestPasswordResetRoute: string | undefined, /** - * The name of the passkey authenticator of zibri, which shows a button that logs in with a passkey, or undefined for - * an app without one. + * The name of the passkey authenticator of the api, like a `PasskeyAuthenticator` of zibri, which shows a button + * that logs in with a passkey, or undefined for an app without one. */ passkeyAuthenticator: string | undefined, /** * The providers to log in at. The browser comes back to the route of the login with a code, which the login - * completes, so add that route to the allowedRedirects of zibri. + * completes, so the api has to allow that route as a redirect, like in the allowedRedirects of zibri. */ providers: LoginProvider[], /** - * The least number of characters of a new password, the minLength of the password policy of zibri. Without it, - * zibri says what is too short. + * The least number of characters of a new password, the minLength of the password policy of the api. Without it, + * the api says what is too short. */ newPasswordMinLength: number | undefined }; \ No newline at end of file diff --git a/projects/ngx-auth/login/login-config.provider.ts b/projects/ngx-auth/login/login-config.provider.ts index 92444a7..c68c0d5 100644 --- a/projects/ngx-auth/login/login-config.provider.ts +++ b/projects/ngx-auth/login/login-config.provider.ts @@ -16,6 +16,8 @@ function getDefaultLoginConfig(): LoginConfig { password: $localize`:@@ngx-auth.login.password:Password`, login: $localize`:@@ngx-auth.login.login:Log in`, forgotPassword: $localize`:@@ngx-auth.login.forgotPassword:Forgot your password?`, + requestLoginLink: $localize`:@@ngx-auth.login.requestLoginLink:Email me a link`, + loginLinkSent: $localize`:@@ngx-auth.login.loginLinkSent:If that email has an account, a link to log in is on its way.`, loginWithPasskey: $localize`:@@ngx-auth.login.loginWithPasskey:Log in with a passkey`, secondFactorTitle: $localize`:@@ngx-auth.login.secondFactorTitle:Confirm it's you`, enrolledMessage: $localize`:@@ngx-auth.login.enrolledMessage:Your second factor is on. Confirm it once more to log in, with the next code.`, diff --git a/projects/ngx-auth/login/login-enrollment.component.ts b/projects/ngx-auth/login/login-enrollment.component.ts index 72accc7..49df960 100644 --- a/projects/ngx-auth/login/login-enrollment.component.ts +++ b/projects/ngx-auth/login/login-enrollment.component.ts @@ -51,6 +51,11 @@ export class LoginEnrollmentComponent { */ readonly email: InputSignal = input.required(); + /** + * Whether codes by email can be enrolled: not for a login by a link, which proved the mailbox already. + */ + readonly emailCodesCount: InputSignal = input.required(); + /** * Emits where the login stands once the method is on. */ @@ -64,9 +69,11 @@ export class LoginEnrollmentComponent { /** * The methods the user can pick. */ - // recovery codes are no first factor: logging in with one would spend one of the codes right away + // recovery codes are no first factor: logging in with one would spend one of the codes right away. Codes by email + // don't count after a login by a link, which zibri refuses to enroll then protected readonly methods: Signal = computed(() => Object.entries(this.secondFactorConfig.methods) - .filter(([, options]) => options != undefined && options.enrollment !== 'recoveryCodes') + .filter(([, options]) => options != undefined && options.enrollment !== 'recoveryCodes' + && (this.emailCodesCount() || options.enrollment !== 'emailCode')) .flatMap(([method]) => { const name: string | undefined = this.secondFactorConfig.labels.methods[method]?.name; return name == undefined ? [] : [{ method, name }]; diff --git a/projects/ngx-auth/login/login-provider.model.ts b/projects/ngx-auth/login/login-provider.model.ts index 99f83d5..408ecd4 100644 --- a/projects/ngx-auth/login/login-provider.model.ts +++ b/projects/ngx-auth/login/login-provider.model.ts @@ -3,7 +3,7 @@ */ export type LoginProvider = { /** - * The name of its authenticator in zibri, like 'google'. + * The name of its authenticator in the api, like 'google'. */ authenticator: string, /** @@ -11,8 +11,8 @@ export type LoginProvider = { */ label: string, /** - * The scopes of the provider's apis the login asks for as well, like a calendar the app reads, whose tokens zibri - * keeps for the user. Each has to be one of the `apiScopes` of the authenticator. None by default. + * The scopes of the provider's apis the login asks for as well, like a calendar the app reads, whose tokens the + * api keeps for the user. Each has to be one of the `apiScopes` of the authenticator. None by default. */ apiScopes?: string[] }; \ No newline at end of file diff --git a/projects/ngx-auth/login/login-step.model.ts b/projects/ngx-auth/login/login-step.model.ts index ffcff54..abcd824 100644 --- a/projects/ngx-auth/login/login-step.model.ts +++ b/projects/ngx-auth/login/login-step.model.ts @@ -41,7 +41,11 @@ export type EnrollmentStep = { /** * The ticket that continues the login. */ - ticket: string + ticket: string, + /** + * Whether codes by email can be enrolled: not for a login by a link, which proved the mailbox already. + */ + emailCodesCount: boolean }; /** @@ -59,6 +63,6 @@ export type PasswordChangeStep = { }; /** - * What the login shows: the email and password, then what the login of zibri waits for. + * What the login shows: the email and password, then what the login of the api waits for. */ export type LoginStep = CredentialsStep | SecondFactorStep | EnrollmentStep | PasswordChangeStep; \ No newline at end of file diff --git a/projects/ngx-auth/login/login.component.html b/projects/ngx-auth/login/login.component.html index b6470ed..f1c24d0 100644 --- a/projects/ngx-auth/login/login.component.html +++ b/projects/ngx-auth/login/login.component.html @@ -10,7 +10,13 @@

{{ title() }}

(passkeyRequested)="confirmPasskey(secondFactor, $event)" /> } @else if (enrollmentStep(); as enrollment) { - + } @else if (passwordChangeStep(); as passwordChange) { {{ title() }}
} @else { - + - + @if (offersPassword()) { + + }
- - @if (config.requestPasswordResetRoute; as requestPasswordResetRoute) { +
+ @if (offersPassword()) { + + @if (offersLoginLink()) { + + + } + } @else if (offersLoginLink()) { + + } +
+ @if (requestPasswordResetRoute(); as requestPasswordResetRoute) { {{ labels.forgotPassword }} } diff --git a/projects/ngx-auth/login/login.component.spec.ts b/projects/ngx-auth/login/login.component.spec.ts index c05b8d7..97a1b73 100644 --- a/projects/ngx-auth/login/login.component.spec.ts +++ b/projects/ngx-auth/login/login.component.spec.ts @@ -9,7 +9,7 @@ import { FormTestingUtilities } from 'testing/form'; import { HttpTestingUtilities } from 'testing/http'; import { AddedPasskeyDevice, PasskeyTestingUtilities } from 'testing/passkey'; import { afterEach, describe, expect, test, vi } from 'vitest'; -import { JwtAuthData } from 'zibri-contract'; +import { ErrorResponseBody, JwtAuthData, LoginMethods, RequestLoginLinkInput } from 'zibri-contract'; import { provideLoginConfig } from './login-config.provider'; import { LoginProvider } from './login-provider.model'; @@ -46,7 +46,22 @@ function createJwtData(): JwtAuthData { }; } -async function setup(url: string, providers: Provider[] = []): Promise<[RouterTestingHarness, HttpTestingController]> { +// what zibri answers GET /login-methods with, or undefined for an api without the route. +async function answerLoginMethods(backend: HttpTestingController, loginMethods: LoginMethods | undefined): Promise { + const request: TestRequest = await expectRequest(backend, 'GET', `${API}/login-methods`); + if (loginMethods == undefined) { + const notFound: ErrorResponseBody = { status: 404, name: 'NotFoundError', message: 'Not found', paragraphs: ['Not found'] }; + request.flush(notFound, { status: 404, statusText: 'Not Found' }); + return; + } + request.flush(loginMethods); +} + +async function setup( + url: string, + providers: Provider[] = [], + loginMethods?: LoginMethods +): Promise<[RouterTestingHarness, HttpTestingController]> { TestBed.configureTestingModule({ providers: [ provideRouter([ @@ -61,7 +76,10 @@ async function setup(url: string, providers: Provider[] = []): Promise<[RouterTe }); const harness: RouterTestingHarness = await RouterTestingHarness.create(); await harness.navigateByUrl(url); - return [harness, TestBed.inject(HttpTestingController)]; + const backend: HttpTestingController = TestBed.inject(HttpTestingController); + await answerLoginMethods(backend, loginMethods); + await harness.fixture.whenStable(); + return [harness, backend]; } function getRoot(harness: RouterTestingHarness): HTMLElement { @@ -308,6 +326,7 @@ describe('LoginComponent', () => { const codeVerifier: string | undefined = authService.findPendingProviderLogin()?.codeVerifier; await harness.navigateByUrl('/'); await harness.navigateByUrl('/login?code=code-1'); + await answerLoginMethods(backend, undefined); const login: TestRequest = await expectRequest(backend, 'POST', `${API}/login?authenticator=google&strategy=jwt`); expect(login.request.body).toEqual({ code: 'code-1', codeVerifier }); // the code works once, so it leaves the url before a reload sends it again @@ -355,6 +374,76 @@ describe('LoginComponent', () => { expect(findInput(harness, 'email')?.value).toBe('ada@example.com'); }); + test('offers a link next to the password when the api takes both, and says it is on its way whatever zibri answers', async () => { + const [harness, backend] = await setup('/login', [], { password: true, loginLink: true }); + await vi.waitFor(() => expect(getRoot(harness).textContent).toContain('Email me a link')); + expect(findInput(harness, 'password')).not.toBeNull(); + expect(getRoot(harness).querySelector('a')?.getAttribute('href')).toBe('/request-password-reset'); + + // the email is checked before a link is asked for, but the password isn't + await click(harness, 'Email me a link'); + expect(document.activeElement).toBe(findInput(harness, 'email')); + + await type(harness, 'email', 'ada@example.com'); + await click(harness, 'Email me a link'); + const request: TestRequest = await expectRequest(backend, 'POST', `${API}/request-login-link`); + const input: RequestLoginLinkInput = { email: 'ada@example.com' }; + expect(request.request.body).toEqual(input); + HttpTestingUtilities.flushNoContent(request); + await vi.waitFor(() => expect(getText(harness, '[role="status"]')).toBe('If that email has an account, a link to log in is on its way.')); + + // whatever else zibri refuses a link for says as little as the answer for an unknown email + await click(harness, 'Email me a link'); + const refused: ErrorResponseBody = { status: 400, name: 'BadRequestError', message: 'Refused', paragraphs: ['Refused'] }; + await vi.waitFor(() => expect(getText(harness, '[role="status"]')).toBe('')); + (await expectRequest(backend, 'POST', `${API}/request-login-link`)).flush(refused, { status: 400, statusText: 'Bad Request' }); + await vi.waitFor(() => expect(getText(harness, '[role="status"]')).toBe('If that email has an account, a link to log in is on its way.')); + expect(getText(harness, '[role="alert"]')).toBe(''); + + // too many links, which zibri says + await click(harness, 'Email me a link'); + const tooMany: ErrorResponseBody = { status: 429, name: 'TooManyRequestsError', message: 'Too many', paragraphs: ['Too many attempts. Try again in a minute.'] }; + (await expectRequest(backend, 'POST', `${API}/request-login-link`)).flush(tooMany, { status: 429, statusText: 'Too Many Requests' }); + await vi.waitFor(() => expect(getText(harness, '[role="alert"]')).toBe('Too many attempts. Try again in a minute.')); + expect(getText(harness, '[role="status"]')).toBe(''); + }); + + test('logs in with the password, while the api takes links as well', async () => { + const [harness, backend] = await setup('/login', [], { password: true, loginLink: true }); + + const login: TestRequest = await submitCredentials(harness, backend); + expect(login.request.body).toEqual({ email: 'ada@example.com', password: 'secret' }); + login.flush(createJwtData()); + await answerCurrentUser(backend); + + await vi.waitFor(() => expect(TestBed.inject(Router).url).toBe('/')); + }); + + test('offers only the link when the api takes no password', async () => { + const [harness, backend] = await setup('/login', [], { password: false, loginLink: true }); + await vi.waitFor(() => expect(findInput(harness, 'password')).toBeNull()); + // no password to reset + expect(getRoot(harness).querySelector('a')).toBeNull(); + expect([...getRoot(harness).querySelectorAll('button')].map(button => button.textContent.trim())).toEqual(['Email me a link', 'Back']); + + await type(harness, 'email', 'ada@example.com'); + await click(harness, 'Email me a link'); + HttpTestingUtilities.flushNoContent(await expectRequest(backend, 'POST', `${API}/request-login-link`)); + + await vi.waitFor(() => expect(getText(harness, '[role="status"]')).toBe('If that email has an account, a link to log in is on its way.')); + }); + + test('asks for the password only, when the api takes no link or has no route for its login methods', async () => { + const [harness] = await setup('/login', [], { password: true, loginLink: false }); + expect(findInput(harness, 'password')).not.toBeNull(); + expect(getRoot(harness).textContent).not.toContain('Email me a link'); + + TestBed.resetTestingModule(); + const [withoutRoute] = await setup('/login'); + expect(findInput(withoutRoute, 'password')).not.toBeNull(); + expect(getRoot(withoutRoute).textContent).not.toContain('Email me a link'); + }); + test('links to the password reset, unless the app has none', async () => { const [harness] = await setup('/login'); const link: HTMLAnchorElement | null = getRoot(harness).querySelector('a'); diff --git a/projects/ngx-auth/login/login.component.ts b/projects/ngx-auth/login/login.component.ts index 5640554..fdeafa0 100644 --- a/projects/ngx-auth/login/login.component.ts +++ b/projects/ngx-auth/login/login.component.ts @@ -1,5 +1,5 @@ import { DOCUMENT } from '@angular/common'; -import { afterNextRender, Component, computed, DestroyRef, inject, Injector, Signal, signal, viewChild, WritableSignal } from '@angular/core'; +import { afterNextRender, Component, computed, DestroyRef, inject, Injector, input, InputSignal, linkedSignal, Signal, signal, viewChild, WritableSignal } from '@angular/core'; import { ActivatedRoute, Params, Router, RouterLink } from '@angular/router'; import { AUTH_CONFIG, AuthConfig, AuthErrorUtilities, AuthService, LoginResult, PasskeyUtilities, SecondFactor } from '@service-soft/ngx-auth/auth'; import { SECOND_FACTOR_CONFIG, SecondFactorCodeRequest, SecondFactorFormComponent, SecondFactorLabels } from '@service-soft/ngx-auth/second-factor'; @@ -7,19 +7,23 @@ import { ButtonComponent } from '@service-soft/ui/button'; import { FormComponent } from '@service-soft/ui/form'; import { InputStringComponent } from '@service-soft/ui/input-string'; import { LinkComponent } from '@service-soft/ui/link'; +import { LoginMethods } from 'zibri-contract'; import { LoginConfig, LoginLabels } from './login-config.model'; import { LOGIN_CONFIG } from './login-config.provider'; import { LoginEnrollmentComponent } from './login-enrollment.component'; import { EnrollmentStep, LoginStep, PasswordChangeStep, SecondFactorStep } from './login-step.model'; import { OtherLogin } from './other-login.model'; +import { PendingLogin } from './pending-login.model'; /** - * The login of zibri, for the route of the login: the email and password, then a second factor or a new password - * when the login waits for one, and the first second factor of a user who has none when their account needs one. Sends - * the user to the page they wanted, the returnUrl the loggedInGuard adds, or to afterLogin of provideAuth. A refused - * attempt shows what zibri answered and keeps what the user typed. Its texts come from provideLoginConfig, the two - * factor methods it asks for and enrolls from provideSecondFactorConfig. + * The login of the api, for the route of the login: the email and password, then a second factor or a new password + * when the login waits for one, and the first second factor of a user who has none when their account needs one. Offers + * to mail a link to log in with next to the password, or in its place, as `GET /login-methods` of the api answers; an + * api without that route takes passwords only. Sends the user to the page they wanted, the returnUrl the loggedInGuard + * adds, or to afterLogin of provideAuth. A refused attempt shows what the api answered and keeps what the user typed. + * Its texts come from provideLoginConfig, the two factor methods it asks for and enrolls from + * provideSecondFactorConfig. */ @Component({ selector: 'ngx-login', @@ -62,6 +66,15 @@ export class LoginComponent { // the page the user wanted before they left to log in at a provider. private providerReturnUrl: string | undefined = undefined; + // the ways the api logs in with, undefined until it answered. + private readonly loginMethods: WritableSignal = signal(undefined); + + /** + * A login that waits for a step, which the login continues with instead of asking for the email, like one that a + * login link started. Going back leads to the email. + */ + readonly pendingLogin: InputSignal = input(); + /** * How the login looks and works. */ @@ -75,12 +88,32 @@ export class LoginComponent { /** * What the login shows. */ - protected readonly step: WritableSignal = signal({ type: 'credentials' }); + protected readonly step: WritableSignal = linkedSignal(() => { + const pending: PendingLogin | undefined = this.pendingLogin(); + return pending == undefined ? { type: 'credentials' } : this.resolvePendingStep(pending.result, pending.emailCodesCount); + }); /** * The email the user typed. */ - protected readonly email: WritableSignal = signal(''); + protected readonly email: WritableSignal = linkedSignal(() => this.pendingLogin()?.email ?? ''); + + /** + * Whether the login asks for a password, which it does until the api answered otherwise. + */ + protected readonly offersPassword: Signal = computed(() => this.loginMethods()?.password ?? true); + + /** + * Whether the login offers to mail a link to log in with. + */ + protected readonly offersLoginLink: Signal = computed(() => this.loginMethods()?.loginLink === true); + + /** + * The route of the page that sends a link to reset the password, while there is a password to reset. + */ + protected readonly requestPasswordResetRoute: Signal = computed(() => { + return this.offersPassword() ? this.config.requestPasswordResetRoute : undefined; + }); /** * The password the user typed. @@ -93,7 +126,7 @@ export class LoginComponent { protected readonly newPassword: WritableSignal = signal(''); /** - * What zibri answered the last refused request with, empty while nothing was refused. + * What the api answered the last refused request with, empty while nothing was refused. */ protected readonly errorParagraphs: WritableSignal = signal([]); @@ -182,10 +215,60 @@ export class LoginComponent { constructor() { // only in the browser, which the provider sent back - afterNextRender(() => void this.completeProviderLogin()); + afterNextRender(() => { + if (this.pendingLogin() != undefined) { + // the button that started the login is gone, and the focus with it + (this.secondFactorForm() ?? this.firstInput())?.focus(); + return; + } + void this.loadLoginMethods(); + void this.completeProviderLogin(); + }); inject(DestroyRef).onDestroy(() => this.stopPasskeyAutofill()); } + /** + * Logs in with the email and the password, or mails a link while the api takes no password. + */ + protected async submitCredentials(): Promise { + await (this.offersPassword() ? this.login() : this.requestLoginLink()); + } + + /** + * Mails a link to log in with, from the button next to the password. It submits no form, which would ask for the + * password, so it checks the email alone, the way a submit does: the input shows what is wrong, and takes the focus. + */ + protected async requestLoginLinkInsteadOfPassword(): Promise { + const inputId: string | undefined = this.firstInput()?.inputId(); + const emailInput: HTMLElement | undefined = inputId == undefined ? undefined : this.document.getElementById(inputId) ?? undefined; + // fires invalid, which the input and the form react to + if (emailInput instanceof HTMLInputElement && !emailInput.checkValidity()) { + return; + } + await this.requestLoginLink(); + } + + /** + * Mails a link to log in with to the email. Says that it is on its way whatever the api answers, which is the same + * for an email without an account, unless it refused too many links. + */ + protected async requestLoginLink(): Promise { + // screen readers announce the text again for a link asked for again + this.status.set(''); + await this.run(async () => { + try { + await this.authService.requestLoginLink(this.email()); + } + catch (error) { + // any other refusal says as little as the answer for an unknown email, so it is not shown either + if (AuthErrorUtilities.isTooManyRequests(error) || AuthErrorUtilities.isNetworkError(error)) { + throw error; + } + } + this.status.set(this.labels.loginLinkSent); + }); + } + /** * Logs in with the email and the password. */ @@ -244,7 +327,7 @@ export class LoginComponent { } /** - * Has zibri send the code of a method, like by email. + * Has the api send the code of a method, like by email. * @param step - The step of the login. * @param request - The method, and whether the user asked for a new code. */ @@ -281,30 +364,47 @@ export class LoginComponent { */ protected back(): void { this.show({ type: 'credentials' }); + // a login that started elsewhere, like with a link, didn't need them so far + if (this.loginMethods() == undefined) { + void this.loadLoginMethods(); + } } private async continueWith(result: LoginResult): Promise { + if (result.type === 'loggedIn') { + // the router only navigates inside the app, so a returnUrl can't send the user to another site + const returnUrl: string | undefined = this.route.snapshot.queryParamMap.get('returnUrl') ?? this.providerReturnUrl; + await this.router.navigateByUrl(returnUrl ?? this.authConfig.routes.afterLogin); + return; + } + // only the first answer of a login asks to enroll. Of the logins this page starts, none proved the mailbox, so a + // code by email counts + this.show(this.resolvePendingStep(result, true)); + } + + private resolvePendingStep(result: PendingLogin['result'], emailCodesCount: boolean): LoginStep { switch (result.type) { - case 'loggedIn': { - // the router only navigates inside the app, so a returnUrl can't send the user to another site - const returnUrl: string | undefined = this.route.snapshot.queryParamMap.get('returnUrl') ?? this.providerReturnUrl; - await this.router.navigateByUrl(returnUrl ?? this.authConfig.routes.afterLogin); - return; - } case 'secondFactorRequired': { // no methods: the account needs a second factor, and the user has none yet - this.show(result.methods.length + return result.methods.length ? { type: 'secondFactor', ticket: result.ticket, methods: result.methods, enrolled: false } - : { type: 'enrollment', ticket: result.ticket }); - return; + : { type: 'enrollment', ticket: result.ticket, emailCodesCount }; } case 'passwordChangeRequired': { - this.show({ type: 'passwordChange', ticket: result.ticket }); - return; + return { type: 'passwordChange', ticket: result.ticket }; } } } + private async loadLoginMethods(): Promise { + try { + this.loginMethods.set(await this.authService.resolveLoginMethods()); + } + catch { + // the password stays, as until the api answered. An api that is down refuses the login itself, which says so + } + } + // asks for a passkey of the autofill while the email shows, if the browser offers them there. It waits until the // user picks one, which logs in, or until it is stopped. private startPasskeyAutofill(): void { diff --git a/projects/ngx-auth/login/login.stories.ts b/projects/ngx-auth/login/login.stories.ts index c39d294..50d9bc1 100644 --- a/projects/ngx-auth/login/login.stories.ts +++ b/projects/ngx-auth/login/login.stories.ts @@ -1,10 +1,12 @@ import { provideHttpClient, withInterceptors } from '@angular/common/http'; -import { afterNextRender, Component, ElementRef, EnvironmentProviders, inject, Provider, Service } from '@angular/core'; +import { afterNextRender, Component, DestroyRef, ElementRef, inject, Provider, Service } from '@angular/core'; import { provideRouter } from '@angular/router'; import { authInterceptor, AuthService, provideAuth } from '@service-soft/ngx-auth/auth'; import { applicationConfig, Meta, StoryObj } from '@storybook/angular'; import { FormTestingUtilities } from 'testing/form'; import { FakeAnswer, HttpTestingUtilities } from 'testing/http'; +import { AddedPasskeyDevice, PasskeyTestingUtilities } from 'testing/passkey'; +import { LoginMethods } from 'zibri-contract'; import { provideLoginConfig } from './login-config.provider'; import { LoginComponent } from './login.component'; @@ -13,15 +15,8 @@ import { LoginComponent } from './login.component'; class StoryAuthService extends AuthService {} // zibri, as far as the login of a story gets: it refuses the password with the answer of the story. -function answerLoginWith(login: FakeAnswer): (Provider | EnvironmentProviders)[] { - return [ - provideRouter([]), - provideHttpClient(withInterceptors([ - authInterceptor, - HttpTestingUtilities.answerWith({ 'POST /api/auth/login': login, 'POST /api/auth/login/2fa/request': { status: 204 } }) - ])), - provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }) - ]; +function answerLoginWith(login: FakeAnswer): Provider { + return HttpTestingUtilities.provideAnswers({ 'POST /api/auth/login': login, 'POST /api/auth/login/2fa/request': { status: 204 } }); } // what zibri answers a refused request with. @@ -29,6 +24,51 @@ function refuse(name: string, body: object = {}): FakeAnswer { return { status: 401, body: { status: 401, name, message: name, paragraphs: [name], ...body } }; } +// zibri with links to log in with, next to the password or in place of it, as the login methods of the story say. +function answerWithLoginMethods(loginMethods: LoginMethods): Provider { + return HttpTestingUtilities.provideAnswers({ + 'GET /api/auth/login-methods': { status: 200, body: loginMethods }, + 'POST /api/auth/request-login-link': { status: 204 } + }); +} + +// asks for a link once the login offers one, like a user would, so the story shows what the login says then. +@Component({ + selector: 'ngx-login-link-request', + template: '', + imports: [LoginComponent] +}) +class LoginLinkRequestComponent { + constructor() { + const root: HTMLElement = inject>(ElementRef).nativeElement; + // the button only shows once the api answered its login methods + const observer: MutationObserver = new MutationObserver(() => { + if ([...root.querySelectorAll('button')].some(button => button.textContent.trim() === 'Email me a link')) { + observer.disconnect(); + FormTestingUtilities.type(root, 'email', 'ada@example.com'); + FormTestingUtilities.click(root, 'Email me a link'); + } + }); + observer.observe(root, { childList: true, subtree: true }); + inject(DestroyRef).onDestroy(() => observer.disconnect()); + } +} + +// the login on a device with passkeys, which the autofill of the email waits for. A browser without one, like the +// headless one of the AXE checks, refuses that request, which the login would show as a failure. +@Component({ + selector: 'ngx-login-with-passkey-device', + template: '', + imports: [LoginComponent] +}) +class LoginWithPasskeyDeviceComponent { + constructor() { + // before the login renders, which starts the autofill + const device: AddedPasskeyDevice = PasskeyTestingUtilities.addDevice({ autofill: true }); + inject(DestroyRef).onDestroy(() => device.remove()); + } +} + // logs in once the login shows, like a user would, so the story shows the step the login leads to. @Component({ selector: 'ngx-login-attempt', @@ -49,7 +89,16 @@ class LoginAttemptComponent { const meta: Meta = { title: 'Auth/Login', component: LoginComponent, - decorators: [applicationConfig({ providers: answerLoginWith({ status: 204 }) })], + decorators: [ + applicationConfig({ + providers: [ + provideRouter([]), + provideHttpClient(withInterceptors([authInterceptor])), + provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }), + answerLoginWith({ status: 204 }) + ] + }) + ], render: () => ({ template: '', moduleMetadata: { imports: [LoginAttemptComponent] } }) }; export default meta; @@ -64,7 +113,7 @@ export const Default: Story = { }; export const WithPasskey: Story = { - render: renderLogin, + render: () => ({ template: '', moduleMetadata: { imports: [LoginWithPasskeyDeviceComponent] } }), decorators: [ applicationConfig({ providers: [ @@ -74,16 +123,33 @@ export const WithPasskey: Story = { { authenticator: 'google', label: 'Log in with Google' }, { authenticator: 'github', label: 'Log in with GitHub' } ] - }) + }), + // the challenge the autofill of the email waits with for a passkey of the device + HttpTestingUtilities.provideAnswers({ 'POST /api/auth/login-options': { status: 200, body: { challenge: 'challenge-1' } } }) ] }) ] }; +export const WithLoginLink: Story = { + render: renderLogin, + decorators: [applicationConfig({ providers: [answerWithLoginMethods({ password: true, loginLink: true })] })] +}; + +export const LoginLinkOnly: Story = { + render: renderLogin, + decorators: [applicationConfig({ providers: [answerWithLoginMethods({ password: false, loginLink: true })] })] +}; + +export const LoginLinkSent: Story = { + render: () => ({ template: '', moduleMetadata: { imports: [LoginLinkRequestComponent] } }), + decorators: [applicationConfig({ providers: [answerWithLoginMethods({ password: false, loginLink: true })] })] +}; + export const PasskeyAsSecondFactor: Story = { decorators: [ applicationConfig({ - providers: answerLoginWith(refuse('SecondFactorRequiredError', { ticket: 'ticket-1', methods: ['passkey', 'otp'] })) + providers: [answerLoginWith(refuse('SecondFactorRequiredError', { ticket: 'ticket-1', methods: ['passkey', 'otp'] }))] }) ] }; @@ -91,7 +157,7 @@ export const PasskeyAsSecondFactor: Story = { export const Refused: Story = { decorators: [ applicationConfig({ - providers: answerLoginWith(refuse('UnauthorizedError', { paragraphs: ['Wrong email or password.'] })) + providers: [answerLoginWith(refuse('UnauthorizedError', { paragraphs: ['Wrong email or password.'] }))] }) ] }; @@ -99,9 +165,7 @@ export const Refused: Story = { export const SecondFactor: Story = { decorators: [ applicationConfig({ - providers: answerLoginWith( - refuse('SecondFactorRequiredError', { ticket: 'ticket-1', methods: ['email', 'otp', 'recovery-code'] }) - ) + providers: [answerLoginWith(refuse('SecondFactorRequiredError', { ticket: 'ticket-1', methods: ['email', 'otp', 'recovery-code'] }))] }) ] }; @@ -109,7 +173,7 @@ export const SecondFactor: Story = { export const NoUsableSecondFactor: Story = { decorators: [ applicationConfig({ - providers: answerLoginWith(refuse('SecondFactorRequiredError', { ticket: 'ticket-1', methods: ['hardware-token'] })) + providers: [answerLoginWith(refuse('SecondFactorRequiredError', { ticket: 'ticket-1', methods: ['hardware-token'] }))] }) ] }; @@ -117,13 +181,13 @@ export const NoUsableSecondFactor: Story = { export const Enrollment: Story = { decorators: [ applicationConfig({ - providers: answerLoginWith(refuse('SecondFactorRequiredError', { ticket: 'ticket-1', methods: [] })) + providers: [answerLoginWith(refuse('SecondFactorRequiredError', { ticket: 'ticket-1', methods: [] }))] }) ] }; export const PasswordChange: Story = { - decorators: [applicationConfig({ providers: answerLoginWith(refuse('PasswordChangeRequiredError', { ticket: 'ticket-1' })) })] + decorators: [applicationConfig({ providers: [answerLoginWith(refuse('PasswordChangeRequiredError', { ticket: 'ticket-1' }))] })] }; // a jwt login bound to the key of the browser, which every request proves. The login succeeds, the key stays in // IndexedDB for the next visit. @@ -131,26 +195,22 @@ export const WithDpop: Story = { decorators: [ applicationConfig({ providers: [ - provideRouter([]), - provideHttpClient(withInterceptors([ - authInterceptor, - HttpTestingUtilities.answerWith({ - 'POST /api/auth/login': { - status: 200, - body: { - userId: 'user-1', - roles: [], - accessToken: { value: 'access-1', expirationDate: '2099-01-01T00:00:00.000Z' }, - refreshToken: { value: 'refresh-1', expirationDate: '2099-01-01T00:00:00.000Z' } - } - }, - 'GET /api/auth/me': { - status: 200, - body: { id: 'user-1', email: 'ada@example.com', memberships: [], platformPermissions: [] } + provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'jwt', dpop: true }), + HttpTestingUtilities.provideAnswers({ + 'POST /api/auth/login': { + status: 200, + body: { + userId: 'user-1', + roles: [], + accessToken: { value: 'access-1', expirationDate: '2099-01-01T00:00:00.000Z' }, + refreshToken: { value: 'refresh-1', expirationDate: '2099-01-01T00:00:00.000Z' } } - }) - ])), - provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'jwt', dpop: true }) + }, + 'GET /api/auth/me': { + status: 200, + body: { id: 'user-1', email: 'ada@example.com', memberships: [], platformPermissions: [] } + } + }) ] }) ] diff --git a/projects/ngx-auth/login/other-login.model.ts b/projects/ngx-auth/login/other-login.model.ts index 71a185f..f84afaa 100644 --- a/projects/ngx-auth/login/other-login.model.ts +++ b/projects/ngx-auth/login/other-login.model.ts @@ -7,7 +7,7 @@ export type OtherLogin = { */ kind: 'passkey' | 'provider', /** - * The name of its authenticator in zibri. + * The name of its authenticator in the api. */ authenticator: string, /** diff --git a/projects/ngx-auth/login/pending-login.model.ts b/projects/ngx-auth/login/pending-login.model.ts new file mode 100644 index 0000000..69bb629 --- /dev/null +++ b/projects/ngx-auth/login/pending-login.model.ts @@ -0,0 +1,26 @@ +import { LoginResult } from '@service-soft/ngx-auth/auth'; + +/** + * What a login waits for: a second factor, or a new password. + */ +type PendingLoginResult = Exclude; + +/** + * A login that waits for a step, which the LoginComponent continues with instead of asking for the email, like one + * that a login link or an invitation without a password started. + */ +export type PendingLogin = { + /** + * What the login waits for. + */ + result: PendingLoginResult, + /** + * The email of the account, when it is known, which a passkey enrolled as the first second factor is listed under. + */ + email?: string, + /** + * Whether a code by email counts as the second factor of the login: not for one by a link, which proved the mailbox + * already. Without, codes by email aren't offered as the first second factor. + */ + emailCodesCount: boolean +}; \ No newline at end of file diff --git a/projects/ngx-auth/login/public-api.ts b/projects/ngx-auth/login/public-api.ts index 24a12c7..dd02ce0 100644 --- a/projects/ngx-auth/login/public-api.ts +++ b/projects/ngx-auth/login/public-api.ts @@ -2,4 +2,5 @@ export * from './login-config-changes.model'; export * from './login-config.model'; export * from './login-config.provider'; export * from './login-provider.model'; -export * from './login.component'; \ No newline at end of file +export * from './login.component'; +export * from './pending-login.model'; \ No newline at end of file diff --git a/projects/ngx-auth/ng-package.json b/projects/ngx-auth/ng-package.json index 7b67fd4..9949d1d 100644 --- a/projects/ngx-auth/ng-package.json +++ b/projects/ngx-auth/ng-package.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/ng-packagr/ng-package.schema.json", - "assets": ["tailwind.css"], + "assets": ["tailwind.css", "locale/messages.de.xlf", "CHANGELOG.md"], "dest": "../../dist/ngx-auth", "lib": { "entryFile": "src/public-api.ts" diff --git a/projects/ngx-auth/package.json b/projects/ngx-auth/package.json index 939b5cc..125c4cf 100644 --- a/projects/ngx-auth/package.json +++ b/projects/ngx-auth/package.json @@ -1,6 +1,6 @@ { "name": "@service-soft/ngx-auth", - "version": "22.3.2", + "version": "22.4.0", "license": "MIT", "repository": { "type": "git", @@ -19,17 +19,21 @@ } }, "peerDependencies": { + "@angular/aria": "^22.2.0", "@angular/common": "^22.2.0", "@angular/core": "^22.2.0", "@angular/localize": "^22.2.0", "@angular/router": "^22.2.0", "@fortawesome/free-solid-svg-icons": "^7.3.1", - "@service-soft/ui": "^22.3.2", + "@service-soft/ui": "^22.4.0", "tailwindcss": "^4.3.3", "uqr": "^0.1.3", - "zibri-contract": "^3.2.0" + "zibri-contract": "^3.3.0" }, "peerDependenciesMeta": { + "@angular/aria": { + "optional": true + }, "@angular/localize": { "optional": true }, @@ -46,5 +50,8 @@ "optional": true } }, - "sideEffects": false + "sideEffects": false, + "translations": { + "de": "./locale/messages.de.xlf" + } } \ No newline at end of file diff --git a/projects/ngx-auth/provider-error/provider-error-config.model.ts b/projects/ngx-auth/provider-error/provider-error-config.model.ts index 458abe6..2b9565d 100644 --- a/projects/ngx-auth/provider-error/provider-error-config.model.ts +++ b/projects/ngx-auth/provider-error/provider-error-config.model.ts @@ -7,7 +7,7 @@ export type ProviderErrorLabels = { */ title: string, /** - * What went wrong, by the `error` of zibri, like 'cancelled'. An error without a text shows the one of 'failed'. + * What went wrong, by the `error` of the api, like 'cancelled'. An error without a text shows the one of 'failed'. */ errors: Partial> & Record<'failed', string>, /** diff --git a/projects/ngx-auth/provider-error/provider-error.component.ts b/projects/ngx-auth/provider-error/provider-error.component.ts index cfaf13c..976d036 100644 --- a/projects/ngx-auth/provider-error/provider-error.component.ts +++ b/projects/ngx-auth/provider-error/provider-error.component.ts @@ -21,9 +21,9 @@ type BackLink = { }; /** - * The page a login at a provider lands on when it failed, for the errorUrl of zibri: it says what went wrong by the - * `error` zibri adds, and leads back to the login, or into the app for a logged in user whose provider couldn't be - * connected. Its texts come from provideProviderErrorConfig. + * The page a login at a provider lands on when it failed, for the url the api sends it to then, like the errorUrl of + * zibri: it says what went wrong by the `error` the api adds, and leads back to the login, or into the app for a logged + * in user whose provider couldn't be connected. Its texts come from provideProviderErrorConfig. */ @Component({ selector: 'ngx-provider-error', diff --git a/projects/ngx-auth/request-password-reset/request-password-reset-config.model.ts b/projects/ngx-auth/request-password-reset/request-password-reset-config.model.ts index 7b910b1..efbc6bf 100644 --- a/projects/ngx-auth/request-password-reset/request-password-reset-config.model.ts +++ b/projects/ngx-auth/request-password-reset/request-password-reset-config.model.ts @@ -19,8 +19,8 @@ export type RequestPasswordResetLabels = { */ send: string, /** - * Shown once zibri took the email. It answers the same whether the email has an account or not, so nobody can find - * out which emails have one. + * Shown once the api took the email. It answers the same whether the email has an account or not, so nobody can + * find out which emails have one. */ sent: string, /** @@ -28,7 +28,7 @@ export type RequestPasswordResetLabels = { */ backToLogin: string, /** - * Shown when the request failed without a message of zibri, like without a connection. + * Shown when the request failed without a message of the api, like without a connection. */ failed: string }; diff --git a/projects/ngx-auth/request-password-reset/request-password-reset.component.ts b/projects/ngx-auth/request-password-reset/request-password-reset.component.ts index 5e88153..817efc3 100644 --- a/projects/ngx-auth/request-password-reset/request-password-reset.component.ts +++ b/projects/ngx-auth/request-password-reset/request-password-reset.component.ts @@ -10,8 +10,8 @@ import { RequestPasswordResetLabels } from './request-password-reset-config.mode import { REQUEST_PASSWORD_RESET_CONFIG } from './request-password-reset-config.provider'; /** - * The page that has zibri mail a link to reset the password, for the requestPasswordResetRoute of the login. The link - * opens the ConfirmPasswordResetComponent. Its texts come from provideRequestPasswordResetConfig. + * The page that has the api mail a link to reset the password, for the requestPasswordResetRoute of the login. The + * link opens the ConfirmPasswordResetComponent. Its texts come from provideRequestPasswordResetConfig. */ @Component({ selector: 'ngx-request-password-reset', @@ -43,7 +43,7 @@ export class RequestPasswordResetComponent { protected readonly email: WritableSignal = signal(''); /** - * What zibri answered a refused request with, empty while nothing was refused. + * What the api answered a refused request with, empty while nothing was refused. */ protected readonly errorParagraphs: WritableSignal = signal([]); @@ -53,7 +53,7 @@ export class RequestPasswordResetComponent { protected readonly status: WritableSignal = signal(''); /** - * Has zibri mail the link. + * Has the api mail the link. */ protected async send(): Promise { if (this.sending) { diff --git a/projects/ngx-auth/request-password-reset/request-password-reset.stories.ts b/projects/ngx-auth/request-password-reset/request-password-reset.stories.ts index 9d19a67..9ba8fd8 100644 --- a/projects/ngx-auth/request-password-reset/request-password-reset.stories.ts +++ b/projects/ngx-auth/request-password-reset/request-password-reset.stories.ts @@ -34,11 +34,9 @@ const meta: Meta = { applicationConfig({ providers: [ provideRouter([]), - provideHttpClient(withInterceptors([ - authInterceptor, - HttpTestingUtilities.answerWith({ 'POST /api/auth/request-password-reset': { status: 204 } }) - ])), - provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }) + provideHttpClient(withInterceptors([authInterceptor])), + provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }), + HttpTestingUtilities.provideAnswers({ 'POST /api/auth/request-password-reset': { status: 204 } }) ] }) ] diff --git a/projects/ngx-auth/second-factor/second-factor-config.model.ts b/projects/ngx-auth/second-factor/second-factor-config.model.ts index 8ba5473..58dbb1c 100644 --- a/projects/ngx-auth/second-factor/second-factor-config.model.ts +++ b/projects/ngx-auth/second-factor/second-factor-config.model.ts @@ -27,7 +27,7 @@ export type SecondFactorMethodOptions = { */ confirmation: 'code' | 'passkey', /** - * Whether zibri sends the code first, like by email or text message. It is sent when the user picks the method, + * Whether the api sends the code first, like by email or text message. It is sent when the user picks the method, * and the user can have a new one sent. */ sendsCode: boolean, diff --git a/projects/ngx-auth/second-factor/second-factor-form.component.ts b/projects/ngx-auth/second-factor/second-factor-form.component.ts index 13e23d8..8444d98 100644 --- a/projects/ngx-auth/second-factor/second-factor-form.component.ts +++ b/projects/ngx-auth/second-factor/second-factor-form.component.ts @@ -56,8 +56,8 @@ export class SecondFactorFormComponent { protected readonly labels: SecondFactorLabels = this.config.labels; /** - * The two factor methods the user enrolled, like the methods zibri answered with. The first one the form can ask for - * shows first. + * The two factor methods the user enrolled, like the methods the api answered with. The first one the form can ask + * for shows first. */ readonly methods: InputSignal = input.required(); @@ -127,7 +127,7 @@ export class SecondFactorFormComponent { }); /** - * Whether zibri sends the code of the current method, which the user can have sent again. + * Whether the api sends the code of the current method, which the user can have sent again. */ protected readonly sendsCode: Signal = computed(() => { const method: string | undefined = this.method(); @@ -162,7 +162,7 @@ export class SecondFactorFormComponent { } /** - * Switches to another method, and asks for its code when zibri sends it. + * Switches to another method, and asks for its code when the api sends it. * @param method - The name of the method. */ protected choose(method: string): void { diff --git a/projects/ngx-auth/service-accounts/ng-package.json b/projects/ngx-auth/service-accounts/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-auth/service-accounts/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-auth/service-accounts/public-api.ts b/projects/ngx-auth/service-accounts/public-api.ts new file mode 100644 index 0000000..1baf198 --- /dev/null +++ b/projects/ngx-auth/service-accounts/public-api.ts @@ -0,0 +1,6 @@ +export * from './service-accounts-labels.model'; +export * from './service-accounts-config.model'; +export * from './service-accounts-config-changes.model'; +export * from './service-accounts-config.provider'; +export * from './service-accounts.service'; +export * from './service-accounts.component'; diff --git a/projects/ngx-auth/service-accounts/service-accounts-config-changes.model.ts b/projects/ngx-auth/service-accounts/service-accounts-config-changes.model.ts new file mode 100644 index 0000000..e76afce --- /dev/null +++ b/projects/ngx-auth/service-accounts/service-accounts-config-changes.model.ts @@ -0,0 +1,21 @@ +import { ServiceAccountsConfig } from './service-accounts-config.model'; +import { ServiceAccountsLabels } from './service-accounts-labels.model'; + +/** + * The values to change in the config of the service accounts. Everything is optional, including every single label, + * but the requests need the url once. + */ +export type ServiceAccountsConfigChanges = Partial> & { + /** + * The url of the routes of the service accounts of your api, like 'https://api.example.com/service-accounts'. + */ + baseUrl?: string, + /** + * The url of the route of the MCP tools of a service account, like 'https://api.example.com/service-account-tools'. + */ + mcpToolsBaseUrl?: string, + /** + * The labels to change. + */ + labels?: Partial +}; diff --git a/projects/ngx-auth/service-accounts/service-accounts-config.model.ts b/projects/ngx-auth/service-accounts/service-accounts-config.model.ts new file mode 100644 index 0000000..a53cd71 --- /dev/null +++ b/projects/ngx-auth/service-accounts/service-accounts-config.model.ts @@ -0,0 +1,53 @@ +import { HeadingLevel } from '@service-soft/ui/heading'; +import { InputOption } from '@service-soft/ui/input'; + +import { ServiceAccountsLabels } from './service-accounts-labels.model'; + +/** + * Where the service accounts are, what can be chosen for them, and what their view shows. + */ +export type ServiceAccountsConfig = { + /** + * The url of the routes of the service accounts of your api, like 'https://api.example.com/service-accounts'. + * Undefined until provideServiceAccountsConfig sets it, which every request needs. + */ + baseUrl: string | undefined, + /** + * The url of the route of the MCP tools of a service account, like 'https://api.example.com/service-account-tools', + * which the id of the account is added to. The view shows the tools of each account only with it. Undefined by + * default. + */ + mcpToolsBaseUrl: string | undefined, + /** + * The platform roles a service account can be given, by their name as the value. None by default. + */ + roles: InputOption[], + /** + * The tenant roles a service account can be given in the tenant the user acts in, by their name as the value. None + * by default. + */ + tenantRoles: InputOption[], + /** + * The permissions an API key can list, of either level, by their name as the value. None by default. + */ + permissions: InputOption[], + /** + * Whether the user may create service accounts, change their roles, create and revoke their keys and delete them, + * like with `service-accounts.manage`, which the view shows its forms by while its `canManage` isn't set. False by + * default. + */ + canManage: boolean, + /** + * How moments show, like when a key expires, as the options of Intl.DateTimeFormat in the LOCALE_ID of the app. A + * medium date and a short time by default. + */ + dateTimeFormat: Intl.DateTimeFormatOptions, + /** + * The level of the heading of the view. Its sections are headed one level below. 2 by default. + */ + headingLevel: HeadingLevel, + /** + * The texts. + */ + labels: ServiceAccountsLabels +}; diff --git a/projects/ngx-auth/service-accounts/service-accounts-config.provider.ts b/projects/ngx-auth/service-accounts/service-accounts-config.provider.ts new file mode 100644 index 0000000..2ddb2a0 --- /dev/null +++ b/projects/ngx-auth/service-accounts/service-accounts-config.provider.ts @@ -0,0 +1,128 @@ +import { inject, InjectionToken, Provider } from '@angular/core'; + +import { ServiceAccountsConfigChanges } from './service-accounts-config-changes.model'; +import { ServiceAccountsConfig } from './service-accounts-config.model'; +import { ServiceAccountsLabels } from './service-accounts-labels.model'; + +/** + * The texts of the service accounts when nothing changes them, as $localize, which an app translates like its own. + * @returns The default labels. + */ +function getDefaultServiceAccountsLabels(): ServiceAccountsLabels { + return { + title: $localize`:@@ngx-auth.service-accounts.title:Service accounts`, + description: $localize`:@@ngx-auth.service-accounts.description:Accounts of AI assistants and integrations. They never log in, and call the api with their API keys.`, + loading: $localize`:@@ngx-auth.service-accounts.loading:Loading`, + loadingFailed: $localize`:@@ngx-auth.service-accounts.loadingFailed:The service accounts couldn't be loaded.`, + failed: $localize`:@@ngx-auth.service-accounts.failed:Something went wrong. Please try again.`, + noServiceAccounts: $localize`:@@ngx-auth.service-accounts.noServiceAccounts:There are no service accounts yet.`, + create: $localize`:@@ngx-auth.service-accounts.create:Create a service account`, + name: $localize`:@@ngx-auth.service-accounts.name:Name`, + nameHint: $localize`:@@ngx-auth.service-accounts.nameHint:What it is for, like assistant: lowercase letters, digits and hyphens between them`, + roles: $localize`:@@ngx-auth.service-accounts.roles:Roles`, + rolesHint: $localize`:@@ngx-auth.service-accounts.rolesHint:Its own roles, which apply in every tenant`, + tenantRoles: $localize`:@@ngx-auth.service-accounts.tenantRoles:Roles in this tenant`, + tenantRolesHint: $localize`:@@ngx-auth.service-accounts.tenantRolesHint:What it may do in the tenant you act in`, + none: $localize`:@@ngx-auth.service-accounts.none:None`, + save: $localize`:@@ngx-auth.service-accounts.save:Save`, + cancel: $localize`:@@ngx-auth.service-accounts.cancel:Cancel`, + created: name => $localize`:@@ngx-auth.service-accounts.created:The service account ${name}:name: was created.`, + changeRoles: $localize`:@@ngx-auth.service-accounts.changeRoles:Change the roles`, + rolesSaved: name => $localize`:@@ngx-auth.service-accounts.rolesSaved:The roles of ${name}:name: were saved.`, + delete: $localize`:@@ngx-auth.service-accounts.delete:Delete`, + deleteQuestion: name => $localize`:@@ngx-auth.service-accounts.deleteQuestion:Delete the service account ${name}:name:?`, + deleteWarning: $localize`:@@ngx-auth.service-accounts.deleteWarning:Its API keys are revoked, and everything that sends one of them is refused. What it proposed, like approval requests, stays for a person to decide.`, + deleted: name => $localize`:@@ngx-auth.service-accounts.deleted:The service account ${name}:name: was deleted.`, + apiKeys: $localize`:@@ngx-auth.service-accounts.apiKeys:API keys`, + noApiKeys: $localize`:@@ngx-auth.service-accounts.noApiKeys:It has no API key yet.`, + addApiKey: $localize`:@@ngx-auth.service-accounts.addApiKey:Add an API key`, + apiKeyName: $localize`:@@ngx-auth.service-accounts.apiKeyName:Name of the key`, + apiKeyNameHint: $localize`:@@ngx-auth.service-accounts.apiKeyNameHint:What sends it, like the assistant of the team`, + permissions: $localize`:@@ngx-auth.service-accounts.permissions:Permissions`, + permissionsHint: $localize`:@@ngx-auth.service-accounts.permissionsHint:What the key may do, as far as the roles of the account allow it`, + expiresAt: $localize`:@@ngx-auth.service-accounts.expiresAt:Expires`, + expiresAtHint: $localize`:@@ngx-auth.service-accounts.expiresAtHint:The key stops working at the end of the day. Leave it empty for a key that works until it is revoked.`, + neverExpires: $localize`:@@ngx-auth.service-accounts.neverExpires:Never`, + bindToTenant: $localize`:@@ngx-auth.service-accounts.bindToTenant:Only in the tenant you act in`, + bindToTenantHint: $localize`:@@ngx-auth.service-accounts.bindToTenantHint:Otherwise the key acts in every tenant the account is a member of`, + requireDpop: $localize`:@@ngx-auth.service-accounts.requireDpop:Only for tokens bound to a key of the client (DPoP)`, + requireDpopHint: $localize`:@@ngx-auth.service-accounts.requireDpopHint:Such a key is only exchanged for tokens, and never taken in a header. Leave it off for an MCP client, which sends the key itself.`, + actsIn: $localize`:@@ngx-auth.service-accounts.actsIn:Acts in`, + thisTenant: $localize`:@@ngx-auth.service-accounts.thisTenant:This tenant only`, + otherTenant: $localize`:@@ngx-auth.service-accounts.otherTenant:Another tenant only`, + everyTenant: $localize`:@@ngx-auth.service-accounts.everyTenant:Every tenant of the account`, + lastUsedAt: $localize`:@@ngx-auth.service-accounts.lastUsedAt:Last used`, + neverUsed: $localize`:@@ngx-auth.service-accounts.neverUsed:Never`, + createdAt: $localize`:@@ngx-auth.service-accounts.createdAt:Created`, + apiKeyCreated: name => $localize`:@@ngx-auth.service-accounts.apiKeyCreated:The API key ${name}:name: was created.`, + secretTitle: name => $localize`:@@ngx-auth.service-accounts.secretTitle:The API key ${name}:name:`, + secretWarning: $localize`:@@ngx-auth.service-accounts.secretWarning:Copy the key now and keep it where its client reads it. You won't see it again: only a hash of it is stored.`, + copy: $localize`:@@ngx-auth.service-accounts.copy:Copy the key`, + copied: $localize`:@@ngx-auth.service-accounts.copied:The key was copied.`, + copyFailed: $localize`:@@ngx-auth.service-accounts.copyFailed:The key couldn't be copied. Select it and copy it yourself.`, + done: $localize`:@@ngx-auth.service-accounts.done:Done`, + revoke: $localize`:@@ngx-auth.service-accounts.revoke:Revoke`, + revokeQuestion: name => $localize`:@@ngx-auth.service-accounts.revokeQuestion:Revoke the API key ${name}:name:?`, + revokeWarning: $localize`:@@ngx-auth.service-accounts.revokeWarning:Everything that sends the key is refused from then on. Its client needs a new key to call again.`, + revoked: name => $localize`:@@ngx-auth.service-accounts.revoked:The API key ${name}:name: was revoked.`, + mcpTools: $localize`:@@ngx-auth.service-accounts.mcpTools:MCP tools it can use`, + mcpToolsDescription: $localize`:@@ngx-auth.service-accounts.mcpToolsDescription:By its roles in the tenant you act in. A key that lists fewer permissions opens fewer of them.`, + noMcpTools: $localize`:@@ngx-auth.service-accounts.noMcpTools:Its roles open none of the tools.`, + mcpToolsLoadingFailed: $localize`:@@ngx-auth.service-accounts.mcpToolsLoadingFailed:The tools couldn't be loaded.`, + readTool: $localize`:@@ngx-auth.service-accounts.readTool:Reads`, + writeTool: $localize`:@@ngx-auth.service-accounts.writeTool:Proposes changes, which a person approves` + }; +} + +/** + * The values of the service accounts when nothing changes them. Their texts are $localize, which an app translates + * like its own, and resolved once the config is injected, so translations an app loads at runtime apply as well. + * @returns The default config. + */ +function getDefaultServiceAccountsConfig(): ServiceAccountsConfig { + return { + baseUrl: undefined, + mcpToolsBaseUrl: undefined, + roles: [], + tenantRoles: [], + permissions: [], + canManage: false, + dateTimeFormat: { dateStyle: 'medium', timeStyle: 'short' }, + headingLevel: 2, + labels: getDefaultServiceAccountsLabels() + }; +} + +/** + * Where the service accounts are, what can be chosen for them and what their view shows, below this injector. Change + * it with provideServiceAccountsConfig. + */ +export const SERVICE_ACCOUNTS_CONFIG: InjectionToken = new InjectionToken( + 'SERVICE_ACCOUNTS_CONFIG', + { providedIn: 'root', factory: () => getDefaultServiceAccountsConfig() } +); + +/** + * Sets where the service accounts are, `{ baseUrl }`, and the route of their MCP tools, and changes what can be chosen + * for them and what their view shows, like the roles, the permissions of a key or the labels to translate them. + * Provide it in the application config for the whole app, or in a component or route for only that part of it. Values + * you leave out are taken from the parent injector, including single labels. + * @param config - The values to change. + * @returns The provider for SERVICE_ACCOUNTS_CONFIG. + */ +export function provideServiceAccountsConfig(config: ServiceAccountsConfigChanges): Provider { + return { + provide: SERVICE_ACCOUNTS_CONFIG, + useFactory: (): ServiceAccountsConfig => { + const parent: ServiceAccountsConfig = inject(SERVICE_ACCOUNTS_CONFIG, { skipSelf: true, optional: true }) + ?? getDefaultServiceAccountsConfig(); + return { + ...parent, + ...config, + baseUrl: config.baseUrl ?? parent.baseUrl, + mcpToolsBaseUrl: config.mcpToolsBaseUrl ?? parent.mcpToolsBaseUrl, + labels: { ...parent.labels, ...config.labels } + }; + } + }; +} diff --git a/projects/ngx-auth/service-accounts/service-accounts-labels.model.ts b/projects/ngx-auth/service-accounts/service-accounts-labels.model.ts new file mode 100644 index 0000000..61ef553 --- /dev/null +++ b/projects/ngx-auth/service-accounts/service-accounts-labels.model.ts @@ -0,0 +1,249 @@ +/** + * The texts of the service accounts. + */ +export type ServiceAccountsLabels = { + /** + * The heading. + */ + title: string, + /** + * Says what a service account is, below the heading. + */ + description: string, + /** + * Read by screen readers while the service accounts load. + */ + loading: string, + /** + * Shown when the service accounts couldn't be loaded. + */ + loadingFailed: string, + /** + * Shown when a request failed without a message of the api, like without a connection. + */ + failed: string, + /** + * Shown while there is no service account. + */ + noServiceAccounts: string, + /** + * The button that opens the form creating a service account, and the heading of that form. + */ + create: string, + /** + * The name of a service account. + */ + name: string, + /** + * What the name is made of. + */ + nameHint: string, + /** + * The platform roles of a service account. + */ + roles: string, + /** + * What the platform roles are. + */ + rolesHint: string, + /** + * The roles of a service account in the tenant the user acts in. + */ + tenantRoles: string, + /** + * What the roles in the tenant are. + */ + tenantRolesHint: string, + /** + * Shown for a service account without roles, and a key without permissions. + */ + none: string, + /** + * The button that saves a form. + */ + save: string, + /** + * The button that closes a form or a question without changing anything. + */ + cancel: string, + /** + * Announced once a service account was created, from its name. + */ + created: (name: string) => string, + /** + * The button that opens the form changing the roles of a service account. + */ + changeRoles: string, + /** + * Announced once the roles of a service account were saved, from its name. + */ + rolesSaved: (name: string) => string, + /** + * The button that deletes a service account. + */ + delete: string, + /** + * The question before a service account is deleted, from its name. + */ + deleteQuestion: (name: string) => string, + /** + * Says what deleting a service account does. + */ + deleteWarning: string, + /** + * Announced once a service account was deleted, from its name. + */ + deleted: (name: string) => string, + /** + * The heading of the API keys of a service account. + */ + apiKeys: string, + /** + * Shown for a service account without API keys. + */ + noApiKeys: string, + /** + * The button that opens the form adding an API key, and the heading of that form. + */ + addApiKey: string, + /** + * The name of an API key. + */ + apiKeyName: string, + /** + * What the name of an API key is for. + */ + apiKeyNameHint: string, + /** + * The permissions of an API key. + */ + permissions: string, + /** + * What the permissions of a key are. + */ + permissionsHint: string, + /** + * When an API key stops working. + */ + expiresAt: string, + /** + * What the expiry of a new key means. + */ + expiresAtHint: string, + /** + * Shown for a key that works until it is revoked. + */ + neverExpires: string, + /** + * Whether a new key acts only in the tenant the user acts in. + */ + bindToTenant: string, + /** + * What binding a new key to the tenant means. + */ + bindToTenantHint: string, + /** + * Whether a new key is only exchanged for tokens bound to a DPoP key. + */ + requireDpop: string, + /** + * What requiring DPoP means. + */ + requireDpopHint: string, + /** + * Where an API key acts. + */ + actsIn: string, + /** + * Shown for a key bound to the tenant the user acts in. + */ + thisTenant: string, + /** + * Shown for a key bound to another tenant. + */ + otherTenant: string, + /** + * Shown for a key that acts in every tenant of its service account. + */ + everyTenant: string, + /** + * When an API key was last used. + */ + lastUsedAt: string, + /** + * Shown for a key never used. + */ + neverUsed: string, + /** + * When an API key was created. + */ + createdAt: string, + /** + * Announced once an API key was created, from its name. + */ + apiKeyCreated: (name: string) => string, + /** + * The heading of the key that was just created, from the name of the key. + */ + secretTitle: (name: string) => string, + /** + * Says that the key is shown once. + */ + secretWarning: string, + /** + * The button that copies the key. + */ + copy: string, + /** + * Announced once the key was copied. + */ + copied: string, + /** + * Shown when the browser didn't copy the key. + */ + copyFailed: string, + /** + * The button that hides the key once it was copied. + */ + done: string, + /** + * The button that revokes an API key. + */ + revoke: string, + /** + * The question before an API key is revoked, from its name. + */ + revokeQuestion: (name: string) => string, + /** + * Says what revoking a key does. + */ + revokeWarning: string, + /** + * Announced once an API key was revoked, from its name. + */ + revoked: (name: string) => string, + /** + * The heading of the MCP tools a service account can use. + */ + mcpTools: string, + /** + * Says which tools are listed. + */ + mcpToolsDescription: string, + /** + * Shown for a service account that can use no tool. + */ + noMcpTools: string, + /** + * Shown when the tools couldn't be loaded. + */ + mcpToolsLoadingFailed: string, + /** + * Shown for a tool that reads. + */ + readTool: string, + /** + * Shown for a tool that proposes a change. + */ + writeTool: string +}; diff --git a/projects/ngx-auth/service-accounts/service-accounts.component.html b/projects/ngx-auth/service-accounts/service-accounts.component.html new file mode 100644 index 0000000..90f7ae7 --- /dev/null +++ b/projects/ngx-auth/service-accounts/service-accounts.component.html @@ -0,0 +1,267 @@ +
+
+
+ {{ labels.title }} + @if (canManage()) { + + } +
+

{{ labels.description }}

+
+ @if (loadingFailed()) { + + } + @if (error().length) { +
+ + @for (paragraph of error(); track $index) { +

{{ paragraph }}

+ } +
+
+ } + + @if (creating()) { +
+ {{ labels.create }} + + + + + +
+ } + + @if (rows().length) { +
    + @for (row of rows(); track row.serviceAccount.id) { +
  • +
    +
    + + {{ row.serviceAccount.name }} + +
    +
    {{ labels.roles }}
    +
    {{ row.roles }}
    + @if (actsInTenant()) { +
    {{ labels.tenantRoles }}
    +
    {{ row.tenantRoles }}
    + } +
    +
    + @if (canManage()) { +
    + + + +
    + } +
    + + @if (row.changingRoles) { + + + + + } + @if (row.addingApiKey) { +
    + {{ labels.addApiKey }} + + + + + @if (actsInTenant()) { + + } + + + +
    + } + @if (row.secret; as secret) { + +
    +

    {{ labels.secretWarning }}

    +

    {{ secret.key }}

    + @if (copyError(); as copyError) { + + } +
    + + +
    +
    +
    + } + +
    + {{ labels.apiKeys }} + @if (row.apiKeys.length) { +
      + @for (apiKey of row.apiKeys; track apiKey.apiKey.id) { +
    • +
      +

      {{ apiKey.apiKey.name }}

      +
      +
      {{ labels.permissions }}
      +
      {{ apiKey.permissions }}
      +
      {{ labels.actsIn }}
      +
      {{ apiKey.actsIn }}
      +
      {{ labels.expiresAt }}
      +
      {{ apiKey.expiresAt }}
      +
      {{ labels.lastUsedAt }}
      +
      {{ apiKey.lastUsedAt }}
      +
      {{ labels.createdAt }}
      +
      {{ apiKey.createdAt }}
      +
      +
      + @if (canManage()) { + + } +
    • + } +
    + } @else { +

    {{ labels.noApiKeys }}

    + } +
    + + @if (showsMcpTools) { +
    + {{ labels.mcpTools }} +

    {{ labels.mcpToolsDescription }}

    + @if (mcpToolsLoadingFailed()) { +

    {{ labels.mcpToolsLoadingFailed }}

    + } @else if (row.mcpTools; as tools) { + @if (tools.length) { +
      + @for (tool of tools; track tool.tool.name) { +
    • + @if (tool.tool.title) { + {{ tool.tool.title }} + } + {{ tool.tool.name }} + {{ tool.kind }} +
    • + } +
    + } @else { +

    {{ labels.noMcpTools }}

    + } + } +
    + } +
  • + } +
+ } + @if (isEmpty()) { +

{{ labels.noServiceAccounts }}

+ } + +

{{ announcement() }}

+
+ + + + + @if (offersTenantRoles()) { + + } + + + + + @if (formError().length) { + + } +
+ + +
+
diff --git a/projects/ngx-auth/service-accounts/service-accounts.component.spec.ts b/projects/ngx-auth/service-accounts/service-accounts.component.spec.ts new file mode 100644 index 0000000..0b9a0e3 --- /dev/null +++ b/projects/ngx-auth/service-accounts/service-accounts.component.spec.ts @@ -0,0 +1,343 @@ +// the DialogService renders the questions into the body, so the tests find them there. +import { provideHttpClient, withInterceptors } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component, Service, signal, WritableSignal } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideRouter } from '@angular/router'; +import { authInterceptor, AuthService, provideAuth } from '@service-soft/ngx-auth/auth'; +import { DialogTestingUtilities } from 'testing/dialog'; +import { FormTestingUtilities } from 'testing/form'; +import { HttpTestingUtilities } from 'testing/http'; +import { PopoverTestingUtilities } from 'testing/popover'; +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; +import { CreatedServiceAccountApiKeyModel, McpToolSummaryModel, ServiceAccountModel } from 'zibri-contract'; + +import { ServiceAccountsConfigChanges } from './service-accounts-config-changes.model'; +import { provideServiceAccountsConfig } from './service-accounts-config.provider'; +import { ServiceAccountsComponent } from './service-accounts.component'; + +const API: string = 'https://api.example.com'; +const ACCOUNTS: string = `${API}/service-accounts`; +const TOOLS: string = `${API}/service-account-tools`; +const TENANT_ID: string = 'tenant-1'; +const HOUR: number = 3_600_000; + +@Service() +class AppAuthService extends AuthService {} + +@Component({ selector: 'ngx-page', template: '' }) +class PageComponent {} + +@Component({ + selector: 'ngx-host', + template: '', + imports: [ServiceAccountsComponent] +}) +class HostComponent { + readonly canManage: WritableSignal = signal(true); +} + +// the assistant of the team, with a key bound to the tenant, and an importer with an old key acting everywhere. +const SERVICE_ACCOUNTS: ServiceAccountModel[] = [ + { + id: 'assistant-id', + name: 'assistant', + roles: [], + tenantRoles: ['member'], + apiKeys: [{ + id: 'key-1', + name: 'Claude', + permissions: ['tasks.read'], + tenantId: TENANT_ID, + createdAt: '2026-11-01T10:00:00.000Z', + requireDpop: false + }] + }, + { + id: 'importer-id', + name: 'importer', + roles: ['user'], + tenantRoles: [], + apiKeys: [{ + id: 'key-2', + name: 'Nightly import', + permissions: ['tasks.read', 'tasks.write'], + expiresAt: '2027-01-01T00:00:00.000Z', + lastUsedAt: '2026-11-20T03:00:00.000Z', + createdAt: '2026-10-01T10:00:00.000Z', + requireDpop: false + }] + } +]; + +const TOOLS_OF_ASSISTANT: McpToolSummaryModel[] = [ + { name: 'tasks.find', title: 'Find tasks', description: 'Finds the tasks of the team.', kind: 'read', permission: 'tasks.read' }, + { name: 'tasks.close', description: 'Proposes closing a task.', kind: 'write', permission: 'tasks.propose' } +]; + +const CONFIG: ServiceAccountsConfigChanges = { + baseUrl: ACCOUNTS, + roles: [{ label: 'User', value: 'user' }], + tenantRoles: [{ label: 'Member', value: 'member' }, { label: 'Owner', value: 'owner' }], + permissions: [{ label: 'Read tasks', value: 'tasks.read' }, { label: 'Write tasks', value: 'tasks.write' }] +}; + +function inMs(ms: number): string { + return new Date(Date.now() + ms).toISOString(); +} + +/** + * Renders the service accounts for a user logged in with tokens, who acts in a tenant, and answers the list. + * @param config - What to change of the config of the suite, like the url of the MCP tools. + * @param canManage - Whether the user manages the service accounts. + * @returns The element, the fixture and the backend. + */ +async function render( + config: ServiceAccountsConfigChanges = {}, + canManage: boolean = true +): Promise<[HTMLElement, ComponentFixture, HttpTestingController]> { + localStorage.setItem('authData', JSON.stringify({ + strategy: 'jwt', + userId: 'user-1', + roles: [], + expiresAt: inMs(24 * HOUR), + accessToken: { value: 'access-1', expirationDate: inMs(HOUR) }, + refreshToken: { value: 'refresh-1', expirationDate: inMs(24 * HOUR) }, + activeTenantId: TENANT_ID + })); + TestBed.configureTestingModule({ + providers: [ + provideRouter([{ path: '**', component: PageComponent }]), + provideHttpClient(withInterceptors([authInterceptor])), + provideHttpClientTesting(), + provideAuth(AppAuthService, { apiUrl: `${API}/auth`, strategy: 'jwt' }), + provideServiceAccountsConfig({ ...CONFIG, ...config }) + ] + }); + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + fixture.componentInstance.canManage.set(canManage); + document.body.append(fixture.nativeElement as HTMLElement); + // rendered without waiting for it to be stable, which it is once the list it loads arrived + fixture.detectChanges(); + const backend: HttpTestingController = TestBed.inject(HttpTestingController); + const list: TestRequest = await vi.waitFor(() => backend.expectOne(ACCOUNTS)); + expect(list.request.headers.get('authorization')).toBe('Bearer access-1'); + expect(list.request.headers.get('x-tenant-id')).toBe(TENANT_ID); + list.flush(SERVICE_ACCOUNTS); + const root: HTMLElement = fixture.nativeElement as HTMLElement; + await vi.waitFor(() => expect(findRows(root)).toHaveLength(2)); + return [root, fixture, backend]; +} + +// the service accounts, each a list item of the outer list +function findRows(root: HTMLElement): HTMLLIElement[] { + return [...root.querySelectorAll('ul.grid > li')]; +} + +function findRow(root: HTMLElement, name: string): HTMLLIElement { + const row: HTMLLIElement | undefined = findRows(root).find(candidate => FormTestingUtilities.getText(candidate, 'ui-heading') === name); + if (row == undefined) { + throw new Error(`There is no service account "${name}".`); + } + return row; +} + +// the texts of an element as a reader reads them, a space between those of two elements +function getText(element: Element | null): string { + if (element == undefined) { + return ''; + } + const walker: TreeWalker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT); + const texts: string[] = []; + for (let node: Node | null = walker.nextNode(); node != undefined; node = walker.nextNode()) { + texts.push(node.textContent ?? ''); + } + return texts.join(' ').replaceAll(/\s+/g, ' ').trim(); +} + +async function chooseChip(fixture: ComponentFixture, root: HTMLElement, name: string, text: string): Promise { + const input: HTMLInputElement | null = FormTestingUtilities.findInput(root, name); + if (input == undefined) { + throw new Error(`There is no input named "${name}".`); + } + input.value = text; + input.dispatchEvent(new InputEvent('input', { inputType: 'insertText' })); + await fixture.whenStable(); + const option: HTMLElement | undefined = [...root.querySelectorAll('[role="option"]')] + .find(candidate => candidate.textContent.trim() === text); + if (option == undefined) { + throw new Error(`There is no option "${text}".`); + } + option.click(); + await fixture.whenStable(); +} + +async function findQuestion(): Promise { + return await vi.waitFor(() => document.querySelector('dialog') ?? Promise.reject(new Error('no question yet'))); +} + +describe('ServiceAccountsComponent', () => { + let removeModalDialogs: () => void; + let removePopovers: () => void; + + beforeEach(() => { + document.body.replaceChildren(); + removeModalDialogs = DialogTestingUtilities.addModalDialogs(); + // the options of the roles and the permissions open as a popover + removePopovers = PopoverTestingUtilities.addPopovers(); + }); + + afterEach(() => { + removeModalDialogs(); + removePopovers(); + localStorage.clear(); + TestBed.inject(HttpTestingController).verify(); + }); + + test('lists the service accounts with their roles and keys, never a secret, and nothing that changes them without canManage', async () => { + const [root] = await render({}, false); + const format: Intl.DateTimeFormat = new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeStyle: 'short' }); + + expect(getText(root.querySelector('h2'))).toBe('Service accounts'); + expect(getText(findRow(root, 'assistant').querySelector('dl'))).toBe('Roles None Roles in this tenant Member'); + expect(getText(findRow(root, 'assistant').querySelector(':scope ul li'))).toBe( + `Claude Permissions Read tasks Acts in This tenant only Expires Never Last used Never Created ${format.format(new Date('2026-11-01T10:00:00.000Z'))}` + ); + expect(getText(findRow(root, 'importer').querySelector(':scope ul li dl'))).toContain( + `Permissions Read tasks, Write tasks Acts in Every tenant of the account Expires ${format.format(new Date('2027-01-01T00:00:00.000Z'))}` + ); + expect(root.querySelectorAll('button')).toHaveLength(0); + // without the url of their route, the tools are neither loaded nor shown + expect(root.textContent).not.toContain('MCP tools'); + }); + + test('shows the MCP tools each service account can use, whether they read or propose changes', async () => { + const [root, , backend] = await render({ mcpToolsBaseUrl: TOOLS }, false); + + (await vi.waitFor(() => backend.expectOne(`${TOOLS}/assistant-id`))).flush(TOOLS_OF_ASSISTANT); + backend.expectOne(`${TOOLS}/importer-id`).flush([]); + + await vi.waitFor(() => expect(getText(findRow(root, 'assistant'))).toContain('Find tasks tasks.find Reads')); + expect(getText(findRow(root, 'assistant'))).toContain('MCP tools it can use By its roles in the tenant you act in. A key that lists fewer permissions opens fewer of them. Find tasks tasks.find Reads tasks.close Proposes changes, which a person approves'); + expect(getText(findRow(root, 'importer'))).toContain('Its roles open none of the tools.'); + }); + + test('creates a service account with its roles, and says so', async () => { + const [root, fixture, backend] = await render(); + + FormTestingUtilities.click(root, 'Create a service account'); + await fixture.whenStable(); + expect(document.activeElement?.getAttribute('name')).toBe('name'); + FormTestingUtilities.type(root, 'name', ' reports '); + await chooseChip(fixture, root, 'tenantRoles', 'Owner'); + FormTestingUtilities.click(root.querySelector('form') ?? root, 'Save'); + const create: TestRequest = await vi.waitFor(() => backend.expectOne({ method: 'POST', url: ACCOUNTS })); + expect(create.request.body).toEqual({ name: 'reports', roles: [], tenantRoles: ['owner'] }); + create.flush({ id: 'reports-id', name: 'reports', roles: [], tenantRoles: ['owner'], apiKeys: [] }); + + await vi.waitFor(() => expect(findRows(root)).toHaveLength(3)); + expect(findRows(root).map(row => FormTestingUtilities.getText(row, 'ui-heading'))).toEqual(['assistant', 'importer', 'reports']); + expect(FormTestingUtilities.getText(root, '[role="status"]')).toBe('The service account reports was created.'); + expect(root.querySelector('form')).toBeNull(); + }); + + test('shows the message of the api in the form when it refuses a service account', async () => { + const [root, fixture, backend] = await render(); + + FormTestingUtilities.click(root, 'Create a service account'); + await fixture.whenStable(); + FormTestingUtilities.type(root, 'name', 'assistant'); + FormTestingUtilities.click(root.querySelector('form') ?? root, 'Save'); + (await vi.waitFor(() => backend.expectOne({ method: 'POST', url: ACCOUNTS }))).flush( + { name: 'ConflictError', message: 'A user with this email exists already.', paragraphs: ['A user with this email exists already.'] }, + { status: 409, statusText: 'Conflict' } + ); + + await vi.waitFor(() => expect(FormTestingUtilities.getText(root, 'form [role="alert"] p')).toBe('A user with this email exists already.')); + expect(findRows(root)).toHaveLength(2); + }); + + test('changes the roles of a service account', async () => { + const [root, fixture, backend] = await render(); + const row: HTMLLIElement = findRow(root, 'assistant'); + + FormTestingUtilities.click(row, 'Change the roles'); + await fixture.whenStable(); + await chooseChip(fixture, row, 'roles', 'User'); + FormTestingUtilities.click(row, 'Save'); + const update: TestRequest = await vi.waitFor(() => backend.expectOne({ method: 'PUT', url: `${ACCOUNTS}/assistant-id/roles` })); + expect(update.request.body).toEqual({ roles: ['user'], tenantRoles: ['member'] }); + update.flush({ ...SERVICE_ACCOUNTS[0], roles: ['user'] }); + + await vi.waitFor(() => expect(getText(findRow(root, 'assistant').querySelector('dl'))).toBe('Roles User Roles in this tenant Member')); + expect(FormTestingUtilities.getText(root, '[role="status"]')).toBe('The roles of assistant were saved.'); + }); + + test('adds a key bound to the tenant, shows its secret once with a button that copies it, and hides it when the user is done', async () => { + const writeText: (text: string) => Promise = vi.fn(async () => await Promise.resolve()); + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }); + const [root, fixture, backend] = await render(); + const row: HTMLLIElement = findRow(root, 'assistant'); + + FormTestingUtilities.click(row, 'Add an API key'); + await fixture.whenStable(); + expect(FormTestingUtilities.findInput(row, 'bindToTenant')?.checked).toBe(true); + expect(FormTestingUtilities.findInput(row, 'requireDpop')?.checked).toBe(false); + FormTestingUtilities.type(row, 'apiKeyName', 'Assistant of the team'); + await chooseChip(fixture, row, 'permissions', 'Read tasks'); + FormTestingUtilities.click(row, 'Save'); + const create: TestRequest = await vi.waitFor(() => backend.expectOne({ method: 'POST', url: `${ACCOUNTS}/assistant-id/api-keys` })); + expect(create.request.body).toEqual({ name: 'Assistant of the team', permissions: ['tasks.read'], tenantId: TENANT_ID, requireDpop: false }); + const created: CreatedServiceAccountApiKeyModel = { + apiKey: { id: 'key-3', name: 'Assistant of the team', permissions: ['tasks.read'], tenantId: TENANT_ID, createdAt: '2026-11-26T10:00:00.000Z', requireDpop: false }, + key: 'zibri_secret-of-the-assistant' + }; + create.flush(created); + + await vi.waitFor(() => expect(getText(findRow(root, 'assistant'))).toContain('zibri_secret-of-the-assistant')); + expect(getText(findRow(root, 'assistant'))).toContain('You won\'t see it again'); + expect(document.activeElement?.getAttribute('data-action')).toBe('copy'); + FormTestingUtilities.click(findRow(root, 'assistant'), 'Copy the key'); + await vi.waitFor(() => expect(FormTestingUtilities.getText(root, '[role="status"]')).toBe('The key was copied.')); + expect(writeText).toHaveBeenCalledWith('zibri_secret-of-the-assistant'); + expect(findRow(root, 'assistant').querySelectorAll(':scope ul li')).toHaveLength(2); + + FormTestingUtilities.click(findRow(root, 'assistant'), 'Done'); + await fixture.whenStable(); + expect(root.textContent).not.toContain('zibri_secret-of-the-assistant'); + Reflect.deleteProperty(navigator, 'clipboard'); + }); + + test('revokes a key once the user confirmed it', async () => { + const [root, fixture, backend] = await render(); + + FormTestingUtilities.click(findRow(root, 'importer').querySelector(':scope ul li') ?? root, 'Revoke'); + const question: HTMLDialogElement = await findQuestion(); + expect(FormTestingUtilities.getText(question, 'h2')).toBe('Revoke the API key Nightly import?'); + FormTestingUtilities.click(question, 'Revoke'); + HttpTestingUtilities.flushNoContent(await vi.waitFor(() => backend.expectOne({ method: 'DELETE', url: `${ACCOUNTS}/importer-id/api-keys/key-2` }))); + + await vi.waitFor(() => expect(getText(findRow(root, 'importer'))).toContain('It has no API key yet.')); + await fixture.whenStable(); + expect(FormTestingUtilities.getText(root, '[role="status"]')).toBe('The API key Nightly import was revoked.'); + }); + + test('deletes a service account once the user confirmed it, and nothing while they cancel', async () => { + const [root, fixture, backend] = await render(); + + FormTestingUtilities.click(findRow(root, 'importer'), 'Delete'); + const cancelled: HTMLDialogElement = await findQuestion(); + expect(FormTestingUtilities.getText(cancelled, 'h2')).toBe('Delete the service account importer?'); + FormTestingUtilities.click(cancelled, 'Cancel'); + await fixture.whenStable(); + backend.expectNone({ method: 'DELETE' }); + cancelled.remove(); + + FormTestingUtilities.click(findRow(root, 'importer'), 'Delete'); + FormTestingUtilities.click(await findQuestion(), 'Delete'); + HttpTestingUtilities.flushNoContent(await vi.waitFor(() => backend.expectOne({ method: 'DELETE', url: `${ACCOUNTS}/importer-id` }))); + + await vi.waitFor(() => expect(findRows(root)).toHaveLength(1)); + expect(FormTestingUtilities.getText(root, '[role="status"]')).toBe('The service account importer was deleted.'); + }); +}); diff --git a/projects/ngx-auth/service-accounts/service-accounts.component.ts b/projects/ngx-auth/service-accounts/service-accounts.component.ts new file mode 100644 index 0000000..155ff51 --- /dev/null +++ b/projects/ngx-auth/service-accounts/service-accounts.component.ts @@ -0,0 +1,706 @@ +import { DOCUMENT, NgTemplateOutlet } from '@angular/common'; +import { afterNextRender, booleanAttribute, Component, computed, ElementRef, inject, Injector, input, InputSignalWithTransform, LOCALE_ID, resource, ResourceRef, Signal, signal, viewChild, WritableSignal } from '@angular/core'; +import { AuthErrorUtilities, AuthService } from '@service-soft/ngx-auth/auth'; +import { BadgeColor, BadgeComponent } from '@service-soft/ui/badge'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { ConfirmDialogComponent, DialogService } from '@service-soft/ui/dialog'; +import { FormComponent } from '@service-soft/ui/form'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { InputOption } from '@service-soft/ui/input'; +import { InputBooleanComponent } from '@service-soft/ui/input-boolean'; +import { InputChipsComponent } from '@service-soft/ui/input-chips'; +import { InputDateComponent } from '@service-soft/ui/input-date'; +import { InputStringComponent } from '@service-soft/ui/input-string'; +import { LoadingDirective } from '@service-soft/ui/loading'; +import { CreatedServiceAccountApiKeyModel, McpToolSummaryModel, ServiceAccountApiKeyModel, ServiceAccountModel, ZIBRI_SERVICE_ACCOUNT_LIMITS } from 'zibri-contract'; + +import { ServiceAccountsConfig } from './service-accounts-config.model'; +import { SERVICE_ACCOUNTS_CONFIG } from './service-accounts-config.provider'; +import { ServiceAccountsLabels } from './service-accounts-labels.model'; +import { ServiceAccountsService } from './service-accounts.service'; + +// the sections of a view are headed one level below it, and a heading of level 6 has no level below. +const SECTION_LEVELS: Record = { 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 6 }; + +// tells the ids of several views on one page apart +let nextId: number = 0; + +/** + * The form creating a service account. + */ +type CreateForm = { + /** + * What the form does. + */ + kind: 'create' +}; + +/** + * A form changing the roles of a service account, or adding a key to it. + */ +type AccountForm = { + /** + * What the form does. + */ + kind: 'roles' | 'apiKey', + /** + * The service account it changes. + */ + serviceAccountId: string +}; + +/** + * The form that shows. + */ +type ServiceAccountForm = CreateForm | AccountForm; + +/** + * A key that was just created, shown until the user is done with it. + */ +type ShownSecret = { + /** + * The service account it belongs to. + */ + serviceAccountId: string, + /** + * The name of the key. + */ + name: string, + /** + * The key itself. + */ + key: string +}; + +/** + * An API key as it shows in the list. + */ +type ApiKeyRow = { + /** + * The key. + */ + apiKey: ServiceAccountApiKeyModel, + /** + * The id of its name, which describes its button. + */ + nameId: string, + /** + * Its permissions, in words. + */ + permissions: string, + /** + * Where it acts, in words. + */ + actsIn: string, + /** + * When it expires, in words. + */ + expiresAt: string, + /** + * When it was last used, in words. + */ + lastUsedAt: string, + /** + * When it was created, in words. + */ + createdAt: string +}; + +/** + * A tool of the MCP server as it shows in the list. + */ +type McpToolRow = { + /** + * The tool. + */ + tool: McpToolSummaryModel, + /** + * Whether the tool reads, in words. + */ + kind: string, + /** + * The color of its badge, which tells a tool that proposes changes apart. + */ + color: BadgeColor +}; + +/** + * A service account as it shows in the list. + */ +type ServiceAccountRow = { + /** + * The service account. + */ + serviceAccount: ServiceAccountModel, + /** + * The id of its heading, which describes its buttons. + */ + headingId: string, + /** + * Its platform roles, in words. + */ + roles: string, + /** + * Its roles in the tenant the user acts in, in words. + */ + tenantRoles: string, + /** + * Its keys, oldest first. + */ + apiKeys: ApiKeyRow[], + /** + * Whether the form changing its roles shows. + */ + changingRoles: boolean, + /** + * Whether the form adding a key shows. + */ + addingApiKey: boolean, + /** + * The key just created for it, or undefined. + */ + secret: ShownSecret | undefined, + /** + * The tools its roles open, or undefined while they load or when the app shows none. + */ + mcpTools: McpToolRow[] | undefined +}; + +/** + * The service accounts of the api, like those of AI assistants, at the api of provideServiceAccountsConfig: + * ``. Each shows its roles, its roles in the tenant the user acts in, its API keys + * with their permissions, where they act and when they expire, never their secret, and the MCP tools it can use when + * the app names their route. With `canManage`, like `service-accounts.manage`, the user creates service accounts, + * changes their roles, adds a key, whose secret shows once with a button that copies it, revokes a key and deletes a + * service account, both after a question. What the api refuses, like a role the user may not hand out, shows its + * message. + */ +@Component({ + selector: 'ngx-service-accounts', + templateUrl: './service-accounts.component.html', + imports: [ + BadgeComponent, + ButtonComponent, + CalloutComponent, + FormComponent, + HeadingComponent, + InputBooleanComponent, + InputChipsComponent, + InputDateComponent, + InputStringComponent, + LoadingDirective, + NgTemplateOutlet + ], + host: { class: 'block' } +}) +export class ServiceAccountsComponent { + /** + * The config of the service accounts. + */ + protected readonly config: ServiceAccountsConfig = inject(SERVICE_ACCOUNTS_CONFIG); + + /** + * Whether the user creates and changes service accounts and their keys, like with `service-accounts.manage`. The + * default comes from provideServiceAccountsConfig. + */ + readonly canManage: InputSignalWithTransform = input(this.config.canManage, { transform: booleanAttribute }); + + /** + * The texts. + */ + protected readonly labels: ServiceAccountsLabels = this.config.labels; + + /** + * The longest values the api takes. + */ + protected readonly limits: typeof ZIBRI_SERVICE_ACCOUNT_LIMITS = ZIBRI_SERVICE_ACCOUNT_LIMITS; + + /** + * The level of the heading of the view. + */ + protected readonly headingLevel: HeadingLevel = this.config.headingLevel; + + /** + * The level of the headings of the service accounts and the form creating one. + */ + protected readonly sectionLevel: HeadingLevel = SECTION_LEVELS[this.config.headingLevel]; + + /** + * The level of the headings of the keys and the tools of a service account. + */ + protected readonly subsectionLevel: HeadingLevel = SECTION_LEVELS[this.sectionLevel]; + + /** + * Whether the view shows the MCP tools of each service account. + */ + protected readonly showsMcpTools: boolean = this.config.mcpToolsBaseUrl != undefined; + + /** + * The form that shows, or undefined for none. + */ + protected readonly form: WritableSignal = signal(undefined); + + /** + * The name of the form creating a service account. + */ + protected readonly name: WritableSignal = signal(''); + + /** + * The platform roles of the form. + */ + protected readonly roles: WritableSignal = signal([]); + + /** + * The roles in the tenant of the form. + */ + protected readonly tenantRoles: WritableSignal = signal([]); + + /** + * The name of the form adding a key. + */ + protected readonly apiKeyName: WritableSignal = signal(''); + + /** + * The permissions of the form adding a key. + */ + protected readonly permissions: WritableSignal = signal([]); + + /** + * The day the key of the form stops working at the end of, or undefined for one that works until it is revoked. + */ + protected readonly expiresOn: WritableSignal = signal(undefined); + + /** + * Whether the key of the form acts only in the tenant the user acts in. + */ + protected readonly bindToTenant: WritableSignal = signal(true); + + /** + * Whether the key of the form is only exchanged for tokens bound to a DPoP key. + */ + protected readonly requireDpop: WritableSignal = signal(false); + + /** + * The first day a key can expire at the end of. + */ + protected readonly today: Date = new Date(new Date().setHours(0, 0, 0, 0)); + + /** + * Whether the form waits for the api. + */ + protected readonly saving: WritableSignal = signal(false); + + /** + * Why the api refused what the form sent, one paragraph each, or none. + */ + protected readonly formError: WritableSignal = signal([]); + + /** + * Why the api refused deleting or revoking, one paragraph each, or none. + */ + protected readonly error: WritableSignal = signal([]); + + /** + * Why the key that was just created couldn't be copied, or none. + */ + protected readonly copyError: WritableSignal = signal(undefined); + + /** + * What the view last said about a change, read by screen readers as it changes. + */ + protected readonly announcement: WritableSignal = signal(''); + + private readonly serviceAccountsService: ServiceAccountsService = inject(ServiceAccountsService); + + private readonly authService: AuthService = inject(AuthService); + + private readonly dialogService: DialogService = inject(DialogService); + + private readonly document: Document = inject(DOCUMENT); + + private readonly injector: Injector = inject(Injector); + + private readonly element: HTMLElement = inject>(ElementRef).nativeElement; + + private readonly dateTimeFormat: Intl.DateTimeFormat = new Intl.DateTimeFormat(inject(LOCALE_ID), this.config.dateTimeFormat); + + private readonly idPrefix: string = `ngx-service-accounts-${nextId++}`; + + private readonly createButton: Signal | undefined> = viewChild('createButton', { read: ElementRef }); + + /** + * The key that was just created, or undefined. + */ + private readonly secret: WritableSignal = signal(undefined); + + // the button that opened the form, which gets the focus back once it closes + private opener: HTMLElement | undefined; + + // changes of this view update it in place rather than loading it again, so the list and the focus in it stay + private readonly serviceAccounts: ResourceRef = resource({ + loader: async () => await this.serviceAccountsService.resolveServiceAccounts() + }); + + // loaded again whenever a service account comes or goes or its roles change, which decide its tools, and not for a + // key added or revoked + private readonly mcpTools: ResourceRef | undefined> = resource({ + params: () => { + if (!this.showsMcpTools || !this.serviceAccounts.hasValue()) { + return undefined; + } + return JSON.stringify((this.serviceAccounts.value() ?? []) + .map(serviceAccount => [serviceAccount.id, serviceAccount.roles, serviceAccount.tenantRoles])); + }, + loader: async () => { + const serviceAccounts: ServiceAccountModel[] = this.serviceAccounts.hasValue() ? this.serviceAccounts.value() ?? [] : []; + return new Map(await Promise.all(serviceAccounts.map(async serviceAccount => { + const entry: [string, McpToolSummaryModel[]] = [serviceAccount.id, await this.serviceAccountsService.resolveMcpTools(serviceAccount.id)]; + return entry; + }))); + } + }); + + /** + * Whether the service accounts are loading. + */ + protected readonly isLoading: Signal = computed(() => this.serviceAccounts.isLoading()); + + /** + * Whether the service accounts couldn't be loaded. + */ + protected readonly loadingFailed: Signal = computed(() => this.serviceAccounts.error() != undefined); + + /** + * Whether the tools couldn't be loaded. + */ + protected readonly mcpToolsLoadingFailed: Signal = computed(() => this.mcpTools.error() != undefined); + + /** + * Whether the user acts in a tenant, which roles in the tenant and keys bound to it need. + */ + protected readonly actsInTenant: Signal = computed(() => this.authService.activeTenantId() != undefined); + + /** + * Whether the forms offer roles in the tenant. + */ + protected readonly offersTenantRoles: Signal = computed(() => this.actsInTenant() && this.config.tenantRoles.length > 0); + + /** + * Whether the form creating a service account shows. + */ + protected readonly creating: Signal = computed(() => this.form()?.kind === 'create'); + + /** + * The service accounts as they show, by name. + */ + protected readonly rows: Signal = computed(() => { + const serviceAccounts: ServiceAccountModel[] = this.serviceAccounts.hasValue() ? this.serviceAccounts.value() ?? [] : []; + const form: ServiceAccountForm | undefined = this.form(); + const secret: ShownSecret | undefined = this.secret(); + const tools: Map | undefined = this.mcpTools.hasValue() ? this.mcpTools.value() : undefined; + return serviceAccounts.map(serviceAccount => ({ + serviceAccount, + headingId: `${this.idPrefix}-${serviceAccount.id}`, + roles: this.describe(serviceAccount.roles, this.config.roles), + tenantRoles: this.describe(serviceAccount.tenantRoles, this.config.tenantRoles), + apiKeys: serviceAccount.apiKeys.map(apiKey => this.toApiKeyRow(apiKey)), + changingRoles: form?.kind === 'roles' && form.serviceAccountId === serviceAccount.id, + addingApiKey: form?.kind === 'apiKey' && form.serviceAccountId === serviceAccount.id, + secret: secret?.serviceAccountId === serviceAccount.id ? secret : undefined, + mcpTools: tools?.get(serviceAccount.id)?.map(tool => tool.kind === 'read' + ? { tool, kind: this.labels.readTool, color: 'neutral' } + : { tool, kind: this.labels.writeTool, color: 'secondary' }) + })); + }); + + /** + * Whether the view says there are no service accounts: once they loaded. + */ + protected readonly isEmpty: Signal = computed(() => this.serviceAccounts.hasValue() && !this.rows().length); + + /** + * Shows the empty form creating a service account, or hides it. + * @param event - The click on the button that toggles it. + */ + protected toggleCreate(event: Event): void { + this.toggle({ kind: 'create' }, undefined, event); + } + + /** + * Shows the form changing the roles of a service account, filled with its roles, or hides it. + * @param serviceAccount - The service account. + * @param event - The click on the button that toggles it. + */ + protected toggleRoles(serviceAccount: ServiceAccountModel, event: Event): void { + this.toggle({ kind: 'roles', serviceAccountId: serviceAccount.id }, serviceAccount, event); + } + + /** + * Shows the empty form adding a key to a service account, or hides it. + * @param serviceAccount - The service account. + * @param event - The click on the button that toggles it. + */ + protected toggleApiKey(serviceAccount: ServiceAccountModel, event: Event): void { + this.toggle({ kind: 'apiKey', serviceAccountId: serviceAccount.id }, undefined, event); + } + + /** + * Hides the form without saving it, and gives the focus back to the button that opened it. + */ + protected closeForm(): void { + this.form.set(undefined); + this.formError.set([]); + const opener: HTMLElement | undefined = this.opener; + this.focusAfterRender(() => opener); + } + + /** + * Creates the service account of the form. + */ + protected async create(): Promise { + await this.send(async () => { + const created: ServiceAccountModel = await this.serviceAccountsService.createServiceAccount({ + name: this.name().trim(), + roles: this.roles(), + tenantRoles: this.offersTenantRoles() ? this.tenantRoles() : [] + }); + this.serviceAccounts.update(serviceAccounts => this.sorted([...serviceAccounts ?? [], created])); + return this.labels.created(created.name); + }); + } + + /** + * Saves the roles of the form as those of a service account. Roles of the tenant the view doesn't offer stay. + * @param serviceAccount - The service account. + */ + protected async saveRoles(serviceAccount: ServiceAccountModel): Promise { + await this.send(async () => { + const saved: ServiceAccountModel = await this.serviceAccountsService.updateRoles(serviceAccount.id, { + roles: this.roles(), + tenantRoles: this.offersTenantRoles() ? this.tenantRoles() : serviceAccount.tenantRoles + }); + this.replace(saved); + return this.labels.rolesSaved(saved.name); + }); + } + + /** + * Creates the key of the form, and shows it once. + * @param serviceAccount - The service account it is for. + */ + protected async addApiKey(serviceAccount: ServiceAccountModel): Promise { + await this.send(async () => { + const expiresOn: Date | undefined = this.expiresOn(); + const tenantId: string | undefined = this.bindToTenant() ? this.authService.activeTenantId() : undefined; + const created: CreatedServiceAccountApiKeyModel = await this.serviceAccountsService.createApiKey(serviceAccount.id, { + name: this.apiKeyName().trim(), + permissions: this.permissions(), + ...tenantId == undefined ? {} : { tenantId }, + // at the end of the day, which is when the next one begins + ...expiresOn == undefined + ? {} + : { expiresAt: new Date(expiresOn.getFullYear(), expiresOn.getMonth(), expiresOn.getDate() + 1).toISOString() }, + requireDpop: this.requireDpop() + }); + this.replace({ ...serviceAccount, apiKeys: [...serviceAccount.apiKeys, created.apiKey] }); + this.copyError.set(undefined); + this.secret.set({ serviceAccountId: serviceAccount.id, name: created.apiKey.name, key: created.key }); + return this.labels.apiKeyCreated(created.apiKey.name); + }, () => this.element.querySelector('[data-action="copy"]') ?? undefined); + } + + /** + * Copies the key that was just created, or says that the browser refused to. + */ + protected async copy(): Promise { + const key: string | undefined = this.secret()?.key; + this.copyError.set(undefined); + this.announcement.set(''); + // undefined without a secure context, like on plain http, where the user copies the key themselves + const clipboard: Clipboard | undefined = this.document.defaultView?.navigator.clipboard; + const copied: boolean = key != undefined && clipboard != undefined && await clipboard.writeText(key).then(() => true, () => false); + if (!copied) { + this.copyError.set(this.labels.copyFailed); + return; + } + this.announcement.set(this.labels.copied); + } + + /** + * Hides the key that was just created, which no request shows again. + * @param row - The service account it belongs to. + */ + protected dismissSecret(row: ServiceAccountRow): void { + this.secret.set(undefined); + this.copyError.set(undefined); + this.focusAddApiKey(row.serviceAccount.id); + } + + /** + * Revokes a key, after asking. + * @param serviceAccount - The service account it belongs to. + * @param apiKey - The key. + */ + protected async revoke(serviceAccount: ServiceAccountModel, apiKey: ServiceAccountApiKeyModel): Promise { + const confirmed: boolean = await this.confirm(this.labels.revokeQuestion(apiKey.name), this.labels.revokeWarning, this.labels.revoke); + if (!confirmed || !await this.run(async () => await this.serviceAccountsService.revokeApiKey(serviceAccount.id, apiKey.id))) { + return; + } + this.replace({ ...serviceAccount, apiKeys: serviceAccount.apiKeys.filter(candidate => candidate.id !== apiKey.id) }); + this.announcement.set(this.labels.revoked(apiKey.name)); + // the button that was focused is gone with its key + this.focusAddApiKey(serviceAccount.id); + } + + /** + * Deletes a service account, after asking. The api revokes its keys with it. + * @param serviceAccount - The service account. + */ + protected async delete(serviceAccount: ServiceAccountModel): Promise { + const confirmed: boolean = await this.confirm( + this.labels.deleteQuestion(serviceAccount.name), + this.labels.deleteWarning, + this.labels.delete + ); + if (!confirmed || !await this.run(async () => await this.serviceAccountsService.deleteServiceAccount(serviceAccount.id))) { + return; + } + this.serviceAccounts.update(serviceAccounts => serviceAccounts?.filter(candidate => candidate.id !== serviceAccount.id)); + const form: ServiceAccountForm | undefined = this.form(); + if (form != undefined && form.kind !== 'create' && form.serviceAccountId === serviceAccount.id) { + this.form.set(undefined); + } + if (this.secret()?.serviceAccountId === serviceAccount.id) { + this.secret.set(undefined); + } + this.announcement.set(this.labels.deleted(serviceAccount.name)); + // the button that was focused is gone with its row + this.focusAfterRender(() => this.createButton()?.nativeElement); + } + + private toggle(form: ServiceAccountForm, serviceAccount: ServiceAccountModel | undefined, event: Event): void { + if (this.isOpen(form)) { + this.closeForm(); + return; + } + // Safari doesn't focus a button that is clicked, so it is the target of the click rather than the active element + this.opener = event.currentTarget instanceof HTMLElement ? event.currentTarget : undefined; + this.name.set(''); + this.roles.set(serviceAccount?.roles ?? []); + this.tenantRoles.set(serviceAccount?.tenantRoles ?? []); + this.apiKeyName.set(''); + this.permissions.set([]); + this.expiresOn.set(undefined); + // conservative by default: a key that acts in one tenant, sent in the header as an MCP client does + this.bindToTenant.set(this.actsInTenant()); + this.requireDpop.set(false); + this.formError.set([]); + this.error.set([]); + this.form.set(form); + // only one form shows at a time + this.focusAfterRender(() => this.element.querySelector('form input') ?? undefined); + } + + // a change the form sends: what the api refuses shows in the form, which stays; what it does is announced, and the + // form closes + private async send(change: () => Promise, findFocus?: () => HTMLElement | undefined): Promise { + if (this.saving()) { + return; + } + this.saving.set(true); + this.formError.set([]); + this.announcement.set(''); + try { + const announcement: string = await change(); + this.closeForm(); + this.announcement.set(announcement); + if (findFocus != undefined) { + this.focusAfterRender(findFocus); + } + } + catch (error) { + this.formError.set(AuthErrorUtilities.findErrorParagraphs(error) ?? [this.labels.failed]); + } + finally { + this.saving.set(false); + } + } + + // a change of a button outside of the forms, whose refusal shows above the list + private async run(change: () => Promise): Promise { + this.error.set([]); + this.announcement.set(''); + try { + await change(); + return true; + } + catch (error) { + this.error.set(AuthErrorUtilities.findErrorParagraphs(error) ?? [this.labels.failed]); + return false; + } + } + + private async confirm(title: string, warning: string, confirmLabel: string): Promise { + const confirmed: boolean | undefined = await this.dialogService.open(ConfirmDialogComponent, { + title, + paragraphs: [warning], + confirmButtonLabel: confirmLabel, + cancelButtonLabel: this.labels.cancel, + confirmButtonColor: 'error' + }).closed; + return confirmed === true; + } + + private isOpen(form: ServiceAccountForm): boolean { + const current: ServiceAccountForm | undefined = this.form(); + if (current == undefined || current.kind !== form.kind) { + return false; + } + return current.kind === 'create' || form.kind === 'create' || current.serviceAccountId === form.serviceAccountId; + } + + private replace(serviceAccount: ServiceAccountModel): void { + this.serviceAccounts.update(serviceAccounts => (serviceAccounts ?? []) + .map(candidate => candidate.id === serviceAccount.id ? serviceAccount : candidate)); + } + + private sorted(serviceAccounts: ServiceAccountModel[]): ServiceAccountModel[] { + return serviceAccounts.sort((a, b) => a.name.localeCompare(b.name)); + } + + private toApiKeyRow(apiKey: ServiceAccountApiKeyModel): ApiKeyRow { + return { + apiKey, + nameId: `${this.idPrefix}-key-${apiKey.id}`, + permissions: this.describe(apiKey.permissions, this.config.permissions), + actsIn: this.resolveActsIn(apiKey), + expiresAt: apiKey.expiresAt == undefined ? this.labels.neverExpires : this.dateTimeFormat.format(new Date(apiKey.expiresAt)), + lastUsedAt: apiKey.lastUsedAt == undefined ? this.labels.neverUsed : this.dateTimeFormat.format(new Date(apiKey.lastUsedAt)), + createdAt: this.dateTimeFormat.format(new Date(apiKey.createdAt)) + }; + } + + private resolveActsIn(apiKey: ServiceAccountApiKeyModel): string { + if (apiKey.tenantId == undefined) { + return this.labels.everyTenant; + } + return apiKey.tenantId === this.authService.activeTenantId() ? this.labels.thisTenant : this.labels.otherTenant; + } + + // the labels the app gave the values, and a value it gave none as it is + private describe(values: string[], options: InputOption[]): string { + if (!values.length) { + return this.labels.none; + } + return values.map(value => options.find(option => option.value === value)?.label ?? value).join(', '); + } + + private focusAddApiKey(serviceAccountId: string): void { + this.focusAfterRender(() => this.element.querySelector(`[data-add-api-key="${serviceAccountId}"]`) ?? undefined); + } + + private focusAfterRender(findElement: () => HTMLElement | undefined): void { + afterNextRender({ write: () => findElement()?.focus() }, { injector: this.injector }); + } +} diff --git a/projects/ngx-auth/service-accounts/service-accounts.service.ts b/projects/ngx-auth/service-accounts/service-accounts.service.ts new file mode 100644 index 0000000..8ff42c0 --- /dev/null +++ b/projects/ngx-auth/service-accounts/service-accounts.service.ts @@ -0,0 +1,105 @@ +import { HttpClient } from '@angular/common/http'; +import { inject, Service } from '@angular/core'; +import { firstValueFrom } from 'rxjs'; +import { CreatedServiceAccountApiKeyModel, McpToolSummaryModel, NewServiceAccountApiKeyModel, NewServiceAccountModel, ServiceAccountModel, ServiceAccountRolesModel } from 'zibri-contract'; + +import { ServiceAccountsConfig } from './service-accounts-config.model'; +import { SERVICE_ACCOUNTS_CONFIG } from './service-accounts-config.provider'; + +/** + * Sends the requests of the routes of the service accounts at the baseUrl of provideServiceAccountsConfig: `GET /` for + * the service accounts, `POST /` to create one, `PUT /:serviceAccountId/roles` to set its roles, + * `POST /:serviceAccountId/api-keys` to create a key, `DELETE /:serviceAccountId/api-keys/:apiKeyId` to revoke one and + * `DELETE /:serviceAccountId` to delete a service account, and `GET /:serviceAccountId` at the mcpToolsBaseUrl for the + * MCP tools of one. It answers the models of zibri-contract, and the secret of a key only when it was just created. It + * needs HttpClient, from provideHttpClient, with the interceptor of provideAuth, which sends the login and the tenant + * the user acts in. + */ +@Service() +export class ServiceAccountsService { + /** + * Sends the requests. + */ + protected readonly http: HttpClient = inject(HttpClient); + + private readonly config: ServiceAccountsConfig = inject(SERVICE_ACCOUNTS_CONFIG); + + /** + * Loads the service accounts, with their roles in the tenant the user acts in and their keys. + * @returns The service accounts, by name. + */ + async resolveServiceAccounts(): Promise { + return await firstValueFrom(this.http.get(this.resolveUrl())); + } + + /** + * Creates a service account. Rejects with the error of the request when the api refuses it, like with 403 for a role + * the user may not hand out or 409 for a name that is taken. + * @param serviceAccount - Its name and its roles. + * @returns The service account created. + */ + async createServiceAccount(serviceAccount: NewServiceAccountModel): Promise { + return await firstValueFrom(this.http.post(this.resolveUrl(), serviceAccount)); + } + + /** + * Sets the roles of a service account. Rejects with 403 for a role the user may not hand out or take. + * @param serviceAccountId - Its id. + * @param roles - The roles it holds from now on. + * @returns The service account with its roles. + */ + async updateRoles(serviceAccountId: string, roles: ServiceAccountRolesModel): Promise { + return await firstValueFrom(this.http.put(this.resolveUrl(serviceAccountId, 'roles'), roles)); + } + + /** + * Creates an API key of a service account. The api asks for a second factor or a recent login first, which the + * interceptor of provideAuth asks the user for. + * @param serviceAccountId - The id of the service account. + * @param apiKey - What the key may do, where and until when. + * @returns The key as it is stored, and the key itself, which no request answers again. + */ + async createApiKey(serviceAccountId: string, apiKey: NewServiceAccountApiKeyModel): Promise { + return await firstValueFrom(this.http.post(this.resolveUrl(serviceAccountId, 'api-keys'), apiKey)); + } + + /** + * Revokes an API key of a service account. + * @param serviceAccountId - The id of the service account. + * @param apiKeyId - The id of the key. + */ + async revokeApiKey(serviceAccountId: string, apiKeyId: string): Promise { + await firstValueFrom(this.http.delete(this.resolveUrl(serviceAccountId, 'api-keys', apiKeyId))); + } + + /** + * Deletes a service account, whose keys the api revokes with it. + * @param serviceAccountId - Its id. + */ + async deleteServiceAccount(serviceAccountId: string): Promise { + await firstValueFrom(this.http.delete(this.resolveUrl(serviceAccountId))); + } + + /** + * Loads the MCP tools the roles of a service account open in the tenant the user acts in. + * @param serviceAccountId - Its id. + * @returns The tools. + */ + async resolveMcpTools(serviceAccountId: string): Promise { + const base: string | undefined = this.config.mcpToolsBaseUrl; + if (base == undefined) { + throw new Error('The ServiceAccountsService needs the url of the route of the MCP tools of your api. ' + + 'Add provideServiceAccountsConfig({ mcpToolsBaseUrl }) to the providers of your app.'); + } + return await firstValueFrom(this.http.get(`${base}/${encodeURIComponent(serviceAccountId)}`)); + } + + private resolveUrl(...segments: string[]): string { + const base: string | undefined = this.config.baseUrl; + if (base == undefined) { + throw new Error('The ServiceAccountsService needs the url of the routes of the service accounts of your api. ' + + 'Add provideServiceAccountsConfig({ baseUrl }) to the providers of your app.'); + } + return [base, ...segments.map(segment => encodeURIComponent(segment))].join('/'); + } +} diff --git a/projects/ngx-auth/service-accounts/service-accounts.stories.ts b/projects/ngx-auth/service-accounts/service-accounts.stories.ts new file mode 100644 index 0000000..d7ba252 --- /dev/null +++ b/projects/ngx-auth/service-accounts/service-accounts.stories.ts @@ -0,0 +1,238 @@ +import { HttpRequest, provideHttpClient, withInterceptors } from '@angular/common/http'; +import { Service } from '@angular/core'; +import { provideRouter } from '@angular/router'; +import { authInterceptor, AuthService, provideAuth } from '@service-soft/ngx-auth/auth'; +import { applicationConfig, Meta, StoryObj } from '@storybook/angular'; +import { FakeAnswer, HttpTestingUtilities } from 'testing/http'; +import { McpToolSummaryModel, ServiceAccountApiKeyModel, ServiceAccountModel } from 'zibri-contract'; + +import { ServiceAccountsConfigChanges } from './service-accounts-config-changes.model'; +import { provideServiceAccountsConfig } from './service-accounts-config.provider'; +import { ServiceAccountsComponent } from './service-accounts.component'; + +@Service() +class StoryAuthService extends AuthService {} + +const TENANT_ID: string = 'tenant-1'; + +const ACCOUNTS_PATH: string = '/api/service-accounts'; + +const TOOLS_PATH: string = '/api/service-account-tools'; + +// the assistant of the team, with a key bound to the tenant, and an importer acting in every tenant. +const SERVICE_ACCOUNTS: ServiceAccountModel[] = [ + { + id: 'assistant-id', + name: 'assistant', + roles: [], + tenantRoles: ['member'], + apiKeys: [{ + id: 'key-1', + name: 'Claude of the team', + permissions: ['tasks.read', 'tasks.propose'], + tenantId: TENANT_ID, + lastUsedAt: '2026-11-25T09:30:00.000Z', + createdAt: '2026-11-01T10:00:00.000Z', + requireDpop: false + }] + }, + { + id: 'importer-id', + name: 'importer', + roles: ['user'], + tenantRoles: [], + apiKeys: [{ + id: 'key-2', + name: 'Nightly import', + permissions: ['tasks.read'], + expiresAt: '2027-01-01T00:00:00.000Z', + createdAt: '2026-10-01T10:00:00.000Z', + requireDpop: true + }] + } +]; + +const TOOLS: McpToolSummaryModel[] = [ + { name: 'tasks.find', title: 'Find tasks', description: 'Finds the tasks of the team.', kind: 'read', permission: 'tasks.read' }, + { name: 'tasks.close', title: 'Close a task', description: 'Proposes closing a task.', kind: 'write', permission: 'tasks.propose' } +]; + +const CONFIG: ServiceAccountsConfigChanges = { + baseUrl: ACCOUNTS_PATH, + roles: [{ label: 'User', value: 'user' }], + tenantRoles: [{ label: 'Member', value: 'member' }, { label: 'Owner', value: 'owner' }], + permissions: [ + { label: 'Read tasks', value: 'tasks.read' }, + { label: 'Propose changes of tasks', value: 'tasks.propose' } + ] +}; + +// what the AuthService finds in the browser when the app starts: a login of Ada, who acts in her team. +async function startLoggedIn(): Promise { + localStorage.setItem('authData', JSON.stringify({ + strategy: 'cookie', + userId: 'user-1', + roles: [], + expiresAt: new Date(Date.now() + 3_600_000).toISOString(), + activeTenantId: TENANT_ID, + user: { id: 'user-1', email: 'ada@example.com', kind: 'person', memberships: [{ tenantId: TENANT_ID, permissions: [] }], platformPermissions: [] } + })); + return await Promise.resolve({}); +} + +// a text of the body as the api reads it, empty for anything else +function readString(body: unknown, key: string): string { + const value: unknown = Reflect.get(Object(body), key); + return typeof value === 'string' ? value : ''; +} + +// texts of the body as the api reads them, leaving out anything else +function readStrings(body: unknown, key: string): string[] { + const value: unknown = Reflect.get(Object(body), key); + return Array.isArray(value) ? value.filter((item: unknown) => typeof item === 'string') : []; +} + +/** + * Answers like the routes of the service accounts and of their MCP tools would, keeping what the story changes. + * @param initial - The service accounts it starts with. + * @returns The provider of the backend. + */ +function provideBackend(initial: ServiceAccountModel[]): ReturnType { + let serviceAccounts: ServiceAccountModel[] = structuredClone(initial); + let created: number = 0; + return HttpTestingUtilities.provideBackend((request: HttpRequest): FakeAnswer | undefined => { + const path: string[] = new URL(request.url, document.baseURI).pathname.split('/').slice(3); + const [id, child, childId] = path; + // what the cookie login sends with every request that changes something + if (request.url.endsWith('/api/auth/csrf-token')) { + return { status: 200, body: { csrfToken: 'story-csrf-token' } }; + } + if (request.url.includes(TOOLS_PATH)) { + return { status: 200, body: serviceAccounts.find(serviceAccount => serviceAccount.id === id)?.tenantRoles.length ? TOOLS : [] }; + } + switch (`${request.method} ${path.length}`) { + case 'GET 0': { + return { status: 200, body: serviceAccounts }; + } + case 'POST 0': { + const serviceAccount: ServiceAccountModel = { + id: `account-${++created}`, + name: readString(request.body, 'name'), + roles: readStrings(request.body, 'roles'), + tenantRoles: readStrings(request.body, 'tenantRoles'), + apiKeys: [] + }; + serviceAccounts = [...serviceAccounts, serviceAccount]; + return { status: 200, body: serviceAccount }; + } + case 'PUT 2': { + serviceAccounts = serviceAccounts.map(serviceAccount => serviceAccount.id === id + ? { ...serviceAccount, roles: readStrings(request.body, 'roles'), tenantRoles: readStrings(request.body, 'tenantRoles') } + : serviceAccount); + return { status: 200, body: serviceAccounts.find(serviceAccount => serviceAccount.id === id) }; + } + case 'POST 2': { + const apiKey: ServiceAccountApiKeyModel = { + id: `key-${++created}`, + name: readString(request.body, 'name'), + permissions: readStrings(request.body, 'permissions'), + tenantId: Reflect.get(Object(request.body), 'tenantId') === TENANT_ID ? TENANT_ID : undefined, + createdAt: new Date().toISOString(), + requireDpop: Reflect.get(Object(request.body), 'requireDpop') === true + }; + return { status: 200, body: { apiKey, key: 'zibri_3q2-7wEAAAB6tSeyxNfLtB9kWqQ2cVd0mYpZrA' } }; + } + case 'DELETE 3': { + return child === 'api-keys' && childId != undefined ? { status: 204 } : undefined; + } + case 'DELETE 1': { + serviceAccounts = serviceAccounts.filter(serviceAccount => serviceAccount.id !== id); + return { status: 204 }; + } + default: { + return undefined; + } + } + }); +} + +function provideStory(serviceAccounts: ServiceAccountModel[], config: ServiceAccountsConfigChanges): ReturnType { + return applicationConfig({ + providers: [ + provideRouter([]), + provideHttpClient(withInterceptors([authInterceptor])), + provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }), + provideBackend(serviceAccounts), + provideServiceAccountsConfig({ ...CONFIG, ...config }) + ] + }); +} + +// waits for what the view renders once it is clicked, or once the api answered. +async function waitForElement(root: HTMLElement, selector: string): Promise { + for (let attempt: number = 0; attempt < 100; attempt++) { + const found: T | null = root.querySelector(selector); + if (found != undefined) { + return found; + } + await new Promise(resolve => setTimeout(resolve, 20)); + } + throw new Error(`Nothing matches ${selector}.`); +} + +const meta: Meta = { + title: 'Auth/Service accounts', + component: ServiceAccountsComponent, + loaders: [startLoggedIn], + render: args => ({ + props: args, + template: '' + }) +}; +export default meta; + +type Story = StoryObj; + +// creates service accounts, changes their roles, adds and revokes keys and deletes them, with the MCP tools of each. +export const List: Story = { + args: { canManage: true }, + decorators: [provideStory(SERVICE_ACCOUNTS, { mcpToolsBaseUrl: TOOLS_PATH })] +}; + +// lists the service accounts without the controls that change them, like without `service-accounts.manage`. +export const ReadOnly: Story = { + args: { canManage: false }, + decorators: [provideStory(SERVICE_ACCOUNTS, { mcpToolsBaseUrl: TOOLS_PATH })] +}; + +// an app without the MCP plugin, which shows no tools. +export const WithoutMcpTools: Story = { + args: { canManage: true }, + decorators: [provideStory(SERVICE_ACCOUNTS, {})] +}; + +export const Empty: Story = { + args: { canManage: true }, + decorators: [provideStory([], { mcpToolsBaseUrl: TOOLS_PATH })] +}; + +// a key just added to the assistant, whose secret shows once. +export const NewApiKey: Story = { + args: { canManage: true }, + decorators: [provideStory(SERVICE_ACCOUNTS, { mcpToolsBaseUrl: TOOLS_PATH })], + play: async ({ canvasElement }) => { + (await waitForElement(canvasElement, '[data-add-api-key="assistant-id"]')).click(); + const name: HTMLInputElement = await waitForElement(canvasElement, 'input[name="apiKeyName"]'); + name.value = 'Assistant of the support'; + name.dispatchEvent(new Event('input')); + const permissions: HTMLInputElement = await waitForElement(canvasElement, 'input[name="permissions"]'); + permissions.value = 'Read tasks'; + permissions.dispatchEvent(new InputEvent('input', { inputType: 'insertText' })); + (await waitForElement(canvasElement, '[role="option"]')).click(); + // the form submits once the chip of the permission rendered, as the field needs one + await waitForElement(canvasElement, 'ui-input-chips[name="permissions"] li'); + await new Promise(resolve => setTimeout(resolve, 50)); + (await waitForElement(canvasElement, 'ui-form button[type="submit"]')).click(); + await waitForElement(canvasElement, '[data-action="copy"]'); + } +}; diff --git a/projects/ngx-auth/sessions/sessions-config.model.ts b/projects/ngx-auth/sessions/sessions-config.model.ts index 56555b9..4980e76 100644 --- a/projects/ngx-auth/sessions/sessions-config.model.ts +++ b/projects/ngx-auth/sessions/sessions-config.model.ts @@ -11,7 +11,7 @@ export type SessionsLabels = { */ thisDevice: string, /** - * Shown for a login whose browser zibri doesn't know. + * Shown for a login whose browser the api doesn't know. */ unknownBrowser: string, /** @@ -43,7 +43,7 @@ export type SessionsLabels = { */ loggedOut: string, /** - * Shown when a request failed without a message of zibri, like without a connection. + * Shown when a request failed without a message of the api, like without a connection. */ failed: string }; diff --git a/projects/ngx-auth/sessions/sessions.component.ts b/projects/ngx-auth/sessions/sessions.component.ts index 47906d6..7bf6b98 100644 --- a/projects/ngx-auth/sessions/sessions.component.ts +++ b/projects/ngx-auth/sessions/sessions.component.ts @@ -43,7 +43,7 @@ export class SessionsComponent { protected readonly labels: SessionsLabels = inject(SESSIONS_CONFIG).labels; /** - * What zibri answered the last refused request with, empty while nothing was refused. + * What the api answered the last refused request with, empty while nothing was refused. */ protected readonly errorParagraphs: WritableSignal = signal([]); diff --git a/projects/ngx-auth/sessions/sessions.stories.ts b/projects/ngx-auth/sessions/sessions.stories.ts index 53ad920..6584951 100644 --- a/projects/ngx-auth/sessions/sessions.stories.ts +++ b/projects/ngx-auth/sessions/sessions.stories.ts @@ -17,28 +17,26 @@ const meta: Meta = { applicationConfig({ providers: [ provideRouter([]), + provideHttpClient(withInterceptors([authInterceptor])), + provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }), // zibri, as far as the list gets: this browser and a phone - provideHttpClient(withInterceptors([ - authInterceptor, - HttpTestingUtilities.answerWith({ - 'GET /api/auth/logins': { - status: 200, - body: [ - { - id: 'login-1', - strategy: 'cookie', - current: true, - lastUsedAt: '2026-11-11T10:00:00.000Z', - expiresAt: '2026-12-11T10:00:00.000Z', - userAgent: 'Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0', - ipAddress: '203.0.113.1' - }, - { id: 'login-2', strategy: 'cookie', current: false, expiresAt: '2026-12-01T10:00:00.000Z' } - ] - } - }) - ])), - provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }) + HttpTestingUtilities.provideAnswers({ + 'GET /api/auth/logins': { + status: 200, + body: [ + { + id: 'login-1', + strategy: 'cookie', + current: true, + lastUsedAt: '2026-11-11T10:00:00.000Z', + expiresAt: '2026-12-11T10:00:00.000Z', + userAgent: 'Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0', + ipAddress: '203.0.113.1' + }, + { id: 'login-2', strategy: 'cookie', current: false, expiresAt: '2026-12-01T10:00:00.000Z' } + ] + } + }) ] }) ] diff --git a/projects/ngx-auth/two-factor/two-factor-config.model.ts b/projects/ngx-auth/two-factor/two-factor-config.model.ts index 743e8e1..590a778 100644 --- a/projects/ngx-auth/two-factor/two-factor-config.model.ts +++ b/projects/ngx-auth/two-factor/two-factor-config.model.ts @@ -100,7 +100,7 @@ export type TwoFactorLabels = { */ turnedOff: string, /** - * Shown when a request failed without a message of zibri, like without a connection. + * Shown when a request failed without a message of the api, like without a connection. */ failed: string }; diff --git a/projects/ngx-auth/two-factor/two-factor-dialog.component.ts b/projects/ngx-auth/two-factor/two-factor-dialog.component.ts index 0f15b43..135aac2 100644 --- a/projects/ngx-auth/two-factor/two-factor-dialog.component.ts +++ b/projects/ngx-auth/two-factor/two-factor-dialog.component.ts @@ -40,7 +40,7 @@ export class TwoFactorDialogComponent { protected readonly secondFactorLabels: SecondFactorLabels = inject(SECOND_FACTOR_CONFIG).labels; /** - * What zibri answered a refused request with, empty while nothing was refused. + * What the api answered a refused request with, empty while nothing was refused. */ protected readonly errorParagraphs: WritableSignal = signal([]); @@ -67,7 +67,7 @@ export class TwoFactorDialogComponent { } /** - * Has zibri send the code of a method, like by email. + * Has the api send the code of a method, like by email. * @param request - The method, and whether the user asked for a new code. */ protected async sendCode(request: SecondFactorCodeRequest): Promise { diff --git a/projects/ngx-auth/two-factor/two-factor-dialog.stories.ts b/projects/ngx-auth/two-factor/two-factor-dialog.stories.ts index db876ca..a1658e6 100644 --- a/projects/ngx-auth/two-factor/two-factor-dialog.stories.ts +++ b/projects/ngx-auth/two-factor/two-factor-dialog.stories.ts @@ -38,11 +38,9 @@ const meta: Meta = { applicationConfig({ providers: [ provideRouter([]), - provideHttpClient(withInterceptors([ - authInterceptor, - HttpTestingUtilities.answerWith({ 'POST /api/auth/2fa/request': { status: 204 } }) - ])), - provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }) + provideHttpClient(withInterceptors([authInterceptor])), + provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }), + HttpTestingUtilities.provideAnswers({ 'POST /api/auth/2fa/request': { status: 204 } }) ] }) ], diff --git a/projects/ngx-auth/two-factor/two-factor-enrollment-details.component.ts b/projects/ngx-auth/two-factor/two-factor-enrollment-details.component.ts index 8d5f5c7..f7d779b 100644 --- a/projects/ngx-auth/two-factor/two-factor-enrollment-details.component.ts +++ b/projects/ngx-auth/two-factor/two-factor-enrollment-details.component.ts @@ -40,7 +40,7 @@ export class TwoFactorEnrollmentDetailsComponent { protected readonly labels: TwoFactorLabels = inject(TWO_FACTOR_CONFIG).labels; /** - * What zibri answered when the enrollment started. + * What the api answered when the enrollment started. */ readonly registration: InputSignal = input.required< OtpRegistration | RecoveryCodeRegistration | undefined diff --git a/projects/ngx-auth/two-factor/two-factor-enrollment-step.type.ts b/projects/ngx-auth/two-factor/two-factor-enrollment-step.type.ts index a42ad66..d7e8074 100644 --- a/projects/ngx-auth/two-factor/two-factor-enrollment-step.type.ts +++ b/projects/ngx-auth/two-factor/two-factor-enrollment-step.type.ts @@ -1,5 +1,5 @@ /** - * Where an enrollment stands: asking for the phone number of codes by text message, waiting for zibri, asking for the - * first code, asking the device to create a passkey, or offering to start again after zibri refused to start. + * Where an enrollment stands: asking for the phone number of codes by text message, waiting for the api, asking for + * the first code, asking the device to create a passkey, or offering to start again after the api refused to start. */ export type TwoFactorEnrollmentStep = 'phoneNumber' | 'requesting' | 'confirming' | 'passkey' | 'failed'; \ No newline at end of file diff --git a/projects/ngx-auth/two-factor/two-factor-enrollment.component.ts b/projects/ngx-auth/two-factor/two-factor-enrollment.component.ts index 421ba44..70bd7d7 100644 --- a/projects/ngx-auth/two-factor/two-factor-enrollment.component.ts +++ b/projects/ngx-auth/two-factor/two-factor-enrollment.component.ts @@ -13,7 +13,7 @@ import { TwoFactorEnrollmentResult } from './two-factor-enrollment-result.model' import { TwoFactorEnrollmentStep } from './two-factor-enrollment-step.type'; /** - * What zibri answers when the enrollment of a method starts, which the user is shown. + * What the api answers when the enrollment of a method starts, which the user is shown. */ type TwoFactorRegistration = OtpRegistration | RecoveryCodeRegistration; @@ -87,7 +87,7 @@ export class TwoFactorEnrollmentComponent { protected readonly step: WritableSignal = signal('requesting'); /** - * What zibri answered when the enrollment started, like the qr code of an authenticator app. + * What the api answered when the enrollment started, like the qr code of an authenticator app. */ protected readonly registration: WritableSignal = signal(undefined); @@ -105,7 +105,7 @@ export class TwoFactorEnrollmentComponent { protected readonly code: WritableSignal = signal(''); /** - * What zibri answered the last refused request with, empty while nothing was refused. + * What the api answered the last refused request with, empty while nothing was refused. */ protected readonly errorParagraphs: WritableSignal = signal([]); @@ -122,7 +122,7 @@ export class TwoFactorEnrollmentComponent { }); /** - * Whether zibri sends the code of the method, which the user can have sent again. + * Whether the api sends the code of the method, which the user can have sent again. */ protected readonly sendsCode: Signal = computed(() => this.secondFactorConfig.methods[this.method()]?.sendsCode === true); @@ -201,7 +201,7 @@ export class TwoFactorEnrollmentComponent { } /** - * Starts again after zibri refused to start. + * Starts again after the api refused to start. */ protected begin(): void { if (this.kind() === 'smsCode') { diff --git a/projects/ngx-auth/two-factor/two-factor-enrollment.stories.ts b/projects/ngx-auth/two-factor/two-factor-enrollment.stories.ts index 2f50a79..30138ff 100644 --- a/projects/ngx-auth/two-factor/two-factor-enrollment.stories.ts +++ b/projects/ngx-auth/two-factor/two-factor-enrollment.stories.ts @@ -1,5 +1,5 @@ import { provideHttpClient, withInterceptors } from '@angular/common/http'; -import { EnvironmentProviders, Provider, Service } from '@angular/core'; +import { Provider, Service } from '@angular/core'; import { provideRouter } from '@angular/router'; import { authInterceptor, AuthService, provideAuth } from '@service-soft/ngx-auth/auth'; import { applicationConfig, Meta, StoryObj } from '@storybook/angular'; @@ -14,17 +14,10 @@ class StoryAuthService extends AuthService {} // zibri, as far as an enrollment gets: it starts with what the method of the story answers. function answerRegistrationWith( registration: OtpRegistration | RecoveryCodeRegistration | PublicKeyCredentialCreationOptionsJSON | undefined -): (Provider | EnvironmentProviders)[] { - return [ - provideRouter([]), - provideHttpClient(withInterceptors([ - authInterceptor, - HttpTestingUtilities.answerWith({ - 'POST /api/auth/2fa/registration/request': registration == undefined ? { status: 204 } : { status: 200, body: registration } - }) - ])), - provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }) - ]; +): Provider { + return HttpTestingUtilities.provideAnswers({ + 'POST /api/auth/2fa/registration/request': registration == undefined ? { status: 204 } : { status: 200, body: registration } + }); } const meta: Meta = { @@ -32,10 +25,15 @@ const meta: Meta = { component: TwoFactorEnrollmentComponent, decorators: [ applicationConfig({ - providers: answerRegistrationWith({ - qrCodeUrl: 'otpauth://totp/Example:ada%40example.com?secret=SECRET&issuer=Example', - secret: 'SECRET' - }) + providers: [ + provideRouter([]), + provideHttpClient(withInterceptors([authInterceptor])), + provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }), + answerRegistrationWith({ + qrCodeUrl: 'otpauth://totp/Example:ada%40example.com?secret=SECRET&issuer=Example', + secret: 'SECRET' + }) + ] }) ], args: { method: 'otp' } @@ -48,24 +46,26 @@ export const AuthenticatorApp: Story = {}; export const Email: Story = { args: { method: 'email' }, - decorators: [applicationConfig({ providers: answerRegistrationWith(undefined) })] + decorators: [applicationConfig({ providers: [answerRegistrationWith(undefined)] })] }; export const TextMessage: Story = { args: { method: 'sms' }, - decorators: [applicationConfig({ providers: answerRegistrationWith(undefined) })] + decorators: [applicationConfig({ providers: [answerRegistrationWith(undefined)] })] }; export const Passkey: Story = { args: { method: 'passkey', passkeyName: 'Ada' }, decorators: [ applicationConfig({ - providers: answerRegistrationWith({ - challenge: 'challenge', - rp: { name: 'Example' }, - user: { id: 'user-1', name: 'Ada', displayName: 'Ada' }, - pubKeyCredParams: [{ type: 'public-key', alg: -7 }] - }) + providers: [ + answerRegistrationWith({ + challenge: 'challenge', + rp: { name: 'Example' }, + user: { id: 'user-1', name: 'Ada', displayName: 'Ada' }, + pubKeyCredParams: [{ type: 'public-key', alg: -7 }] + }) + ] }) ] }; @@ -74,7 +74,7 @@ export const RecoveryCodes: Story = { args: { method: 'recovery-code' }, decorators: [ applicationConfig({ - providers: answerRegistrationWith({ codes: ['FIRST-CODE', 'SECOND-CODE', 'THIRD-CODE', 'FOURTH-CODE', 'FIFTH-CODE'] }) + providers: [answerRegistrationWith({ codes: ['FIRST-CODE', 'SECOND-CODE', 'THIRD-CODE', 'FOURTH-CODE', 'FIFTH-CODE'] })] }) ] }; \ No newline at end of file diff --git a/projects/ngx-auth/two-factor/two-factor-settings.component.ts b/projects/ngx-auth/two-factor/two-factor-settings.component.ts index 0966df6..ea8b5bb 100644 --- a/projects/ngx-auth/two-factor/two-factor-settings.component.ts +++ b/projects/ngx-auth/two-factor/two-factor-settings.component.ts @@ -11,9 +11,9 @@ import { TwoFactorMethodAction, TwoFactorMethodRow } from './two-factor-method-r /** * The two factor methods of the logged in user, for the page of their account: which ones are on, setting one up and - * turning one off. To change them, zibri asks for the second factor or a recent login, which the interceptor asks the - * user for with the secondFactorPrompt. Its heading is a h2, below the heading of that page. The methods it offers come - * from provideSecondFactorConfig, its texts from provideTwoFactorConfig. + * turning one off. To change them, the api asks for the second factor or a recent login, which the interceptor asks + * the user for with the secondFactorPrompt. Its heading is a h2, below the heading of that page. The methods it offers + * come from provideSecondFactorConfig, its texts from provideTwoFactorConfig. */ @Component({ selector: 'ngx-two-factor-settings', @@ -46,7 +46,7 @@ export class TwoFactorSettingsComponent { protected readonly labels: TwoFactorLabels = inject(TWO_FACTOR_CONFIG).labels; /** - * What zibri answered the last refused request with, empty while nothing was refused. + * What the api answered the last refused request with, empty while nothing was refused. */ protected readonly errorParagraphs: WritableSignal = signal([]); @@ -56,7 +56,7 @@ export class TwoFactorSettingsComponent { protected readonly status: WritableSignal = signal(''); /** - * The methods, once zibri said which ones the user enrolled. + * The methods, once the api said which ones the user enrolled. */ protected readonly rows: Signal = computed(() => { const enrolledMethods: string[] | undefined = this.enrolledMethods(); diff --git a/projects/ngx-auth/two-factor/two-factor-settings.stories.ts b/projects/ngx-auth/two-factor/two-factor-settings.stories.ts index cd93ecf..1a33c3c 100644 --- a/projects/ngx-auth/two-factor/two-factor-settings.stories.ts +++ b/projects/ngx-auth/two-factor/two-factor-settings.stories.ts @@ -1,5 +1,5 @@ import { provideHttpClient, withInterceptors } from '@angular/common/http'; -import { EnvironmentProviders, Provider, Service } from '@angular/core'; +import { Provider, Service } from '@angular/core'; import { provideRouter } from '@angular/router'; import { authInterceptor, AuthService, provideAuth } from '@service-soft/ngx-auth/auth'; import { applicationConfig, Meta, StoryObj } from '@storybook/angular'; @@ -11,21 +11,23 @@ import { TwoFactorSettingsComponent } from './two-factor-settings.component'; class StoryAuthService extends AuthService {} // zibri, as far as the settings get: the user of the story enrolled these methods. -function answerEnrolledWith(methods: string[]): (Provider | EnvironmentProviders)[] { - return [ - provideRouter([]), - provideHttpClient(withInterceptors([ - authInterceptor, - HttpTestingUtilities.answerWith({ 'GET /api/auth/2fa/registrations': { status: 200, body: { methods } } }) - ])), - provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }) - ]; +function answerEnrolledWith(methods: string[]): Provider { + return HttpTestingUtilities.provideAnswers({ 'GET /api/auth/2fa/registrations': { status: 200, body: { methods } } }); } const meta: Meta = { title: 'Auth/Two factor settings', component: TwoFactorSettingsComponent, - decorators: [applicationConfig({ providers: answerEnrolledWith(['otp', 'recovery-code']) })] + decorators: [ + applicationConfig({ + providers: [ + provideRouter([]), + provideHttpClient(withInterceptors([authInterceptor])), + provideAuth(StoryAuthService, { apiUrl: '/api/auth', strategy: 'cookie' }), + answerEnrolledWith(['otp', 'recovery-code']) + ] + }) + ] }; export default meta; @@ -34,5 +36,5 @@ type Story = StoryObj; export const Default: Story = {}; export const NothingEnrolled: Story = { - decorators: [applicationConfig({ providers: answerEnrolledWith([]) })] + decorators: [applicationConfig({ providers: [answerEnrolledWith([])] })] }; \ No newline at end of file diff --git a/projects/ngx-backup/CHANGELOG.md b/projects/ngx-backup/CHANGELOG.md new file mode 100644 index 0000000..9ecd8c1 --- /dev/null +++ b/projects/ngx-backup/CHANGELOG.md @@ -0,0 +1,11 @@ +# Changelog + +## 22.4.0 + +First release. + +### Features +- `@service-soft/ngx-backup/api`: `BackupTransportsService` and its config. +- `@service-soft/ngx-backup/tenant-transports`: where the backups of a tenant are stored, on S3, SFTP, WebDAV or a + Nextcloud, with a secret that is only written. +- The German translation of the texts ships with the package (`locale/messages.de.xlf`). diff --git a/projects/ngx-backup/LICENSE b/projects/ngx-backup/LICENSE new file mode 100644 index 0000000..959f86e --- /dev/null +++ b/projects/ngx-backup/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Tim Fabian + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/projects/ngx-backup/README.md b/projects/ngx-backup/README.md new file mode 100644 index 0000000..6007073 --- /dev/null +++ b/projects/ngx-backup/README.md @@ -0,0 +1,133 @@ +# ngx-backup +The storage a tenant keeps its backups on: a list of it, and with the permission for it, adding storage, which the api adds once it wrote a small file to it, changing it and its secret, which is never shown again, and removing it after a question that says what happens to the backups on it. A bucket of an S3 compatible storage, an SFTP server, and a folder of a WebDAV server or a Nextcloud, reached through the WebDAV connections of [@service-soft/ngx-web-dav](https://www.npmjs.com/package/@service-soft/ngx-web-dav), each with the fields of its kind. What the api refuses, like a secret the storage refused or backups still stored on it, shows its message. + +It reads and writes through the models of [zibri-contract](https://www.npmjs.com/package/zibri-contract), like `TenantBackupTransportModel`, `NewTenantBackupTransportModel` and `TenantS3TransportSettingsModel`, which any api can answer; the backup transport routes of [zibri](https://www.npmjs.com/package/zibri) are one that does. It is built on [@service-soft/ui](https://www.npmjs.com/package/@service-soft/ui), shows the messages of the api with [@service-soft/ngx-error-handling](https://www.npmjs.com/package/@service-soft/ngx-error-handling), and is styled with Tailwind CSS. + +# Table of Contents +- [ngx-backup](#ngx-backup) +- [Table of Contents](#table-of-contents) +- [Requirements](#requirements) +- [Setup](#setup) +- [The storage of the backups](#the-storage-of-the-backups) + - [The kinds of storage](#the-kinds-of-storage) + - [A kind of your own](#a-kind-of-your-own) +- [The routes of the api](#the-routes-of-the-api) +- [The service](#the-service) +- [Configuration](#configuration) + - [Translating](#translating) +- [License](#license) + +# Requirements +Angular 22 with `@angular/localize`, which [translates the texts](#translating), and Tailwind CSS 4. The inputs of ui need `@angular/aria`: + +```sh +npm install @service-soft/ngx-backup @service-soft/ngx-web-dav @service-soft/ngx-error-handling @service-soft/ui @angular/aria zibri-contract +ng add @angular/localize +``` + +# Setup +Your Tailwind generates the css. Add the packages to your global stylesheet: + +```css +@import "tailwindcss"; +@import "@service-soft/ui"; +@import "@service-soft/ngx-backup"; +``` + +Give it the url of the backup transport routes of your api, and `HttpClient`, which it sends the requests with. A folder of a WebDAV server or a Nextcloud is reached through a WebDAV connection of the tenant, so an app that offers those kinds gives the url of the WebDAV connection routes as well, with `provideWebDavConfig` of `@service-soft/ngx-web-dav/api`: + +```ts +// app.config.ts +import { provideHttpClient } from '@angular/common/http'; +import { provideBackupConfig } from '@service-soft/ngx-backup/api'; +import { provideWebDavConfig } from '@service-soft/ngx-web-dav/api'; + +export const appConfig: ApplicationConfig = { + providers: [ + provideHttpClient(), + provideBackupConfig({ baseUrl: 'https://api.example.com/backup-transports' }), + provideWebDavConfig({ baseUrl: 'https://api.example.com/web-dav-connections' }) + ] +}; +``` + +```ts +// app.routes.ts +export const routes: Routes = [ + { path: 'settings/backups', loadComponent: async () => (await import('@service-soft/ngx-backup/tenant-transports')).TenantTransportsComponent } +]; +``` + +The view is an entry point of its own, so only its page loads its code: `@service-soft/ngx-backup/tenant-transports`. It reads the service and the config of `@service-soft/ngx-backup/api`. + +# The storage of the backups +```html + +``` + +The storage of the tenant by name, each with its kind and its settings in words, like the bucket and the region of a bucket or the connection and the folder of a Nextcloud. The api never answers a secret, so none shows. + +| Input | Values | What it shows | +|---|---|---| +| `canManage` | `boolean` | The forms that add, change and remove storage, like with `backup-transports.manage`. `canManage` of the config by default, `false` | + +With `canManage` a form adds storage: its name, like `Office bucket`, its kind, which the user chooses as nothing is chosen at first, and the fields of that kind. Only the kinds the api offers, `GET /kinds`, that the view knows can be chosen, and a folder of a WebDAV server or a Nextcloud only in an app that gives the url of the WebDAV connections. Without any, the button that adds storage doesn't show. The api tests the storage first, which may take a moment, and adds it once it wrote a small file to it and deleted it again; otherwise the form stays as it was and shows why, like a bucket that refused the access key or an SFTP server that isn't reached. + +The form of a storage changes its name and its settings, and sends only what changed. Its kind never changes. Its secret, like the secret access key of a bucket or the password of an SFTP server, starts empty, as the view never knows it: left empty, the storage keeps the one it has. Changed settings or a new secret are tested again. While backups are stored on it, its settings can't change, as the backups would be lost with them, and the api refuses with the backups it names; its name and its secret can always change. + +Removing storage asks first, and says what happens: the app forgets the storage and its secret, and what is stored on it stays there. While backups are stored on it, the api refuses, and the view shows the backups it names, which are deleted first. + +Screen readers hear what changed. A form takes the focus as it opens, and gives it back to the button that opened it as it closes. + +## The kinds of storage +| Kind | Settings | Secret | +|---|---|---| +| `s3`, an S3 bucket | Endpoint, bucket, region, the folder in the bucket, where the requests name the bucket, the access key ID | The secret access key | +| `sftp`, an SFTP server | Host, port, username, the folder on the server, the fingerprint of the host key | A password, or a private key with its passphrase if it has one | +| `web-dav`, a folder of a WebDAV server | One of the WebDAV connections to a WebDAV server, the folder below it | None: it logs in with the password of the connection | +| `nextcloud`, a folder of a Nextcloud | One of the WebDAV connections to a Nextcloud, the folder below it, the users and the groups of the Nextcloud it is shared with to read | None: it logs in with the password of the connection | + +The connections are those of `WebDavConnectionsService` of `@service-soft/ngx-web-dav/api`, of the server the kind reaches; a connection added in the connections view of ngx-web-dav shows right away. A user who may not list the connections sees a connection by its id. + +## A kind of your own +The api is the same for every kind: settings and a secret, which the api checks against the models of the kind. Storage of a kind the view doesn't know shows its name and its settings as they are, and only its name changes here; it can't be added here. Write the form of your kind against `BackupTransportsService`, and offer it next to the view. + +# The routes of the api +Below the `baseUrl`, each with the tenant permission it needs. Errors are the `ErrorResponseBody` of zibri-contract. + +| Route | Does | Permission | +|---|---|---| +| `GET /` | The storage of the tenant, `TenantBackupTransportModel[]` by name, without secrets | `backup-transports.read` | +| `GET /kinds` | The kinds the tenant may add, `TenantBackupTransportKindModel[]` | `backup-transports.read` | +| `POST /` | Adds a `NewTenantBackupTransportModel` once a small file was written to it and deleted again, and answers the `TenantBackupTransportModel`; `400` with the reason in the `message` of the error when the test failed, `409` for a name that is taken | `backup-transports.manage` | +| `PATCH /:transportId` | Changes storage by a `TenantBackupTransportChangeModel` and answers it; changed settings or a new secret are tested like above, and changed settings are refused with `409` while backups are stored on it | `backup-transports.manage` | +| `DELETE /:transportId` | Removes storage, `204`, and leaves what is stored on it there; `409` while backups are stored on it, which the error names | `backup-transports.manage` | + +The settings of the kinds are `TenantS3TransportSettingsModel`, `TenantSftpTransportSettingsModel`, `TenantWebDavTransportSettingsModel` and `TenantNextcloudTransportSettingsModel`, the secrets `TenantS3TransportSecretModel` and `TenantSftpTransportSecretModel`, the names of the kinds `ZIBRI_BACKUP_TRANSPORT_KINDS`, the lengths the routes take at most `ZIBRI_BACKUP_TRANSPORT_LIMITS` and the permissions `ZIBRI_BACKUP_TRANSPORT_PERMISSIONS`, all of zibri-contract. + +# The service +`BackupTransportsService` of `@service-soft/ngx-backup/api` sends the routes for your own views: `resolveTransports()`, `resolveKinds()`, `createTransport(transport)`, `updateTransport(transportId, change)` and `deleteTransport(transportId)`. Each rejects with the `HttpErrorResponse` of a refused request. + +# Configuration +```ts +provideBackupConfig({ + baseUrl: 'https://api.example.com/backup-transports', + canManage: true, + headingLevel: 1 +}) +``` + +| Value | What it is | Default | +|---|---|---| +| `baseUrl` | The url of the backup transport routes of your api | required | +| `canManage` | See [the storage of the backups](#the-storage-of-the-backups) | `false` | +| `headingLevel` | The level of the heading of the view, the storage and the form one below | `2` | +| `labels` | The texts, by view: `tenantTransports` | English, German ships with it | + +Provide it in the application config, or in a route for only that part of your app. Values you leave out are taken from the parent injector. + +## Translating +Every text is `$localize`. German ships with the library: `locale/messages.de.xlf` of the package has a German target for each, and its `package.json` names it in `"translations"`, so a merge of the translations of an app's dependencies fills them in. Change a text with the `labels` of `provideBackupConfig`, like `{ labels: { tenantTransports: { transports: 'Backups' } } }`. `kinds` names each kind in words and is replaced as a whole, so a kind of your own gets a name by listing it beside those of zibri-contract. + +# License +MIT diff --git a/projects/ngx-backup/api/backup-config-changes.model.ts b/projects/ngx-backup/api/backup-config-changes.model.ts new file mode 100644 index 0000000..03048a6 --- /dev/null +++ b/projects/ngx-backup/api/backup-config-changes.model.ts @@ -0,0 +1,17 @@ +import { BackupConfig } from './backup-config.model'; +import { BackupLabelsChanges } from './backup-labels-changes.model'; + +/** + * The values to change in the config of the backups. Everything is optional, including every single label, but the + * requests need their url once. + */ +export type BackupConfigChanges = Partial> & { + /** + * The url of the backup transport routes of your api, like 'https://api.example.com/backup-transports'. + */ + baseUrl?: string, + /** + * The labels to change, by the view that shows them. + */ + labels?: BackupLabelsChanges +}; diff --git a/projects/ngx-backup/api/backup-config.model.ts b/projects/ngx-backup/api/backup-config.model.ts new file mode 100644 index 0000000..da0be03 --- /dev/null +++ b/projects/ngx-backup/api/backup-config.model.ts @@ -0,0 +1,27 @@ +import { HeadingLevel } from '@service-soft/ui/heading'; + +import { BackupLabels } from './backup-labels.model'; + +/** + * Where the backup transports of the tenant are, and the values their views use. + */ +export type BackupConfig = { + /** + * The url of the backup transport routes of your api, like 'https://api.example.com/backup-transports'. Undefined + * until provideBackupConfig sets it, which every request needs. + */ + baseUrl: string | undefined, + /** + * Whether the user may add, change and remove the storage of the backups, like with `backup-transports.manage`, + * which the view shows its forms by while its `canManage` isn't set. False by default. + */ + canManage: boolean, + /** + * The level of the headings of the views. Their sections are headed one level below. + */ + headingLevel: HeadingLevel, + /** + * The texts of the views. + */ + labels: BackupLabels +}; diff --git a/projects/ngx-backup/api/backup-config.provider.ts b/projects/ngx-backup/api/backup-config.provider.ts new file mode 100644 index 0000000..14386d9 --- /dev/null +++ b/projects/ngx-backup/api/backup-config.provider.ts @@ -0,0 +1,153 @@ +import { inject, InjectionToken, Provider } from '@angular/core'; +import { ZIBRI_BACKUP_TRANSPORT_KINDS } from 'zibri-contract'; + +import { BackupConfigChanges } from './backup-config-changes.model'; +import { BackupConfig } from './backup-config.model'; +import { BackupLabelsChanges } from './backup-labels-changes.model'; +import { BackupLabels } from './backup-labels.model'; + +/** + * The texts of the views when nothing changes them, as $localize, which an app translates like its own. + * @returns The default labels. + */ +function getDefaultBackupLabels(): BackupLabels { + return { + tenantTransports: { + transports: $localize`:@@ngx-backup.api.tenantTransports.transports:Storage of the backups`, + loading: $localize`:@@ngx-backup.api.tenantTransports.loading:Loading`, + loadingFailed: $localize`:@@ngx-backup.api.tenantTransports.loadingFailed:The storage of the backups couldn't be loaded.`, + requestFailed: $localize`:@@ngx-backup.api.tenantTransports.requestFailed:The request couldn't be sent. Please try again.`, + noTransports: $localize`:@@ngx-backup.api.tenantTransports.noTransports:There is no storage for the backups yet.`, + name: $localize`:@@ngx-backup.api.tenantTransports.name:Name`, + nameHint: $localize`:@@ngx-backup.api.tenantTransports.nameHint:What the storage is called, like Office bucket`, + kind: $localize`:@@ngx-backup.api.tenantTransports.kind:Kind`, + chooseKind: $localize`:@@ngx-backup.api.tenantTransports.chooseKind:Choose the kind of storage`, + kinds: { + [ZIBRI_BACKUP_TRANSPORT_KINDS.S3]: $localize`:@@ngx-backup.api.tenantTransports.kinds.s3:S3 bucket`, + [ZIBRI_BACKUP_TRANSPORT_KINDS.SFTP]: $localize`:@@ngx-backup.api.tenantTransports.kinds.sftp:SFTP server`, + [ZIBRI_BACKUP_TRANSPORT_KINDS.WEB_DAV]: $localize`:@@ngx-backup.api.tenantTransports.kinds.web-dav:Folder of a WebDAV server`, + [ZIBRI_BACKUP_TRANSPORT_KINDS.NEXTCLOUD]: $localize`:@@ngx-backup.api.tenantTransports.kinds.nextcloud:Folder of a Nextcloud` + }, + endpoint: $localize`:@@ngx-backup.api.tenantTransports.endpoint:Endpoint`, + endpointHint: $localize`:@@ngx-backup.api.tenantTransports.endpointHint:The address of the storage, like https://s3.eu-central-1.amazonaws.com`, + bucket: $localize`:@@ngx-backup.api.tenantTransports.bucket:Bucket`, + region: $localize`:@@ngx-backup.api.tenantTransports.region:Region`, + regionHint: $localize`:@@ngx-backup.api.tenantTransports.regionHint:Like eu-central-1`, + accessKeyId: $localize`:@@ngx-backup.api.tenantTransports.accessKeyId:Access key ID`, + secretAccessKey: $localize`:@@ngx-backup.api.tenantTransports.secretAccessKey:Secret access key`, + newSecretAccessKey: $localize`:@@ngx-backup.api.tenantTransports.newSecretAccessKey:New secret access key`, + prefix: $localize`:@@ngx-backup.api.tenantTransports.prefix:Folder in the bucket`, + prefixHint: $localize`:@@ngx-backup.api.tenantTransports.prefixHint:The backups go below it. Leave it empty for the top of the bucket`, + topOfBucket: $localize`:@@ngx-backup.api.tenantTransports.topOfBucket:The top of the bucket`, + addressingStyle: $localize`:@@ngx-backup.api.tenantTransports.addressingStyle:Bucket named in`, + addressingStyles: { + 'virtual-hosted': $localize`:@@ngx-backup.api.tenantTransports.addressingStyles.virtual-hosted:The host, like agency-backups.s3.example.com`, + 'path': $localize`:@@ngx-backup.api.tenantTransports.addressingStyles.path:The path, like s3.example.com/agency-backups` + }, + host: $localize`:@@ngx-backup.api.tenantTransports.host:Host`, + port: $localize`:@@ngx-backup.api.tenantTransports.port:Port`, + portHint: $localize`:@@ngx-backup.api.tenantTransports.portHint:Leave it empty for 22`, + defaultPort: $localize`:@@ngx-backup.api.tenantTransports.defaultPort:22`, + username: $localize`:@@ngx-backup.api.tenantTransports.username:Username`, + hostKeyFingerprint: $localize`:@@ngx-backup.api.tenantTransports.hostKeyFingerprint:Fingerprint of the host key`, + hostKeyFingerprintHint: $localize`:@@ngx-backup.api.tenantTransports.hostKeyFingerprintHint:Its SHA256 fingerprint as ssh-keygen -lf prints it, like SHA256:…`, + path: $localize`:@@ngx-backup.api.tenantTransports.path:Folder on the server`, + login: $localize`:@@ngx-backup.api.tenantTransports.login:Log in with`, + logins: { + password: $localize`:@@ngx-backup.api.tenantTransports.logins.password:A password`, + privateKey: $localize`:@@ngx-backup.api.tenantTransports.logins.privateKey:A private key` + }, + keepLogin: $localize`:@@ngx-backup.api.tenantTransports.keepLogin:The login it has`, + password: $localize`:@@ngx-backup.api.tenantTransports.password:Password`, + privateKey: $localize`:@@ngx-backup.api.tenantTransports.privateKey:Private key`, + privateKeyHint: $localize`:@@ngx-backup.api.tenantTransports.privateKeyHint:In OpenSSH format, as it is written in its file`, + passphrase: $localize`:@@ngx-backup.api.tenantTransports.passphrase:Passphrase`, + passphraseHint: $localize`:@@ngx-backup.api.tenantTransports.passphraseHint:Only for a private key that is encrypted with one`, + connection: $localize`:@@ngx-backup.api.tenantTransports.connection:Connection`, + chooseConnection: $localize`:@@ngx-backup.api.tenantTransports.chooseConnection:Choose the connection`, + connectionHint: $localize`:@@ngx-backup.api.tenantTransports.connectionHint:One of the WebDAV connections, whose password it logs in with`, + nextcloudConnectionHint: $localize`:@@ngx-backup.api.tenantTransports.nextcloudConnectionHint:One of the Nextcloud connections, logged in as the user who owns the folder`, + noConnections: $localize`:@@ngx-backup.api.tenantTransports.noConnections:There is no connection to a server of this kind yet. Add one to the WebDAV connections first.`, + folder: $localize`:@@ngx-backup.api.tenantTransports.folder:Folder`, + folderHint: $localize`:@@ngx-backup.api.tenantTransports.folderHint:Relative to the URL of the connection, like Backups. Leave it empty for the folder of the connection`, + nextcloudFolderHint: $localize`:@@ngx-backup.api.tenantTransports.nextcloudFolderHint:Relative to the URL of the connection, like Backups. Only the app writes into it`, + folderOfConnection: $localize`:@@ngx-backup.api.tenantTransports.folderOfConnection:The folder of the connection`, + sharedWithUsers: $localize`:@@ngx-backup.api.tenantTransports.sharedWithUsers:Shared with the users`, + sharedWithGroups: $localize`:@@ngx-backup.api.tenantTransports.sharedWithGroups:Shared with the groups`, + sharedWithHint: $localize`:@@ngx-backup.api.tenantTransports.sharedWithHint:Their IDs in the Nextcloud, each followed by Enter. They read the backups and sync them to their devices`, + nobody: $localize`:@@ngx-backup.api.tenantTransports.nobody:Nobody`, + secretHint: $localize`:@@ngx-backup.api.tenantTransports.secretHint:It is stored and never shown again.`, + keepSecretHint: $localize`:@@ngx-backup.api.tenantTransports.keepSecretHint:Leave it empty to keep the one it has.`, + editHint: $localize`:@@ngx-backup.api.tenantTransports.editHint:While backups are stored on it, only its name and its secret can change.`, + add: $localize`:@@ngx-backup.api.tenantTransports.add:Add storage`, + edit: $localize`:@@ngx-backup.api.tenantTransports.edit:Edit`, + delete: $localize`:@@ngx-backup.api.tenantTransports.delete:Remove`, + save: $localize`:@@ngx-backup.api.tenantTransports.save:Save`, + cancel: $localize`:@@ngx-backup.api.tenantTransports.cancel:Cancel`, + testing: $localize`:@@ngx-backup.api.tenantTransports.testing:Testing the storage…`, + added: name => $localize`:@@ngx-backup.api.tenantTransports.added:The storage ${name}:name: was added.`, + saved: name => $localize`:@@ngx-backup.api.tenantTransports.saved:The storage ${name}:name: was saved.`, + deleted: name => $localize`:@@ngx-backup.api.tenantTransports.deleted:The storage ${name}:name: was removed.`, + deleteQuestion: name => $localize`:@@ngx-backup.api.tenantTransports.deleteQuestion:Remove the storage ${name}:name:?`, + deleteWarning: $localize`:@@ngx-backup.api.tenantTransports.deleteWarning:The app forgets the storage and its secret, and backs up nothing to it anymore. What is stored on it stays there. While backups are stored on it, it can't be removed: delete those backups first.` + } + }; +} + +/** + * The values of the backups when nothing changes them. Their texts are $localize, which an app translates like its + * own, and resolved once the config is injected, so translations an app loads at runtime apply as well. + * @returns The default config. + */ +function getDefaultBackupConfig(): BackupConfig { + return { + baseUrl: undefined, + canManage: false, + headingLevel: 2, + labels: getDefaultBackupLabels() + }; +} + +/** + * Merges the labels to change into the ones of the parent, view by view. + * @param parent - The labels of the parent injector. + * @param changes - The labels to change. + * @returns The merged labels. + */ +function mergeLabels(parent: BackupLabels, changes: BackupLabelsChanges | undefined): BackupLabels { + return { + tenantTransports: { ...parent.tenantTransports, ...changes?.tenantTransports } + }; +} + +/** + * Where the backup transports are, and the values their views use, below this injector. Change them with + * provideBackupConfig. + */ +export const BACKUP_CONFIG: InjectionToken = new InjectionToken( + 'BACKUP_CONFIG', + { providedIn: 'root', factory: () => getDefaultBackupConfig() } +); + +/** + * Sets where the backup transports are, `{ baseUrl }`, and changes the values their views use, like whether the user + * may manage them or the labels to translate them. Provide it in the application config for the whole app, or in a + * component or route for only that part of it. Values you leave out are taken from the parent injector, including + * single labels. + * @param config - The values to change. + * @returns The provider for BACKUP_CONFIG. + */ +export function provideBackupConfig(config: BackupConfigChanges): Provider { + return { + provide: BACKUP_CONFIG, + useFactory: (): BackupConfig => { + const parent: BackupConfig = inject(BACKUP_CONFIG, { skipSelf: true, optional: true }) ?? getDefaultBackupConfig(); + return { + ...parent, + ...config, + baseUrl: config.baseUrl ?? parent.baseUrl, + labels: mergeLabels(parent.labels, config.labels) + }; + } + }; +} diff --git a/projects/ngx-backup/api/backup-labels-changes.model.ts b/projects/ngx-backup/api/backup-labels-changes.model.ts new file mode 100644 index 0000000..866cb49 --- /dev/null +++ b/projects/ngx-backup/api/backup-labels-changes.model.ts @@ -0,0 +1,8 @@ +import { BackupLabels } from './backup-labels.model'; + +/** + * The texts of the views to change, by the view that shows them. Each text left out keeps its default. + */ +export type BackupLabelsChanges = { + [View in keyof BackupLabels]?: Partial +}; diff --git a/projects/ngx-backup/api/backup-labels.model.ts b/projects/ngx-backup/api/backup-labels.model.ts new file mode 100644 index 0000000..fde0826 --- /dev/null +++ b/projects/ngx-backup/api/backup-labels.model.ts @@ -0,0 +1,11 @@ +import { TenantTransportsLabels } from './tenant-transports-labels.model'; + +/** + * The texts of the views of the backups, to translate them, by the view that shows them. + */ +export type BackupLabels = { + /** + * The texts of the storage the tenant keeps its backups on. + */ + tenantTransports: TenantTransportsLabels +}; diff --git a/projects/ngx-backup/api/backup-transports.service.spec.ts b/projects/ngx-backup/api/backup-transports.service.spec.ts new file mode 100644 index 0000000..8468dae --- /dev/null +++ b/projects/ngx-backup/api/backup-transports.service.spec.ts @@ -0,0 +1,117 @@ +import { HttpErrorResponse, provideHttpClient } from '@angular/common/http'; +import { TestBed } from '@angular/core/testing'; +import { beforeEach, describe, expect, test } from 'vitest'; +import { TenantBackupTransportKindModel, TenantBackupTransportModel } from 'zibri-contract'; + +import { BackupTestingUtilities } from '../fixtures/backup-testing.utilities'; +import { BACKUP_TRANSPORT_IDS, BACKUP_TRANSPORT_KINDS, BACKUP_TRANSPORT_SECRET, BACKUP_TRANSPORTS, BACKUP_TRANSPORTS_BASE_URL, BUCKET_BACKUPS, BUCKET_TRANSPORT, OFFICE_SERVER_TRANSPORT } from '../fixtures/backup.fixtures'; +import { FakeBackupTransportsBackend } from '../fixtures/fake-backup-transports-backend.model'; +import { BackupTransportsService } from './backup-transports.service'; + +/** + * Gets what a request rejected with. + * @param request - The request. + * @returns The error of the request. + * @throws {Error} When the request didn't reject. + */ +async function findRefusal(request: Promise): Promise { + try { + await request; + } + catch (error) { + if (error instanceof HttpErrorResponse) { + return error; + } + throw error; + } + throw new Error('The request was not refused.'); +} + +describe('BackupTransportsService', () => { + let backend: FakeBackupTransportsBackend; + let service: BackupTransportsService; + + beforeEach(() => { + backend = new FakeBackupTransportsBackend({ secret: BACKUP_TRANSPORT_SECRET, backups: { [BACKUP_TRANSPORT_IDS.bucket]: BUCKET_BACKUPS } }); + TestBed.configureTestingModule({ providers: BackupTestingUtilities.getProviders(backend) }); + service = TestBed.inject(BackupTransportsService); + }); + + test('loads the storage of the tenant at the baseUrl, without secrets', async () => { + const transports: TenantBackupTransportModel[] = await service.resolveTransports(); + + expect(transports).toEqual(BACKUP_TRANSPORTS); + expect(backend.requests.map(request => `${request.method} ${request.url}`)).toEqual([`GET ${BACKUP_TRANSPORTS_BASE_URL}`]); + }); + + test('loads the kinds the tenant may add', async () => { + const kinds: TenantBackupTransportKindModel[] = await service.resolveKinds(); + + expect(kinds).toEqual(BACKUP_TRANSPORT_KINDS); + expect(backend.requests.map(request => `${request.method} ${request.url}`)).toEqual([`GET ${BACKUP_TRANSPORTS_BASE_URL}/kinds`]); + }); + + test('adds a storage with its secret, and answers it without', async () => { + const created: TenantBackupTransportModel = await service.createTransport({ + name: 'Second bucket', + kind: 's3', + settings: { ...BUCKET_TRANSPORT.settings, bucket: 'agency-copies' }, + secret: { secretAccessKey: BACKUP_TRANSPORT_SECRET } + }); + + expect(created).toMatchObject({ name: 'Second bucket', kind: 's3', settings: { ...BUCKET_TRANSPORT.settings, bucket: 'agency-copies' } }); + expect(Object.keys(created)).not.toContain('secret'); + expect(backend.getSecret(created.id)).toEqual({ secretAccessKey: BACKUP_TRANSPORT_SECRET }); + }); + + test('rejects with the message of the api when the storage refuses the secret', async () => { + const error: HttpErrorResponse = await findRefusal(service.createTransport({ + name: 'Second bucket', + kind: 's3', + settings: BUCKET_TRANSPORT.settings, + secret: { secretAccessKey: 'wrong' } + })); + + expect(error.status).toBe(400); + expect(error.error).toMatchObject({ message: 'The transport Second bucket could not be written to: The storage refused the secret.' }); + expect(backend.getTransports()).toHaveLength(4); + }); + + test('changes a storage at its id, and only what is sent', async () => { + const saved: TenantBackupTransportModel = await service.updateTransport(BACKUP_TRANSPORT_IDS.officeServer, { name: 'Office' }); + + expect(saved).toEqual({ ...OFFICE_SERVER_TRANSPORT, name: 'Office' }); + expect(backend.requests[0]?.method).toBe('PATCH'); + expect(backend.requests[0]?.url).toBe(`${BACKUP_TRANSPORTS_BASE_URL}/${BACKUP_TRANSPORT_IDS.officeServer}`); + expect(backend.requests[0]?.body).toEqual({ name: 'Office' }); + }); + + test('encodes the id of a storage', async () => { + const error: HttpErrorResponse = await findRefusal(service.updateTransport('a/b', { name: 'Office' })); + + expect(error.status).toBe(404); + expect(backend.requests[0]?.url).toBe(`${BACKUP_TRANSPORTS_BASE_URL}/a%2Fb`); + }); + + test('removes a storage', async () => { + await service.deleteTransport(BACKUP_TRANSPORT_IDS.officeServer); + + expect(backend.getTransports().map(transport => transport.id)).not.toContain(BACKUP_TRANSPORT_IDS.officeServer); + }); + + test('rejects removing a storage backups are stored on, with them in the error', async () => { + const error: HttpErrorResponse = await findRefusal(service.deleteTransport(BACKUP_TRANSPORT_IDS.bucket)); + + expect(error.status).toBe(409); + expect(error.error).toMatchObject({ paragraphs: [`The transport is stored on by backups: ${BUCKET_BACKUPS.join(', ')}. Delete those first.`] }); + expect(backend.getTransports()).toHaveLength(4); + }); +}); + +describe('BackupTransportsService without a baseUrl', () => { + test('says how to set the url of the routes', async () => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), new FakeBackupTransportsBackend().provide()] }); + + await expect(TestBed.inject(BackupTransportsService).resolveTransports()).rejects.toThrow('provideBackupConfig({ baseUrl })'); + }); +}); diff --git a/projects/ngx-backup/api/backup-transports.service.ts b/projects/ngx-backup/api/backup-transports.service.ts new file mode 100644 index 0000000..827c84a --- /dev/null +++ b/projects/ngx-backup/api/backup-transports.service.ts @@ -0,0 +1,79 @@ +import { HttpClient } from '@angular/common/http'; +import { inject, Service } from '@angular/core'; +import { firstValueFrom } from 'rxjs'; +import { NewTenantBackupTransportModel, TenantBackupTransportChangeModel, TenantBackupTransportKindModel, TenantBackupTransportModel } from 'zibri-contract'; + +import { BackupConfig } from './backup-config.model'; +import { BACKUP_CONFIG } from './backup-config.provider'; + +/** + * Sends the requests of the backup transport routes at the baseUrl of provideBackupConfig: `GET /` for the storage the + * tenant keeps its backups on, `GET /kinds` for the kinds it may add, `POST /` to add one, `PATCH /:transportId` to + * change one and `DELETE /:transportId` to remove one. It answers the models of zibri-contract, never with a secret. It + * needs HttpClient, from provideHttpClient. + */ +@Service() +export class BackupTransportsService { + /** + * Sends the requests. + */ + protected readonly http: HttpClient = inject(HttpClient); + + private readonly config: BackupConfig = inject(BACKUP_CONFIG); + + /** + * Loads the storage the tenant keeps its backups on. + * @returns The transports, by name, without their secrets. + */ + async resolveTransports(): Promise { + return await firstValueFrom(this.http.get(this.resolveUrl())); + } + + /** + * Loads the kinds of storage the tenant may add, like `s3`. + * @returns The kinds, in the order the api lists them. + */ + async resolveKinds(): Promise { + return await firstValueFrom(this.http.get(`${this.resolveUrl()}/kinds`)); + } + + /** + * Adds a storage, which the api adds once it wrote a small file to it and deleted it again. Rejects with the error of + * the request when the api refuses it, like with 400 for a secret the storage refused or 409 for a name that is + * taken. + * @param transport - The storage, with its secret. + * @returns The storage added, without its secret. + */ + async createTransport(transport: NewTenantBackupTransportModel): Promise { + return await firstValueFrom(this.http.post(this.resolveUrl(), transport)); + } + + /** + * Changes a storage. Changed settings or a new secret are tested by the api first, which rejects with 400 when the + * storage refuses them, and with 409 for changed settings while backups are stored on it. + * @param transportId - Its id. + * @param change - What changes, each value left out stays. + * @returns The storage changed, without its secret. + */ + async updateTransport(transportId: string, change: TenantBackupTransportChangeModel): Promise { + return await firstValueFrom(this.http.patch(this.resolveUrl(transportId), change)); + } + + /** + * Removes a storage, and leaves what is stored on it there. Rejects with 409 while backups are stored on it, whose + * error names them. + * @param transportId - Its id. + */ + async deleteTransport(transportId: string): Promise { + await firstValueFrom(this.http.delete(this.resolveUrl(transportId))); + } + + private resolveUrl(transportId?: string): string { + const base: string | undefined = this.config.baseUrl; + if (base == undefined) { + throw new Error('The BackupTransportsService needs the url of the backup transport routes of your api. ' + + 'Add provideBackupConfig({ baseUrl }) to the providers of your app.'); + } + return transportId == undefined ? base : `${base}/${encodeURIComponent(transportId)}`; + } +} diff --git a/projects/ngx-backup/api/ng-package.json b/projects/ngx-backup/api/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-backup/api/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-backup/api/public-api.ts b/projects/ngx-backup/api/public-api.ts new file mode 100644 index 0000000..76f6c94 --- /dev/null +++ b/projects/ngx-backup/api/public-api.ts @@ -0,0 +1,8 @@ +export * from './backup-config-changes.model'; +export * from './backup-config.model'; +export * from './backup-config.provider'; +export * from './backup-labels-changes.model'; +export * from './backup-labels.model'; +export * from './backup-transports.service'; +export * from './sftp-login.type'; +export * from './tenant-transports-labels.model'; diff --git a/projects/ngx-backup/api/sftp-login.type.ts b/projects/ngx-backup/api/sftp-login.type.ts new file mode 100644 index 0000000..9b20c74 --- /dev/null +++ b/projects/ngx-backup/api/sftp-login.type.ts @@ -0,0 +1,4 @@ +/** + * What the user logs in to an SFTP server with: a password, or a private key. + */ +export type SftpLogin = 'password' | 'privateKey'; diff --git a/projects/ngx-backup/api/tenant-transports-labels.model.ts b/projects/ngx-backup/api/tenant-transports-labels.model.ts new file mode 100644 index 0000000..6e83ec8 --- /dev/null +++ b/projects/ngx-backup/api/tenant-transports-labels.model.ts @@ -0,0 +1,273 @@ +import { S3AddressingStyle } from 'zibri-contract'; + +import { SftpLogin } from './sftp-login.type'; + +/** + * The texts of the storage the tenant keeps its backups on, to translate them. + */ +export type TenantTransportsLabels = { + /** + * The heading of the view. + */ + transports: string, + /** + * What screen readers read while the storage loads. + */ + loading: string, + /** + * What the view says when the storage couldn't be loaded. + */ + loadingFailed: string, + /** + * What the view says when a request was refused without a message of the server, like without a connection. + */ + requestFailed: string, + /** + * What the view says when there is no storage. + */ + noTransports: string, + /** + * The name of a storage. + */ + name: string, + /** + * The hint of the name. + */ + nameHint: string, + /** + * What kind of storage it is. + */ + kind: string, + /** + * What the kind shows while none is chosen. + */ + chooseKind: string, + /** + * Each kind the view knows in words, by its name, like `s3`. A kind without a text shows its name. + */ + kinds: Record, + /** + * The address of the storage of a bucket. + */ + endpoint: string, + /** + * The hint of the endpoint. + */ + endpointHint: string, + /** + * The bucket. + */ + bucket: string, + /** + * The region of the bucket. + */ + region: string, + /** + * The hint of the region. + */ + regionHint: string, + /** + * The id of the access key of a bucket. + */ + accessKeyId: string, + /** + * The secret of the access key. + */ + secretAccessKey: string, + /** + * The new secret of the access key, in the form changing a bucket. + */ + newSecretAccessKey: string, + /** + * The folder in the bucket the backups go below. + */ + prefix: string, + /** + * The hint of the folder in the bucket. + */ + prefixHint: string, + /** + * What shows for a bucket whose backups go to its top. + */ + topOfBucket: string, + /** + * Where the requests name the bucket. + */ + addressingStyle: string, + /** + * Each place the requests name the bucket in, in words. + */ + addressingStyles: Record, + /** + * The host of an SFTP server. + */ + host: string, + /** + * The port of the server. + */ + port: string, + /** + * The hint of the port. + */ + portHint: string, + /** + * What shows for a server without a port of its own. + */ + defaultPort: string, + /** + * The user that logs in. + */ + username: string, + /** + * The fingerprint of the host key of the server. + */ + hostKeyFingerprint: string, + /** + * The hint of the fingerprint. + */ + hostKeyFingerprintHint: string, + /** + * The folder on the server the backups go into. + */ + path: string, + /** + * What the user logs in to the server with. + */ + login: string, + /** + * Each way of logging in, in words. + */ + logins: Record, + /** + * The choice of the form changing a server that keeps the login it has. + */ + keepLogin: string, + /** + * The password of the user. + */ + password: string, + /** + * The private key of the user. + */ + privateKey: string, + /** + * The hint of the private key. + */ + privateKeyHint: string, + /** + * The passphrase of the private key. + */ + passphrase: string, + /** + * The hint of the passphrase. + */ + passphraseHint: string, + /** + * The WebDAV connection a folder is reached through. + */ + connection: string, + /** + * What the connection shows while none is chosen. + */ + chooseConnection: string, + /** + * The hint of the connection of a folder of a WebDAV server. + */ + connectionHint: string, + /** + * The hint of the connection of a folder of a Nextcloud. + */ + nextcloudConnectionHint: string, + /** + * The hint of the connection when the tenant has no connection of the kind. + */ + noConnections: string, + /** + * The folder the backups are kept in. + */ + folder: string, + /** + * The hint of the folder of a WebDAV server. + */ + folderHint: string, + /** + * The hint of the folder of a Nextcloud. + */ + nextcloudFolderHint: string, + /** + * What shows for backups kept in the folder of the connection itself. + */ + folderOfConnection: string, + /** + * The users of the Nextcloud the folder is shared with, to read. + */ + sharedWithUsers: string, + /** + * The groups of the Nextcloud the folder is shared with, to read. + */ + sharedWithGroups: string, + /** + * The hint of the users and the groups. + */ + sharedWithHint: string, + /** + * What shows for a folder shared with no user or no group. + */ + nobody: string, + /** + * The hint of a secret in the form adding a storage. + */ + secretHint: string, + /** + * The hint of a secret in the form changing a storage. + */ + keepSecretHint: string, + /** + * The hint of the form changing a storage. + */ + editHint: string, + /** + * The button that opens the form adding a storage, and its heading. + */ + add: string, + /** + * The button that opens the form changing a storage. + */ + edit: string, + /** + * The button that removes a storage. + */ + delete: string, + /** + * The button that saves a form. + */ + save: string, + /** + * The button that closes a form or the question without doing anything. + */ + cancel: string, + /** + * What shows while the api tests a storage, which may take a moment. + */ + testing: string, + /** + * What screen readers hear once a storage was added, from its name. + */ + added: (name: string) => string, + /** + * What screen readers hear once a storage was changed, from its name. + */ + saved: (name: string) => string, + /** + * What screen readers hear once a storage was removed, from its name. + */ + deleted: (name: string) => string, + /** + * The question before a storage is removed, from its name. + */ + deleteQuestion: (name: string) => string, + /** + * What removing a storage does, and what happens to the backups on it. + */ + deleteWarning: string +}; diff --git a/projects/ngx-backup/fixtures/backup-story.utilities.ts b/projects/ngx-backup/fixtures/backup-story.utilities.ts new file mode 100644 index 0000000..f2e98af --- /dev/null +++ b/projects/ngx-backup/fixtures/backup-story.utilities.ts @@ -0,0 +1,61 @@ +import { HttpBackend, provideHttpClient } from '@angular/common/http'; +import { Provider } from '@angular/core'; +import { BackupConfigChanges, provideBackupConfig } from '@service-soft/ngx-backup/api'; +import { provideWebDavConfig } from '@service-soft/ngx-web-dav/api'; +import { applicationConfig } from '@storybook/angular'; +import { NEVER } from 'rxjs'; +import { HttpTestingUtilities } from 'testing/http'; + +import { BACKUP_TRANSPORTS_BASE_URL } from './backup.fixtures'; +import { FakeBackupTransportsBackendOptions } from './fake-backup-transports-backend-options.model'; +import { FakeBackupTransportsBackend } from './fake-backup-transports-backend.model'; +import { FakeWebDavConnectionsBackend } from '../../ngx-web-dav/fixtures/fake-web-dav-connections-backend.model'; +import { WEB_DAV_CONNECTIONS_BASE_URL } from '../../ngx-web-dav/fixtures/web-dav.fixtures'; + +/** + * What a story of the backup transports renders against: the options of its fake backend, and its config. + */ +export type BackupStoryBackend = FakeBackupTransportsBackendOptions & { + /** + * The config of the story beside the url. + */ + config?: BackupConfigChanges, + /** + * Whether the backend never answers, so the story shows what loads. + */ + loading?: boolean +}; + +/** + * Utilities for the stories of the backup transports, which render them against a FakeBackupTransportsBackend and the + * WebDAV connections of the fixtures of ngx-web-dav. + */ +export abstract class BackupStoryUtilities { + /** + * Provides a backend answering like the backup transport routes and the WebDAV connection routes would, and the + * configs with their urls. + * @param backend - The fake backend and the config of the story. + * @returns The decorator of the story. + */ + static provideBackend(backend: BackupStoryBackend = {}): ReturnType { + const { config, loading, ...options } = backend; + const transports: FakeBackupTransportsBackend = new FakeBackupTransportsBackend(options); + const webDav: FakeWebDavConnectionsBackend = new FakeWebDavConnectionsBackend(); + return applicationConfig({ + providers: [ + provideHttpClient(), + loading === true + ? this.provideSilentBackend() + : HttpTestingUtilities.provideBackend(request => transports.findAnswer(request) ?? webDav.findAnswer(request)), + provideBackupConfig({ baseUrl: options.baseUrl ?? BACKUP_TRANSPORTS_BASE_URL, ...config }), + provideWebDavConfig({ baseUrl: WEB_DAV_CONNECTIONS_BASE_URL }) + ] + }); + } + + // a request that never ends, which HttpTestingUtilities has no answer for + private static provideSilentBackend(): Provider { + const backend: HttpBackend = { handle: () => NEVER }; + return { provide: HttpBackend, useValue: backend }; + } +} diff --git a/projects/ngx-backup/fixtures/backup-testing.utilities.ts b/projects/ngx-backup/fixtures/backup-testing.utilities.ts new file mode 100644 index 0000000..3bc7259 --- /dev/null +++ b/projects/ngx-backup/fixtures/backup-testing.utilities.ts @@ -0,0 +1,117 @@ +import { provideHttpClient } from '@angular/common/http'; +import { EnvironmentProviders, Provider } from '@angular/core'; +import { ComponentFixture } from '@angular/core/testing'; +import { BackupConfigChanges, provideBackupConfig } from '@service-soft/ngx-backup/api'; +import { provideWebDavConfig } from '@service-soft/ngx-web-dav/api'; +import { HttpTestingUtilities } from 'testing/http'; + +import { BACKUP_TRANSPORTS_BASE_URL } from './backup.fixtures'; +import { FakeBackupTransportsBackend } from './fake-backup-transports-backend.model'; +import { FakeWebDavConnectionsBackend } from '../../ngx-web-dav/fixtures/fake-web-dav-connections-backend.model'; +import { WEB_DAV_CONNECTIONS_BASE_URL } from '../../ngx-web-dav/fixtures/web-dav.fixtures'; + +/** + * Utilities for the specs of the backup transports, which render them against a FakeBackupTransportsBackend, and the + * WebDAV connections of the fixtures of ngx-web-dav. + */ +export abstract class BackupTestingUtilities { + /** + * Gets the providers of a spec: HttpClient on the fake backends, and the configs with their urls. + * @param backend - The fake backend of the spec. + * @param config - The config beside the url. + * @param webDav - The fake WebDAV connections, those of the fixtures by default. + * @returns The providers. + */ + static getProviders( + backend: FakeBackupTransportsBackend, + config: BackupConfigChanges = {}, + webDav: FakeWebDavConnectionsBackend = new FakeWebDavConnectionsBackend() + ): (Provider | EnvironmentProviders)[] { + return [ + provideHttpClient(), + HttpTestingUtilities.provideBackend(request => backend.findAnswer(request) ?? webDav.findAnswer(request)), + provideBackupConfig({ baseUrl: BACKUP_TRANSPORTS_BASE_URL, ...config }), + provideWebDavConfig({ baseUrl: WEB_DAV_CONNECTIONS_BASE_URL }) + ]; + } + + /** + * Renders what changed once the requests it sent were answered, which the fake backend does right away. + * @param fixture - The fixture. + */ + static async render(fixture: ComponentFixture): Promise { + fixture.detectChanges(); + await fixture.whenStable(); + // the focus moves after the next render + await new Promise(resolve => setTimeout(resolve)); + await fixture.whenStable(); + } + + /** + * Gets the texts of an element one after the other, as a screen reader reads them. + * @param element - The element, or null. + * @returns The texts, separated by single spaces. + */ + static getText(element: Element | null | undefined): string { + if (element == undefined) { + return ''; + } + // text node by text node: angular drops the whitespace between elements, which textContent would then join + const walker: TreeWalker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT); + const texts: string[] = []; + while (walker.nextNode()) { + texts.push(walker.currentNode.textContent ?? ''); + } + return texts.join(' ').replaceAll(/\s+/g, ' ') + .trim(); + } + + /** + * Chooses an option of a select by its text, through the native select, like an autofill does. + * @param root - The element the select is in. + * @param name - The name of the select. + * @param text - The text of the option. + * @throws {Error} When there is no such select or option. + */ + static choose(root: ParentNode, name: string, text: string): void { + const select: HTMLSelectElement | null = root.querySelector(`select[name="${name}"]`); + const option: HTMLOptionElement | undefined = [...select?.options ?? []].find(candidate => candidate.textContent.trim() === text); + if (select == undefined || option == undefined) { + throw new Error(`There is no option "${text}" of the select "${name}".`); + } + select.value = option.value; + select.dispatchEvent(new Event('change')); + } + + /** + * Types a value into a textarea, which fires its input event like typing does. + * @param root - The element the textarea is in. + * @param name - The name of the textarea. + * @param value - The value to type. + * @throws {Error} When there is no such textarea. + */ + static typeText(root: ParentNode, name: string, value: string): void { + const textarea: HTMLTextAreaElement | null = root.querySelector(`textarea[name="${name}"]`); + if (textarea == undefined) { + throw new Error(`There is no textarea named "${name}".`); + } + textarea.value = value; + textarea.dispatchEvent(new Event('input')); + } + + /** + * Finds a button by its text. + * @param root - The element the button is in. + * @param text - Its text. + * @returns The button. + * @throws {Error} When there is none. + */ + static findButton(root: ParentNode, text: string): HTMLButtonElement { + const button: HTMLButtonElement | undefined = [...root.querySelectorAll('button')] + .find(candidate => candidate.textContent.trim() === text); + if (button == undefined) { + throw new Error(`There is no button "${text}".`); + } + return button; + } +} diff --git a/projects/ngx-backup/fixtures/backup.fixtures.ts b/projects/ngx-backup/fixtures/backup.fixtures.ts new file mode 100644 index 0000000..83e229c --- /dev/null +++ b/projects/ngx-backup/fixtures/backup.fixtures.ts @@ -0,0 +1,123 @@ +import { TenantBackupTransportKindModel, TenantBackupTransportModel, ZIBRI_BACKUP_TRANSPORT_KINDS } from 'zibri-contract'; + +import { WEB_DAV_IDS, WEB_DAV_TENANT_ID } from '../../ngx-web-dav/fixtures/web-dav.fixtures'; + +// The storage a small agency keeps its backups on, as the backup transport routes of zibri answer it: a bucket, an SFTP +// server of its archive, and folders of its Nextcloud and of its office server, through the WebDAV connections of the +// fixtures of ngx-web-dav. + +/** + * The url the specs and stories have the backup transport routes at. + */ +export const BACKUP_TRANSPORTS_BASE_URL: string = '/api/backup-transports'; + +/** + * The ids of the transports, by what they are. + */ +export const BACKUP_TRANSPORT_IDS: Record<'bucket' | 'archive' | 'nextcloud' | 'officeServer' | 'tape', string> = { + bucket: 'c8000000-0000-4000-8000-000000000001', + archive: 'c8000000-0000-4000-8000-000000000002', + nextcloud: 'c8000000-0000-4000-8000-000000000003', + officeServer: 'c8000000-0000-4000-8000-000000000004', + tape: 'c8000000-0000-4000-8000-000000000005' +}; + +/** + * The only secret the storages of the fixtures accept, as the secret access key of the bucket and the password of the + * SFTP server. + */ +export const BACKUP_TRANSPORT_SECRET: string = 'storage-secret'; + +/** + * The bucket of the agency. + */ +export const BUCKET_TRANSPORT: TenantBackupTransportModel = { + id: BACKUP_TRANSPORT_IDS.bucket, + tenantId: WEB_DAV_TENANT_ID, + name: 'Office bucket', + kind: ZIBRI_BACKUP_TRANSPORT_KINDS.S3, + settings: { + endpoint: 'https://s3.eu-central-1.amazonaws.com', + bucket: 'agency-backups', + region: 'eu-central-1', + accessKeyId: 'AKIAIOSFODNN7EXAMPLE', + prefix: 'nightly', + addressingStyle: 'virtual-hosted' + } +}; + +/** + * The SFTP server of the archive of the agency. + */ +export const ARCHIVE_TRANSPORT: TenantBackupTransportModel = { + id: BACKUP_TRANSPORT_IDS.archive, + tenantId: WEB_DAV_TENANT_ID, + name: 'Archive server', + kind: ZIBRI_BACKUP_TRANSPORT_KINDS.SFTP, + settings: { + host: 'archive.example.com', + port: 2222, + username: 'backup', + hostKeyFingerprint: 'SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8', + path: '/srv/backups/agency' + } +}; + +/** + * The folder of the Nextcloud of the agency, which Ada and the management read on their devices. + */ +export const NEXTCLOUD_TRANSPORT: TenantBackupTransportModel = { + id: BACKUP_TRANSPORT_IDS.nextcloud, + tenantId: WEB_DAV_TENANT_ID, + name: 'Nextcloud', + kind: ZIBRI_BACKUP_TRANSPORT_KINDS.NEXTCLOUD, + settings: { + connectionId: WEB_DAV_IDS.nextcloud, + folder: 'Backups', + sharedWithUsers: ['ada'], + sharedWithGroups: ['management'] + } +}; + +/** + * The folder of the connection to the office server. + */ +export const OFFICE_SERVER_TRANSPORT: TenantBackupTransportModel = { + id: BACKUP_TRANSPORT_IDS.officeServer, + tenantId: WEB_DAV_TENANT_ID, + name: 'Office server', + kind: ZIBRI_BACKUP_TRANSPORT_KINDS.WEB_DAV, + settings: { + connectionId: WEB_DAV_IDS.officeServer, + folder: '' + } +}; + +/** + * A tape library, of a kind of storage the app offers that the view doesn't know. + */ +export const TAPE_TRANSPORT: TenantBackupTransportModel = { + id: BACKUP_TRANSPORT_IDS.tape, + tenantId: WEB_DAV_TENANT_ID, + name: 'Tape library', + kind: 'tape', + settings: { + library: 'LTO-9 in the basement', + slots: [4, 5] + } +}; + +/** + * The storage of the tenant, by name. + */ +export const BACKUP_TRANSPORTS: TenantBackupTransportModel[] = [ARCHIVE_TRANSPORT, NEXTCLOUD_TRANSPORT, BUCKET_TRANSPORT, OFFICE_SERVER_TRANSPORT]; + +/** + * The kinds of storage the app offers, every kind zibri ships. + */ +export const BACKUP_TRANSPORT_KINDS: TenantBackupTransportKindModel[] = Object.values(ZIBRI_BACKUP_TRANSPORT_KINDS).map(name => ({ name })); + +/** + * The backups stored on the bucket, which keep it from being removed. + */ +export const BUCKET_BACKUPS: string[] = ['nightly-2026-11-25', 'nightly-2026-11-26']; diff --git a/projects/ngx-backup/fixtures/fake-backup-transports-backend-options.model.ts b/projects/ngx-backup/fixtures/fake-backup-transports-backend-options.model.ts new file mode 100644 index 0000000..a51ce1c --- /dev/null +++ b/projects/ngx-backup/fixtures/fake-backup-transports-backend-options.model.ts @@ -0,0 +1,32 @@ +import { TenantBackupTransportKindModel, TenantBackupTransportModel } from 'zibri-contract'; + +/** + * How a FakeBackupTransportsBackend answers. + */ +export type FakeBackupTransportsBackendOptions = { + /** + * The url it has the routes at, BACKUP_TRANSPORTS_BASE_URL by default. + */ + baseUrl?: string, + /** + * The transports it starts with, BACKUP_TRANSPORTS by default. They log in with BACKUP_TRANSPORT_SECRET. + */ + transports?: TenantBackupTransportModel[], + /** + * The kinds the app lets the tenant add, BACKUP_TRANSPORT_KINDS by default. + */ + kinds?: TenantBackupTransportKindModel[], + /** + * The only secret the storages accept, like BACKUP_TRANSPORT_SECRET: a test of a bucket or an SFTP server with any + * other is refused with 400, like by a storage that refused the login. Every secret is accepted by default. + */ + secret?: string, + /** + * The backups stored on each transport, by its id. Removing it or changing its settings is refused with 409. + */ + backups?: Record, + /** + * Whether it answers every request with 503, like an api that is down. + */ + unavailable?: boolean +}; diff --git a/projects/ngx-backup/fixtures/fake-backup-transports-backend.model.ts b/projects/ngx-backup/fixtures/fake-backup-transports-backend.model.ts new file mode 100644 index 0000000..f17ac8b --- /dev/null +++ b/projects/ngx-backup/fixtures/fake-backup-transports-backend.model.ts @@ -0,0 +1,297 @@ +import { HttpRequest } from '@angular/common/http'; +import { Provider } from '@angular/core'; +import { FakeAnswer, HttpTestingUtilities } from 'testing/http'; +import { ErrorResponseBody, TenantBackupTransportKindModel, TenantBackupTransportModel, ZIBRI_BACKUP_TRANSPORT_KINDS } from 'zibri-contract'; + +import { BACKUP_TRANSPORT_KINDS, BACKUP_TRANSPORT_SECRET, BACKUP_TRANSPORTS, BACKUP_TRANSPORTS_BASE_URL } from './backup.fixtures'; +import { FakeBackupTransportsBackendOptions } from './fake-backup-transports-backend-options.model'; +import { WEB_DAV_TENANT_ID } from '../../ngx-web-dav/fixtures/web-dav.fixtures'; + +/** + * A transport as the fake keeps it, with the secret it logs in with. + */ +type FakeStoredTransport = TenantBackupTransportModel & { + /** + * The secret, which is never answered. + */ + secret: Record +}; + +/** + * What a request to add or change a transport sent, as the api reads it. + */ +type FakeTransportBody = { + /** + * The name, if it is a string. + */ + name: string | undefined, + /** + * The kind, if it is a string. + */ + kind: string | undefined, + /** + * The settings, if they are an object. + */ + settings: Record | undefined, + /** + * The secret, if it is an object. + */ + secret: Record | undefined +}; + +/** + * The backup transport routes of an api for the specs and stories, which keeps the transports in memory and answers + * like the routes in the README of this library: it lists the transports by name and the kinds of the options, and + * tests a transport before it adds it or changes its settings or secret, which refuses a kind the options don't offer, + * a transport without a connection or a secret, and a secret other than the one of the options with 400, and a name + * that is taken with 409. Removing a transport, or changing its settings, while backups are stored on it is refused with + * 409 as well. + * + * Provide it as the backend of the HttpClient with provide, after provideHttpClient. Beside other fakes, like the + * WebDAV connections of ngx-web-dav, hand its findAnswer to the backend of HttpTestingUtilities first. + */ +export class FakeBackupTransportsBackend { + /** + * Every request it answered, in order, to check what was sent. + */ + readonly requests: HttpRequest[] = []; + + private readonly baseUrl: string; + + private readonly kinds: TenantBackupTransportKindModel[]; + + private readonly secret: string | undefined; + + private readonly backups: Record; + + private readonly unavailable: boolean; + + private stored: FakeStoredTransport[]; + + private nextId: number = 1; + + constructor(options: FakeBackupTransportsBackendOptions = {}) { + this.baseUrl = new URL(options.baseUrl ?? BACKUP_TRANSPORTS_BASE_URL, document.baseURI).pathname; + this.kinds = options.kinds ?? BACKUP_TRANSPORT_KINDS; + this.secret = options.secret; + this.backups = options.backups ?? {}; + this.unavailable = options.unavailable ?? false; + this.stored = (options.transports ?? BACKUP_TRANSPORTS).map(transport => ({ + ...transport, + secret: FakeBackupTransportsBackend.resolveFixtureSecret(transport.kind) + })); + } + + /** + * Gets the transports it has now, by name, as the api answers them. + * @returns The transports, without their secrets. + */ + getTransports(): TenantBackupTransportModel[] { + return this.stored + .map(transport => FakeBackupTransportsBackend.toModel(transport)) + .sort((a, b) => a.name.localeCompare(b.name)); + } + + /** + * Gets the secret a transport logs in with now, which the api never answers. + * @param transportId - The id of the transport. + * @returns The secret, or undefined for no such transport. + */ + getSecret(transportId: string): Record | undefined { + return this.stored.find(transport => transport.id === transportId)?.secret; + } + + /** + * Answers a request to the routes, and changes the transports like the api would. + * @param request - The request. + * @returns The answer, or undefined for a request to another url. + */ + findAnswer(request: HttpRequest): FakeAnswer | undefined { + const path: string = new URL(request.url, document.baseURI).pathname; + if (path !== this.baseUrl && !path.startsWith(`${this.baseUrl}/`)) { + return undefined; + } + this.requests.push(request); + if (this.unavailable) { + return { status: 503 }; + } + if (path === this.baseUrl) { + switch (request.method) { + case 'GET': { + return { status: 200, body: this.getTransports() }; + } + case 'POST': { + return this.create(FakeBackupTransportsBackend.readBody(request.body)); + } + default: { + return FakeBackupTransportsBackend.refuse(404, 'NotFoundError', [`There is no route ${request.method} ${path}.`]); + } + } + } + if (path === `${this.baseUrl}/kinds` && request.method === 'GET') { + return { status: 200, body: this.kinds }; + } + const transportId: string = decodeURIComponent(path.slice(this.baseUrl.length + 1)); + const stored: FakeStoredTransport | undefined = this.stored.find(transport => transport.id === transportId); + if (stored == undefined) { + return FakeBackupTransportsBackend.refuse(404, 'NotFoundError', [`There is no backup transport ${transportId}.`]); + } + switch (request.method) { + case 'PATCH': { + return this.update(stored, FakeBackupTransportsBackend.readBody(request.body)); + } + case 'DELETE': { + return this.delete(stored); + } + default: { + return FakeBackupTransportsBackend.refuse(404, 'NotFoundError', [`There is no route ${request.method} ${path}.`]); + } + } + } + + /** + * Provides it as the backend of the HttpClient, which answers right away. A request to another url fails with 404. + * @returns The provider, after provideHttpClient. + */ + provide(): Provider { + return HttpTestingUtilities.provideBackend(request => this.findAnswer(request)); + } + + private create(body: FakeTransportBody): FakeAnswer { + if (body.kind == undefined || !this.kinds.some(kind => kind.name === body.kind)) { + return FakeBackupTransportsBackend.refuse(400, 'BadRequestError', [ + `A transport needs to be one of ${this.kinds.map(kind => kind.name).join(', ')}.` + ]); + } + const transport: FakeStoredTransport = { + // apart from the ids of the fixtures, which start with c8 + id: `c9000000-0000-4000-8000-${String(this.nextId++).padStart(12, '0')}`, + tenantId: WEB_DAV_TENANT_ID, + name: body.name ?? '', + kind: body.kind, + settings: body.settings ?? {}, + secret: body.secret ?? {} + }; + const refusal: FakeAnswer | undefined = this.findTestRefusal(transport) ?? this.findNameRefusal(transport); + if (refusal != undefined) { + return refusal; + } + this.stored.push(transport); + return { status: 200, body: FakeBackupTransportsBackend.toModel(transport) }; + } + + private update(stored: FakeStoredTransport, body: FakeTransportBody): FakeAnswer { + const changed: FakeStoredTransport = { + ...stored, + name: body.name ?? stored.name, + settings: body.settings ?? stored.settings, + secret: body.secret ?? stored.secret + }; + const backups: string[] = this.backups[stored.id] ?? []; + // like the api: the backups stored on it are where its settings lead, so they can't change while there are any + if (body.settings != undefined && backups.length) { + return FakeBackupTransportsBackend.refuse(409, 'ConflictError', [ + `The settings of the transport are kept while backups are stored on it: ${backups.join(', ')}. Delete those first.` + ]); + } + const tested: boolean = body.settings != undefined || body.secret != undefined; + const refusal: FakeAnswer | undefined = (tested ? this.findTestRefusal(changed) : undefined) ?? this.findNameRefusal(changed); + if (refusal != undefined) { + return refusal; + } + this.stored = this.stored.map(transport => transport.id === stored.id ? changed : transport); + return { status: 200, body: FakeBackupTransportsBackend.toModel(changed) }; + } + + private delete(stored: FakeStoredTransport): FakeAnswer { + const backups: string[] = this.backups[stored.id] ?? []; + if (backups.length) { + return FakeBackupTransportsBackend.refuse(409, 'ConflictError', [ + `The transport is stored on by backups: ${backups.join(', ')}. Delete those first.` + ]); + } + this.stored = this.stored.filter(transport => transport.id !== stored.id); + return { status: 204 }; + } + + // the test of the api: what the kind needs, then writing a small file with the secret + private findTestRefusal(transport: FakeStoredTransport): FakeAnswer | undefined { + const secret: unknown = this.resolveLogin(transport); + if (transport.kind === ZIBRI_BACKUP_TRANSPORT_KINDS.SFTP && (transport.secret['password'] == undefined) === (transport.secret['privateKey'] == undefined)) { + return FakeBackupTransportsBackend.refuse(400, 'BadRequestError', [ + 'The secret of an SFTP server needs to be a password or a private key, exactly one of them.' + ]); + } + if ((transport.kind === ZIBRI_BACKUP_TRANSPORT_KINDS.WEB_DAV || transport.kind === ZIBRI_BACKUP_TRANSPORT_KINDS.NEXTCLOUD) + && typeof transport.settings['connectionId'] !== 'string') { + return FakeBackupTransportsBackend.refuse(400, 'ValidationError', ['connectionId is required']); + } + if (this.secret != undefined && secret !== undefined && secret !== this.secret) { + return FakeBackupTransportsBackend.refuse(400, 'BadRequestError', [ + `The transport ${transport.name} could not be written to: The storage refused the secret.` + ]); + } + return undefined; + } + + // what logs in of the secret of a bucket or an SFTP server, undefined for a kind whose secret is the connection's + private resolveLogin(transport: FakeStoredTransport): unknown { + switch (transport.kind) { + case ZIBRI_BACKUP_TRANSPORT_KINDS.S3: { + return transport.secret['secretAccessKey']; + } + case ZIBRI_BACKUP_TRANSPORT_KINDS.SFTP: { + return transport.secret['password'] ?? transport.secret['privateKey']; + } + default: { + return undefined; + } + } + } + + private findNameRefusal(transport: FakeStoredTransport): FakeAnswer | undefined { + const taken: boolean = this.stored.some(candidate => candidate.id !== transport.id && candidate.name === transport.name); + const message: string = 'Another TenantBackupTransport already holds these values for "name".'; + return taken ? FakeBackupTransportsBackend.refuse(409, 'ConflictError', [message]) : undefined; + } + + private static resolveFixtureSecret(kind: string): Record { + switch (kind) { + case ZIBRI_BACKUP_TRANSPORT_KINDS.S3: { + return { secretAccessKey: BACKUP_TRANSPORT_SECRET }; + } + case ZIBRI_BACKUP_TRANSPORT_KINDS.SFTP: { + return { password: BACKUP_TRANSPORT_SECRET }; + } + default: { + return {}; + } + } + } + + private static refuse(status: number, name: string, paragraphs: string[]): FakeAnswer { + const body: ErrorResponseBody = { status, name, message: paragraphs[0] ?? '', paragraphs }; + return { status, body }; + } + + private static toModel(transport: FakeStoredTransport): TenantBackupTransportModel { + const { id, tenantId, name, kind, settings } = transport; + return { id, tenantId, name, kind, settings }; + } + + // the body as the api reads it: strings for the name and the kind, objects for the settings and the secret + private static readBody(body: unknown): FakeTransportBody { + if (typeof body !== 'object' || body == undefined) { + return { name: undefined, kind: undefined, settings: undefined, secret: undefined }; + } + const readString: (key: string) => string | undefined = key => { + const value: unknown = Reflect.get(body, key); + return typeof value === 'string' ? value : undefined; + }; + const readObject: (key: string) => Record | undefined = key => { + const value: unknown = Reflect.get(body, key); + return typeof value === 'object' && value != undefined && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : undefined; + }; + return { name: readString('name'), kind: readString('kind'), settings: readObject('settings'), secret: readObject('secret') }; + } +} diff --git a/projects/ngx-backup/locale/messages.de.xlf b/projects/ngx-backup/locale/messages.de.xlf new file mode 100644 index 0000000..492d634 --- /dev/null +++ b/projects/ngx-backup/locale/messages.de.xlf @@ -0,0 +1,291 @@ + + + + + + Access key ID + Zugriffsschlüssel-ID + + + Add storage + Speicher hinzufügen + + + The storage was added. + Der Speicher wurde hinzugefügt. + + + Bucket named in + Bucket benannt im + + + The path, like s3.example.com/agency-backups + Pfad, wie s3.example.com/agency-backups + + + The host, like agency-backups.s3.example.com + Host, wie agency-backups.s3.example.com + + + Bucket + Bucket + + + Cancel + Abbrechen + + + Choose the connection + Verbindung wählen + + + Choose the kind of storage + Art des Speichers wählen + + + Connection + Verbindung + + + One of the WebDAV connections, whose password it logs in with + Eine der WebDAV-Verbindungen, mit deren Passwort er sich anmeldet + + + 22 + 22 + + + Remove + Entfernen + + + Remove the storage ? + Den Speicher entfernen? + + + The app forgets the storage and its secret, and backs up nothing to it anymore. What is stored on it stays there. While backups are stored on it, it can't be removed: delete those backups first. + Die App vergisst den Speicher und sein Geheimnis und sichert nichts mehr darauf. Was darauf gespeichert ist, bleibt dort. Solange Backups darauf gespeichert sind, kann er nicht entfernt werden: Löschen Sie diese Backups zuerst. + + + The storage was removed. + Der Speicher wurde entfernt. + + + Edit + Bearbeiten + + + While backups are stored on it, only its name and its secret can change. + Solange Backups darauf gespeichert sind, können sich nur sein Name und sein Geheimnis ändern. + + + Endpoint + Endpunkt + + + The address of the storage, like https://s3.eu-central-1.amazonaws.com + Die Adresse des Speichers, wie https://s3.eu-central-1.amazonaws.com + + + Folder + Ordner + + + Relative to the URL of the connection, like Backups. Leave it empty for the folder of the connection + Relativ zur URL der Verbindung, wie Backups. Leer lassen für den Ordner der Verbindung + + + The folder of the connection + Der Ordner der Verbindung + + + Host + Host + + + Fingerprint of the host key + Fingerabdruck des Host-Schlüssels + + + Its SHA256 fingerprint as ssh-keygen -lf prints it, like SHA256:… + Sein SHA256-Fingerabdruck, wie ssh-keygen -lf ihn ausgibt, wie SHA256:… + + + The login it has + Die bisherige Anmeldung + + + Leave it empty to keep the one it has. + Leer lassen, um das bisherige zu behalten. + + + Kind + Art + + + Folder of a Nextcloud + Ordner einer Nextcloud + + + S3 bucket + S3-Bucket + + + SFTP server + SFTP-Server + + + Folder of a WebDAV server + Ordner eines WebDAV-Servers + + + Loading + Wird geladen + + + The storage of the backups couldn't be loaded. + Der Speicher der Backups konnte nicht geladen werden. + + + Log in with + Anmelden mit + + + A password + Einem Passwort + + + A private key + Einem privaten Schlüssel + + + Name + Name + + + What the storage is called, like Office bucket + Wie der Speicher heißt, wie Büro-Bucket + + + New secret access key + Neuer geheimer Zugriffsschlüssel + + + One of the Nextcloud connections, logged in as the user who owns the folder + Eine der Nextcloud-Verbindungen, angemeldet als der Benutzer, dem der Ordner gehört + + + Relative to the URL of the connection, like Backups. Only the app writes into it + Relativ zur URL der Verbindung, wie Backups. Nur die App schreibt hinein + + + There is no connection to a server of this kind yet. Add one to the WebDAV connections first. + Es gibt noch keine Verbindung zu einem Server dieser Art. Fügen Sie zuerst eine zu den WebDAV-Verbindungen hinzu. + + + There is no storage for the backups yet. + Es gibt noch keinen Speicher für die Backups. + + + Nobody + Niemandem + + + Passphrase + Passphrase + + + Only for a private key that is encrypted with one + Nur für einen privaten Schlüssel, der mit einer verschlüsselt ist + + + Password + Passwort + + + Folder on the server + Ordner auf dem Server + + + Port + Port + + + Leave it empty for 22 + Leer lassen für 22 + + + Folder in the bucket + Ordner im Bucket + + + The backups go below it. Leave it empty for the top of the bucket + Die Backups liegen darunter. Leer lassen für die oberste Ebene des Buckets + + + Private key + Privater Schlüssel + + + In OpenSSH format, as it is written in its file + Im OpenSSH-Format, wie er in seiner Datei steht + + + Region + Region + + + Like eu-central-1 + Wie eu-central-1 + + + The request couldn't be sent. Please try again. + Die Anfrage konnte nicht gesendet werden. Bitte versuchen Sie es erneut. + + + Save + Speichern + + + The storage was saved. + Der Speicher wurde gespeichert. + + + Secret access key + Geheimer Zugriffsschlüssel + + + It is stored and never shown again. + Es wird gespeichert und nie wieder angezeigt. + + + Shared with the groups + Geteilt mit den Gruppen + + + Their IDs in the Nextcloud, each followed by Enter. They read the backups and sync them to their devices + Ihre IDs in der Nextcloud, jeweils gefolgt von Enter. Sie lesen die Backups und synchronisieren sie auf ihre Geräte + + + Shared with the users + Geteilt mit den Benutzern + + + Testing the storage… + Der Speicher wird getestet… + + + The top of the bucket + Die oberste Ebene des Buckets + + + Storage of the backups + Speicher der Backups + + + Username + Benutzername + + + + diff --git a/projects/ngx-backup/ng-package.json b/projects/ngx-backup/ng-package.json new file mode 100644 index 0000000..eb19a9d --- /dev/null +++ b/projects/ngx-backup/ng-package.json @@ -0,0 +1,8 @@ +{ + "$schema": "../../node_modules/ng-packagr/ng-package.schema.json", + "assets": ["tailwind.css", "locale/messages.de.xlf", "CHANGELOG.md"], + "dest": "../../dist/ngx-backup", + "lib": { + "entryFile": "src/public-api.ts" + } +} diff --git a/projects/ngx-backup/package.json b/projects/ngx-backup/package.json new file mode 100644 index 0000000..b0cfb13 --- /dev/null +++ b/projects/ngx-backup/package.json @@ -0,0 +1,37 @@ +{ + "name": "@service-soft/ngx-backup", + "version": "22.4.0", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/Service-Soft/angular-libraries.git", + "directory": "projects/ngx-backup" + }, + "publishConfig": { + "access": "public" + }, + "dependencies": { + "tslib": "^2.3.0" + }, + "exports": { + ".": { + "style": "./tailwind.css" + } + }, + "peerDependencies": { + "@angular/aria": "^22.2.0", + "@angular/common": "^22.2.0", + "@angular/core": "^22.2.0", + "@angular/localize": "^22.2.0", + "@service-soft/ngx-error-handling": "^22.4.0", + "@service-soft/ngx-web-dav": "^22.4.0", + "@service-soft/ui": "^22.4.0", + "rxjs": "^7.8.0", + "tailwindcss": "^4.3.3", + "zibri-contract": "^3.3.0" + }, + "sideEffects": false, + "translations": { + "de": "./locale/messages.de.xlf" + } +} diff --git a/projects/ngx-backup/src/public-api.ts b/projects/ngx-backup/src/public-api.ts new file mode 100644 index 0000000..523e0c0 --- /dev/null +++ b/projects/ngx-backup/src/public-api.ts @@ -0,0 +1,5 @@ +/** + * The views live in their own secondary entry points, '@service-soft/ngx-backup/tenant-transports', and the services + * and the config in '@service-soft/ngx-backup/api'. + */ +export {}; diff --git a/projects/ngx-backup/tailwind.css b/projects/ngx-backup/tailwind.css new file mode 100644 index 0000000..4c7b7e3 --- /dev/null +++ b/projects/ngx-backup/tailwind.css @@ -0,0 +1 @@ +@source "./fesm2022"; diff --git a/projects/ngx-backup/tenant-transports/ng-package.json b/projects/ngx-backup/tenant-transports/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-backup/tenant-transports/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-backup/tenant-transports/public-api.ts b/projects/ngx-backup/tenant-transports/public-api.ts new file mode 100644 index 0000000..808c7c4 --- /dev/null +++ b/projects/ngx-backup/tenant-transports/public-api.ts @@ -0,0 +1 @@ +export * from './tenant-transports.component'; diff --git a/projects/ngx-backup/tenant-transports/tenant-transports.component.html b/projects/ngx-backup/tenant-transports/tenant-transports.component.html new file mode 100644 index 0000000..2fd7b2b --- /dev/null +++ b/projects/ngx-backup/tenant-transports/tenant-transports.component.html @@ -0,0 +1,244 @@ +
+
+ {{ labels.transports }} + @if (canAdd()) { + + } +
+ @if (loadingFailed()) { + + } + @if (error().length) { +
+ + @for (paragraph of error(); track $index) { +

{{ paragraph }}

+ } +
+
+ } + + @if (adding()) { +
+ {{ labels.add }} + + + + + + +
+ } + + @if (rows().length) { +
    + @for (row of rows(); track row.transport.id) { +
  • +
    +
    + + {{ row.transport.name }} + +
    +
    {{ labels.kind }}
    +
    {{ row.kind }}
    + @for (detail of row.details; track detail.label) { +
    {{ detail.label }}
    +
    {{ detail.value }}
    + } +
    +
    + @if (canManage()) { +
    + + +
    + } +
    + @if (row.editing) { + + @if (isKnownKind()) { +

    {{ labels.editHint }}

    + } + + + +
    + } +
  • + } +
+ } + @if (isEmpty()) { +

{{ labels.noTransports }}

+ } + +

{{ announcement() }}

+
+ + + + + + + + @switch (formKind()) { + @case (kinds.S3) { + + + + + + + + } + @case (kinds.SFTP) { + + + + + + + @if (login() === 'password') { + + } + @if (login() === 'privateKey') { + + + } + } + @case (kinds.WEB_DAV) { + + } + @case (kinds.NEXTCLOUD) { + + + + } + } + + + + + + + + + + + @if (formError().length) { + + } +
+ + + @if (saving()) { + {{ labels.testing }} + } +
+
diff --git a/projects/ngx-backup/tenant-transports/tenant-transports.component.spec.ts b/projects/ngx-backup/tenant-transports/tenant-transports.component.spec.ts new file mode 100644 index 0000000..35ebad1 --- /dev/null +++ b/projects/ngx-backup/tenant-transports/tenant-transports.component.spec.ts @@ -0,0 +1,402 @@ +import { Component, signal, WritableSignal } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { FormTestingUtilities } from 'testing/form'; +import { beforeEach, describe, expect, test } from 'vitest'; + +import { BackupTestingUtilities } from '../fixtures/backup-testing.utilities'; +import { ARCHIVE_TRANSPORT, BACKUP_TRANSPORT_IDS, BACKUP_TRANSPORT_SECRET, BUCKET_BACKUPS, TAPE_TRANSPORT } from '../fixtures/backup.fixtures'; +import { FakeBackupTransportsBackendOptions } from '../fixtures/fake-backup-transports-backend-options.model'; +import { FakeBackupTransportsBackend } from '../fixtures/fake-backup-transports-backend.model'; +import { FakeWebDavConnectionsBackend } from '../../ngx-web-dav/fixtures/fake-web-dav-connections-backend.model'; +import { OFFICE_SERVER_CONNECTION, WEB_DAV_IDS } from '../../ngx-web-dav/fixtures/web-dav.fixtures'; +import { TenantTransportsComponent } from './tenant-transports.component'; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [TenantTransportsComponent] +}) +class HostComponent { + readonly canManage: WritableSignal = signal(true); +} + +let backend: FakeBackupTransportsBackend; + +/** + * Renders the storage of the backups against a fake backend. + * @param canManage - Whether the user manages the storage. + * @param options - How the backend answers, by default a storage that accepts only BACKUP_TRANSPORT_SECRET, and a bucket + * that backups are stored on. + * @param webDav - The WebDAV connections of the tenant, those of the fixtures by default. + * @returns The fixture and its element. + */ +async function render( + canManage: boolean = true, + options: FakeBackupTransportsBackendOptions = { secret: BACKUP_TRANSPORT_SECRET, backups: { [BACKUP_TRANSPORT_IDS.bucket]: BUCKET_BACKUPS } }, + webDav?: FakeWebDavConnectionsBackend +): Promise<[ComponentFixture, HTMLElement]> { + backend = new FakeBackupTransportsBackend(options); + TestBed.configureTestingModule({ providers: BackupTestingUtilities.getProviders(backend, {}, webDav) }); + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + fixture.componentInstance.canManage.set(canManage); + document.body.append(fixture.nativeElement as HTMLElement); + await BackupTestingUtilities.render(fixture); + return [fixture, fixture.nativeElement as HTMLElement]; +} + +// by their headings: the chips of a form are list items as well +function findRows(root: HTMLElement): HTMLLIElement[] { + return [...root.querySelectorAll('h3')].map(heading => heading.closest('li')).filter(row => row != undefined); +} + +function findNames(root: HTMLElement): string[] { + return findRows(root).map(row => BackupTestingUtilities.getText(row.querySelector('h3'))); +} + +function findRow(root: HTMLElement, name: string): HTMLLIElement { + const row: HTMLLIElement | undefined = findRows(root).find(candidate => BackupTestingUtilities.getText(candidate.querySelector('h3')) === name); + if (row == undefined) { + throw new Error(`There is no storage "${name}".`); + } + return row; +} + +function getStatus(root: HTMLElement): string { + return BackupTestingUtilities.getText(root.querySelector('p[role="status"]')); +} + +// the options to choose, without the empty one of the native select while nothing is chosen +function findOptions(root: HTMLElement, name: string): string[] { + return [...root.querySelector(`select[name="${name}"]`)?.options ?? []] + .map(option => option.textContent.trim()) + .filter(text => text !== ''); +} + +async function openAdd(fixture: ComponentFixture, root: HTMLElement, kind: string): Promise { + BackupTestingUtilities.findButton(root, 'Add storage').click(); + await BackupTestingUtilities.render(fixture); + BackupTestingUtilities.choose(root, 'kind', kind); + await BackupTestingUtilities.render(fixture); +} + +async function submit(fixture: ComponentFixture, root: HTMLElement): Promise { + await BackupTestingUtilities.render(fixture); + BackupTestingUtilities.findButton(root, 'Save').click(); + await BackupTestingUtilities.render(fixture); +} + +async function addChip(fixture: ComponentFixture, root: HTMLElement, name: string, text: string): Promise { + const input: HTMLInputElement | null = FormTestingUtilities.findInput(root, name); + if (input == undefined) { + throw new Error(`There is no input named "${name}".`); + } + input.value = text; + input.dispatchEvent(new InputEvent('input', { inputType: 'insertText' })); + await fixture.whenStable(); + input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', cancelable: true })); + await fixture.whenStable(); +} + +describe('TenantTransportsComponent', () => { + beforeEach(() => { + document.body.replaceChildren(); + }); + + test('lists the storage by name with its kind and its settings in words, and nothing that changes it without canManage', async () => { + const [, root] = await render(false); + + expect(BackupTestingUtilities.getText(root.querySelector('h2'))).toBe('Storage of the backups'); + expect(findRows(root).map(row => BackupTestingUtilities.getText(row))).toEqual([ + 'Archive server Kind SFTP server Host archive.example.com Port 2222 Username backup Folder on the server /srv/backups/agency ' + + 'Fingerprint of the host key SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8', + 'Nextcloud Kind Folder of a Nextcloud Connection Nextcloud Folder Backups Shared with the users ada Shared with the groups management', + 'Office bucket Kind S3 bucket Endpoint https://s3.eu-central-1.amazonaws.com Bucket agency-backups Region eu-central-1 ' + + 'Folder in the bucket nightly Bucket named in The host, like agency-backups.s3.example.com Access key ID AKIAIOSFODNN7EXAMPLE', + 'Office server Kind Folder of a WebDAV server Connection Office server Folder The folder of the connection' + ]); + expect(root.querySelectorAll('button')).toHaveLength(0); + // the kinds are only for the form adding storage + expect(backend.requests.map(request => request.url)).toEqual(['/api/backup-transports']); + }); + + test('shows a kind of the app it doesn\'t know by its name, with its settings as they are, and only its name to change', async () => { + const [fixture, root] = await render(true, { transports: [TAPE_TRANSPORT] }); + + expect(BackupTestingUtilities.getText(findRow(root, 'Tape library'))).toContain('Kind tape library LTO-9 in the basement slots [4,5]'); + BackupTestingUtilities.findButton(root, 'Edit').click(); + await BackupTestingUtilities.render(fixture); + expect([...root.querySelectorAll('form input, form select, form textarea')].map(input => input.getAttribute('name'))).toEqual(['name']); + FormTestingUtilities.type(root, 'name', 'Tapes'); + await submit(fixture, root); + + expect(backend.requests.at(-1)?.body).toEqual({ name: 'Tapes' }); + expect(findNames(root)).toEqual(['Tapes']); + }); + + test('adds a bucket once the api wrote to it, says so and gives the focus back', async () => { + const [fixture, root] = await render(); + const addButton: HTMLButtonElement = BackupTestingUtilities.findButton(root, 'Add storage'); + + await openAdd(fixture, root, 'S3 bucket'); + expect(addButton.getAttribute('aria-expanded')).toBe('true'); + FormTestingUtilities.type(root, 'name', ' Second bucket '); + FormTestingUtilities.type(root, 'endpoint', 'https://s3.eu-west-1.amazonaws.com'); + FormTestingUtilities.type(root, 'bucket', 'agency-copies'); + FormTestingUtilities.type(root, 'region', 'eu-west-1'); + FormTestingUtilities.type(root, 'accessKeyId', 'AKIAI44QH8DHBEXAMPLE'); + FormTestingUtilities.type(root, 'secretAccessKey', BACKUP_TRANSPORT_SECRET); + expect(FormTestingUtilities.findInput(root, 'secretAccessKey')?.type).toBe('password'); + await submit(fixture, root); + + expect(backend.requests.at(-1)?.body).toEqual({ + name: 'Second bucket', + kind: 's3', + settings: { + endpoint: 'https://s3.eu-west-1.amazonaws.com', + bucket: 'agency-copies', + region: 'eu-west-1', + accessKeyId: 'AKIAI44QH8DHBEXAMPLE', + prefix: null, + addressingStyle: 'virtual-hosted' + }, + secret: { secretAccessKey: BACKUP_TRANSPORT_SECRET } + }); + expect(findNames(root)).toEqual(['Archive server', 'Nextcloud', 'Office bucket', 'Office server', 'Second bucket']); + expect(BackupTestingUtilities.getText(findRow(root, 'Second bucket'))).toContain('Folder in the bucket The top of the bucket'); + expect(getStatus(root)).toBe('The storage Second bucket was added.'); + expect(root.querySelector('form')).toBeNull(); + expect(document.activeElement).toBe(addButton); + }); + + test('shows why the api refused the test of a storage in the form, which stays as it was', async () => { + const [fixture, root] = await render(); + + await openAdd(fixture, root, 'S3 bucket'); + FormTestingUtilities.type(root, 'name', 'Second bucket'); + FormTestingUtilities.type(root, 'endpoint', 'https://s3.eu-west-1.amazonaws.com'); + FormTestingUtilities.type(root, 'bucket', 'agency-copies'); + FormTestingUtilities.type(root, 'region', 'eu-west-1'); + FormTestingUtilities.type(root, 'accessKeyId', 'AKIAI44QH8DHBEXAMPLE'); + FormTestingUtilities.type(root, 'secretAccessKey', 'wrong'); + await submit(fixture, root); + + expect(BackupTestingUtilities.getText(root.querySelector('form [role="alert"] p'))).toBe( + 'The transport Second bucket could not be written to: The storage refused the secret.' + ); + expect(FormTestingUtilities.findInput(root, 'bucket')?.value).toBe('agency-copies'); + expect(getStatus(root)).toBe(''); + expect(backend.getTransports()).toHaveLength(4); + }); + + test('offers only the kinds the api offers that it knows, and no button to add without one', async () => { + const [fixture, root] = await render(true, { kinds: [{ name: 'sftp' }, { name: 'tape' }] }); + + BackupTestingUtilities.findButton(root, 'Add storage').click(); + await BackupTestingUtilities.render(fixture); + expect(findOptions(root, 'kind')).toEqual(['SFTP server']); + + }); + + test('has no button adding storage while the api offers no kind it knows', async () => { + const [, root] = await render(true, { kinds: [{ name: 'tape' }] }); + + expect([...root.querySelectorAll('button')].map(button => button.textContent.trim())).not.toContain('Add storage'); + expect(BackupTestingUtilities.getText(root)).toContain('Edit'); + }); + + test('adds an SFTP server that logs in with a private key and its passphrase', async () => { + const [fixture, root] = await render(true, {}); + + await openAdd(fixture, root, 'SFTP server'); + FormTestingUtilities.type(root, 'name', 'Second archive'); + FormTestingUtilities.type(root, 'host', 'second.example.com'); + FormTestingUtilities.type(root, 'username', 'backup'); + FormTestingUtilities.type(root, 'path', '/srv/backups'); + FormTestingUtilities.type(root, 'hostKeyFingerprint', 'SHA256:abc'); + expect(FormTestingUtilities.findInput(root, 'password')).not.toBeNull(); + BackupTestingUtilities.choose(root, 'login', 'A private key'); + await BackupTestingUtilities.render(fixture); + expect(FormTestingUtilities.findInput(root, 'password')).toBeNull(); + BackupTestingUtilities.typeText(root, 'privateKey', '-----BEGIN OPENSSH PRIVATE KEY-----'); + FormTestingUtilities.type(root, 'passphrase', 'correct horse'); + await submit(fixture, root); + + expect(backend.requests.at(-1)?.body).toEqual({ + name: 'Second archive', + kind: 'sftp', + settings: { host: 'second.example.com', port: null, username: 'backup', hostKeyFingerprint: 'SHA256:abc', path: '/srv/backups' }, + secret: { privateKey: '-----BEGIN OPENSSH PRIVATE KEY-----', passphrase: 'correct horse' } + }); + expect(BackupTestingUtilities.getText(findRow(root, 'Second archive'))).toContain('Port 22'); + }); + + test('adds a folder of a Nextcloud through one of the Nextcloud connections, shared with users and groups', async () => { + const [fixture, root] = await render(); + + await openAdd(fixture, root, 'Folder of a Nextcloud'); + expect(findOptions(root, 'connectionId')).toEqual(['Nextcloud']); + FormTestingUtilities.type(root, 'name', 'Second Nextcloud'); + BackupTestingUtilities.choose(root, 'connectionId', 'Nextcloud'); + FormTestingUtilities.type(root, 'folder', 'Backups/Copies'); + await addChip(fixture, root, 'sharedWithUsers', 'grace'); + await addChip(fixture, root, 'sharedWithGroups', 'auditors'); + await submit(fixture, root); + + expect(backend.requests.at(-1)?.body).toEqual({ + name: 'Second Nextcloud', + kind: 'nextcloud', + settings: { connectionId: WEB_DAV_IDS.nextcloud, folder: 'Backups/Copies', sharedWithUsers: ['grace'], sharedWithGroups: ['auditors'] }, + secret: {} + }); + }); + + test('offers the WebDAV connections for a folder of a WebDAV server, whose folder may be the one of the connection', async () => { + const [fixture, root] = await render(); + + await openAdd(fixture, root, 'Folder of a WebDAV server'); + expect(findOptions(root, 'connectionId')).toEqual(['Office server']); + expect(FormTestingUtilities.findInput(root, 'folder')?.required).toBe(false); + FormTestingUtilities.type(root, 'name', 'Office copy'); + BackupTestingUtilities.choose(root, 'connectionId', 'Office server'); + await submit(fixture, root); + + expect(backend.requests.at(-1)?.body).toEqual({ + name: 'Office copy', + kind: 'web-dav', + settings: { connectionId: WEB_DAV_IDS.officeServer, folder: '' }, + secret: {} + }); + }); + + test('says when the tenant has no connection of the server a kind reaches its folder through', async () => { + const [fixture, root] = await render(true, {}, new FakeWebDavConnectionsBackend({ connections: [OFFICE_SERVER_CONNECTION] })); + + await openAdd(fixture, root, 'Folder of a Nextcloud'); + + expect(findOptions(root, 'connectionId')).toEqual([]); + expect(BackupTestingUtilities.getText(root.querySelector('ui-input-select[name="connectionId"]'))).toContain( + 'There is no connection to a server of this kind yet. Add one to the WebDAV connections first.' + ); + // the list shows a connection it doesn't know by its id + expect(BackupTestingUtilities.getText(findRow(root, 'Nextcloud'))).toContain(`Connection ${WEB_DAV_IDS.nextcloud}`); + }); + + test('changes only the name of a storage, and keeps its secret, which the form never shows', async () => { + const [fixture, root] = await render(); + const editButton: HTMLButtonElement = BackupTestingUtilities.findButton(findRow(root, 'Office bucket'), 'Edit'); + + editButton.click(); + await BackupTestingUtilities.render(fixture); + expect(BackupTestingUtilities.getText(root.querySelector('form'))).toContain('While backups are stored on it, only its name and its secret can change.'); + expect(FormTestingUtilities.findInput(root, 'bucket')?.value).toBe('agency-backups'); + expect(FormTestingUtilities.findInput(root, 'prefix')?.value).toBe('nightly'); + expect(FormTestingUtilities.findInput(root, 'secretAccessKey')?.value).toBe(''); + expect(FormTestingUtilities.findInput(root, 'secretAccessKey')?.required).toBe(false); + FormTestingUtilities.type(root, 'name', 'Main bucket'); + await submit(fixture, root); + + expect(backend.requests.at(-1)?.method).toBe('PATCH'); + expect(backend.requests.at(-1)?.url).toBe(`/api/backup-transports/${BACKUP_TRANSPORT_IDS.bucket}`); + expect(backend.requests.at(-1)?.body).toEqual({ name: 'Main bucket' }); + expect(getStatus(root)).toBe('The storage Main bucket was saved.'); + expect(document.activeElement).toBe(editButton); + }); + + test('sets a new secret of a storage backups are stored on, without its settings', async () => { + const [fixture, root] = await render(); + + BackupTestingUtilities.findButton(findRow(root, 'Office bucket'), 'Edit').click(); + await BackupTestingUtilities.render(fixture); + FormTestingUtilities.type(root, 'secretAccessKey', BACKUP_TRANSPORT_SECRET); + await submit(fixture, root); + + expect(backend.requests.at(-1)?.body).toEqual({ secret: { secretAccessKey: BACKUP_TRANSPORT_SECRET } }); + expect(root.querySelector('form')).toBeNull(); + }); + + test('shows why the api refused changing the settings of a storage backups are stored on', async () => { + const [fixture, root] = await render(); + + BackupTestingUtilities.findButton(findRow(root, 'Office bucket'), 'Edit').click(); + await BackupTestingUtilities.render(fixture); + FormTestingUtilities.type(root, 'bucket', 'agency-elsewhere'); + await submit(fixture, root); + + expect(BackupTestingUtilities.getText(root.querySelector('form [role="alert"] p'))).toBe( + `The settings of the transport are kept while backups are stored on it: ${BUCKET_BACKUPS.join(', ')}. Delete those first.` + ); + expect(backend.getTransports().find(transport => transport.id === BACKUP_TRANSPORT_IDS.bucket)?.settings['bucket']).toBe('agency-backups'); + }); + + test('changes the settings of an SFTP server and keeps the login it has', async () => { + const [fixture, root] = await render(); + + BackupTestingUtilities.findButton(findRow(root, 'Archive server'), 'Edit').click(); + await BackupTestingUtilities.render(fixture); + expect(root.querySelector('select[name="login"]')?.selectedOptions[0]?.textContent.trim()).toBe('The login it has'); + expect(FormTestingUtilities.findInput(root, 'password')).toBeNull(); + expect(FormTestingUtilities.findInput(root, 'port')?.value).toBe('2222'); + FormTestingUtilities.type(root, 'host', 'archive2.example.com'); + await submit(fixture, root); + + expect(backend.requests.at(-1)?.body).toEqual({ settings: { ...ARCHIVE_TRANSPORT.settings, host: 'archive2.example.com' } }); + expect(backend.getSecret(BACKUP_TRANSPORT_IDS.archive)).toEqual({ password: BACKUP_TRANSPORT_SECRET }); + }); + + test('removes a storage after asking, which says what happens to the backups on it', async () => { + const [fixture, root] = await render(); + + BackupTestingUtilities.findButton(findRow(root, 'Office server'), 'Remove').click(); + await BackupTestingUtilities.render(fixture); + const dialog: HTMLDialogElement | null = document.querySelector('dialog[open]'); + expect(BackupTestingUtilities.getText(dialog)).toContain('Remove the storage Office server?'); + expect(BackupTestingUtilities.getText(dialog)).toContain('What is stored on it stays there. While backups are stored on it, it can\'t be removed'); + BackupTestingUtilities.findButton(dialog ?? document, 'Remove').click(); + await BackupTestingUtilities.render(fixture); + + expect(backend.requests.at(-1)?.method).toBe('DELETE'); + expect(findNames(root)).toEqual(['Archive server', 'Nextcloud', 'Office bucket']); + expect(getStatus(root)).toBe('The storage Office server was removed.'); + expect(document.activeElement).toBe(BackupTestingUtilities.findButton(root, 'Add storage')); + }); + + test('removes nothing when the question is cancelled', async () => { + const [fixture, root] = await render(); + + BackupTestingUtilities.findButton(findRow(root, 'Office server'), 'Remove').click(); + await BackupTestingUtilities.render(fixture); + BackupTestingUtilities.findButton(document.querySelector('dialog[open]') ?? document, 'Cancel').click(); + await BackupTestingUtilities.render(fixture); + + expect(backend.requests.map(request => request.method)).toEqual(['GET', 'GET']); + expect(findRows(root)).toHaveLength(4); + }); + + test('shows the backups the api names when it refuses removing a storage they are stored on', async () => { + const [fixture, root] = await render(); + + BackupTestingUtilities.findButton(findRow(root, 'Office bucket'), 'Remove').click(); + await BackupTestingUtilities.render(fixture); + BackupTestingUtilities.findButton(document.querySelector('dialog[open]') ?? document, 'Remove').click(); + await BackupTestingUtilities.render(fixture); + + expect([...root.querySelectorAll('[role="alert"] p')].map(paragraph => BackupTestingUtilities.getText(paragraph))).toEqual([ + `The transport is stored on by backups: ${BUCKET_BACKUPS.join(', ')}. Delete those first.` + ]); + expect(findRows(root)).toHaveLength(4); + }); + + test('says when there is no storage', async () => { + const [, root] = await render(true, { transports: [] }); + + expect(BackupTestingUtilities.getText(root.querySelector('ngx-backup-tenant-transports'))).toContain('There is no storage for the backups yet.'); + expect(root.querySelector('ul')).toBeNull(); + }); + + test('says when the storage couldn\'t be loaded', async () => { + const [, root] = await render(true, { unavailable: true }); + + expect(BackupTestingUtilities.getText(root.querySelector('[role="alert"]'))).toBe('The storage of the backups couldn\'t be loaded.'); + expect(BackupTestingUtilities.getText(root)).not.toContain('There is no storage for the backups yet.'); + }); +}); diff --git a/projects/ngx-backup/tenant-transports/tenant-transports.component.ts b/projects/ngx-backup/tenant-transports/tenant-transports.component.ts new file mode 100644 index 0000000..47f934f --- /dev/null +++ b/projects/ngx-backup/tenant-transports/tenant-transports.component.ts @@ -0,0 +1,831 @@ +import { NgTemplateOutlet } from '@angular/common'; +import { HttpErrorResponse } from '@angular/common/http'; +import { afterNextRender, booleanAttribute, Component, computed, ElementRef, inject, Injector, input, InputSignalWithTransform, resource, ResourceRef, Signal, signal, viewChild, WritableSignal } from '@angular/core'; +import { BACKUP_CONFIG, BackupConfig, BackupTransportsService, SftpLogin, TenantTransportsLabels } from '@service-soft/ngx-backup/api'; +import { ErrorResponseUtilities } from '@service-soft/ngx-error-handling/error-response'; +import { WEB_DAV_CONFIG, WebDavConfig, WebDavConnectionsService } from '@service-soft/ngx-web-dav/api'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { ConfirmDialogComponent, DialogService } from '@service-soft/ui/dialog'; +import { FormComponent } from '@service-soft/ui/form'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { InputOption } from '@service-soft/ui/input'; +import { InputChipsComponent, InputChipsCustomValue } from '@service-soft/ui/input-chips'; +import { InputNumberComponent } from '@service-soft/ui/input-number'; +import { InputSelectComponent } from '@service-soft/ui/input-select'; +import { InputStringComponent } from '@service-soft/ui/input-string'; +import { InputTextareaComponent } from '@service-soft/ui/input-textarea'; +import { LoadingDirective } from '@service-soft/ui/loading'; +import { ErrorResponseBody, S3_ADDRESSING_STYLES, S3AddressingStyle, TenantBackupTransportChangeModel, TenantBackupTransportKindModel, TenantBackupTransportModel, TenantNextcloudTransportSettingsModel, TenantS3TransportSettingsModel, TenantSftpTransportSecretModel, TenantSftpTransportSettingsModel, TenantWebDavConnectionModel, TenantWebDavTransportSettingsModel, WebDavConnectionKind, ZIBRI_BACKUP_TRANSPORT_KINDS, ZIBRI_BACKUP_TRANSPORT_LIMITS } from 'zibri-contract'; + +// the sections of a view are headed one level below it, and a heading of level 6 has no level below. +const SECTION_LEVELS: Record = { 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 6 }; + +// the kinds whose fields the view knows, and the server each reaches its folder through, if any. A kind of the app +// beyond them shows its settings as they are, and only its name changes here. +const KNOWN_KINDS: Record = { + [ZIBRI_BACKUP_TRANSPORT_KINDS.S3]: undefined, + [ZIBRI_BACKUP_TRANSPORT_KINDS.SFTP]: undefined, + [ZIBRI_BACKUP_TRANSPORT_KINDS.WEB_DAV]: WebDavConnectionKind.WEB_DAV, + [ZIBRI_BACKUP_TRANSPORT_KINDS.NEXTCLOUD]: WebDavConnectionKind.NEXTCLOUD +}; + +// tells the ids of several views on one page apart +let nextId: number = 0; + +/** + * What the form changing an SFTP server logs in with: a new password or private key, or the login it has. + */ +type SftpLoginChoice = SftpLogin | 'keep'; + +/** + * The form adding a transport. + */ +type AddForm = { + /** + * What the form does. + */ + kind: 'add' +}; + +/** + * The form changing a transport. + */ +type EditForm = { + /** + * What the form does. + */ + kind: 'edit', + /** + * The transport it changes. + */ + transport: TenantBackupTransportModel, + /** + * The settings as the form showed them when it opened, as json, which tells whether they changed. + */ + initialSettings: string | undefined +}; + +/** + * The form that shows. + */ +type TransportForm = AddForm | EditForm; + +/** + * A setting of a transport as it shows in the list. + */ +type TransportDetail = { + /** + * What it is. + */ + label: string, + /** + * Its value, in words. + */ + value: string +}; + +/** + * A transport as it shows in the list. + */ +type TransportRow = { + /** + * The transport. + */ + transport: TenantBackupTransportModel, + /** + * Its kind, in words. + */ + kind: string, + /** + * Its settings, in words. + */ + details: TransportDetail[], + /** + * The id of its heading, which describes its buttons. + */ + headingId: string, + /** + * Whether the form changing it shows. + */ + editing: boolean +}; + +/** + * The storage the tenant keeps its backups on, at the api of provideBackupConfig: ``. Each shows its name, its kind and its settings, never its secret. With `canManage`, like + * `backup-transports.manage`, the user adds storage of the kinds the api offers, a bucket, an SFTP server, or a folder of + * a WebDAV server or a Nextcloud through a connection of `@service-soft/ngx-web-dav`, which the api adds once it wrote to + * it, changes it and its write-only secret, and removes it after a question. What the api refuses, like a secret the + * storage refused or backups still stored on it, shows its message. + */ +@Component({ + selector: 'ngx-backup-tenant-transports', + templateUrl: './tenant-transports.component.html', + imports: [ + ButtonComponent, + CalloutComponent, + FormComponent, + HeadingComponent, + InputChipsComponent, + InputNumberComponent, + InputSelectComponent, + InputStringComponent, + InputTextareaComponent, + LoadingDirective, + NgTemplateOutlet + ], + host: { class: 'block' } +}) +export class TenantTransportsComponent { + /** + * The config of the backups. + */ + protected readonly config: BackupConfig = inject(BACKUP_CONFIG); + + /** + * Whether the user adds, changes and removes storage, like with `backup-transports.manage`. The default comes from + * provideBackupConfig. + */ + readonly canManage: InputSignalWithTransform = input(this.config.canManage, { transform: booleanAttribute }); + + /** + * The texts of the view. + */ + protected readonly labels: TenantTransportsLabels = this.config.labels.tenantTransports; + + /** + * The longest values the api takes. + */ + protected readonly limits: typeof ZIBRI_BACKUP_TRANSPORT_LIMITS = ZIBRI_BACKUP_TRANSPORT_LIMITS; + + /** + * The names of the kinds the view knows, for the template. + */ + protected readonly kinds: typeof ZIBRI_BACKUP_TRANSPORT_KINDS = ZIBRI_BACKUP_TRANSPORT_KINDS; + + /** + * The level of the heading of the view. + */ + protected readonly headingLevel: HeadingLevel = this.config.headingLevel; + + /** + * The level of the headings of the transports and the form adding one. + */ + protected readonly sectionLevel: HeadingLevel = SECTION_LEVELS[this.config.headingLevel]; + + /** + * The form that shows, or undefined for none. + */ + protected readonly form: WritableSignal = signal(undefined); + + /** + * The name of the form. + */ + protected readonly name: WritableSignal = signal(''); + + /** + * The kind of the form adding a transport, undefined until the user chose one. + */ + protected readonly kind: WritableSignal = signal(undefined); + + /** + * The endpoint of a bucket. + */ + protected readonly endpoint: WritableSignal = signal(''); + + /** + * The bucket. + */ + protected readonly bucket: WritableSignal = signal(''); + + /** + * The region of a bucket. + */ + protected readonly region: WritableSignal = signal(''); + + /** + * The id of the access key of a bucket. + */ + protected readonly accessKeyId: WritableSignal = signal(''); + + /** + * The folder in a bucket, empty for its top. + */ + protected readonly prefix: WritableSignal = signal(''); + + /** + * Where the requests name a bucket. + */ + protected readonly addressingStyle: WritableSignal = signal('virtual-hosted'); + + /** + * The secret access key of a bucket, never filled in by the view. + */ + protected readonly secretAccessKey: WritableSignal = signal(''); + + /** + * The host of an SFTP server. + */ + protected readonly host: WritableSignal = signal(''); + + /** + * The port of an SFTP server, undefined for 22. + */ + protected readonly port: WritableSignal = signal(undefined); + + /** + * The user logging in to an SFTP server. + */ + protected readonly username: WritableSignal = signal(''); + + /** + * The fingerprint of the host key of an SFTP server. + */ + protected readonly hostKeyFingerprint: WritableSignal = signal(''); + + /** + * The folder on an SFTP server. + */ + protected readonly path: WritableSignal = signal(''); + + /** + * What an SFTP server is logged in to with. + */ + protected readonly login: WritableSignal = signal('password'); + + /** + * The password of an SFTP server, never filled in by the view. + */ + protected readonly password: WritableSignal = signal(''); + + /** + * The private key of an SFTP server, never filled in by the view. + */ + protected readonly privateKey: WritableSignal = signal(''); + + /** + * The passphrase of the private key, never filled in by the view. + */ + protected readonly passphrase: WritableSignal = signal(''); + + /** + * The WebDAV connection a folder is reached through. + */ + protected readonly connectionId: WritableSignal = signal(undefined); + + /** + * The folder of a WebDAV server or a Nextcloud. + */ + protected readonly folder: WritableSignal = signal(''); + + /** + * The users the folder of a Nextcloud is shared with. + */ + protected readonly sharedWithUsers: WritableSignal = signal([]); + + /** + * The groups the folder of a Nextcloud is shared with. + */ + protected readonly sharedWithGroups: WritableSignal = signal([]); + + /** + * Takes the id of a user or a group the user typed. + */ + protected readonly toId: InputChipsCustomValue = text => text.trim() === '' ? undefined : text.trim(); + + /** + * Where the requests name a bucket, to choose from. + */ + protected readonly addressingStyleOptions: InputOption[] = S3_ADDRESSING_STYLES + .map(style => ({ label: this.labels.addressingStyles[style], value: style })); + + /** + * Whether the form waits for the api, which tests the transport first. + */ + protected readonly saving: WritableSignal = signal(false); + + /** + * Why the api refused what the form sent, one paragraph each, or none. + */ + protected readonly formError: WritableSignal = signal([]); + + /** + * Why the api refused removing a transport, one paragraph each, or none. + */ + protected readonly error: WritableSignal = signal([]); + + /** + * What the view last said about a change, read by screen readers as it changes. + */ + protected readonly announcement: WritableSignal = signal(''); + + private readonly transportsService: BackupTransportsService = inject(BackupTransportsService); + + private readonly webDavConfig: WebDavConfig = inject(WEB_DAV_CONFIG); + + private readonly webDavConnectionsService: WebDavConnectionsService = inject(WebDavConnectionsService); + + private readonly dialogService: DialogService = inject(DialogService); + + private readonly injector: Injector = inject(Injector); + + private readonly element: HTMLElement = inject>(ElementRef).nativeElement; + + private readonly idPrefix: string = `ngx-backup-tenant-transports-${nextId++}`; + + private readonly addButton: Signal | undefined> = viewChild('addButton', { read: ElementRef }); + + // the button that opened the form, which gets the focus back once it closes + private opener: HTMLElement | undefined; + + // changes of this view update it in place rather than loading it again, so the list and the focus in it stay + private readonly transports: ResourceRef = resource({ + loader: async () => await this.transportsService.resolveTransports() + }); + + // only the forms adding a transport choose a kind + private readonly offeredKinds: ResourceRef = resource({ + params: () => this.canManage() ? true : undefined, + loader: async () => await this.transportsService.resolveKinds() + }); + + // loaded again after every change of the connections in the app, like one added in the connections view. Without the + // url of the connection routes there are none, and a folder of a WebDAV server or a Nextcloud can't be added + private readonly connectionsResource: ResourceRef = resource({ + params: () => this.webDavConfig.baseUrl == undefined ? undefined : { revision: this.webDavConnectionsService.revision() }, + loader: async () => await this.webDavConnectionsService.resolveConnections() + }); + + /** + * The connections of the tenant, none for a user who may not list them: the list then shows a connection by its id. + */ + private readonly connections: Signal = computed(() => { + return this.connectionsResource.hasValue() ? this.connectionsResource.value() ?? [] : []; + }); + + /** + * Whether the transports are loading. + */ + protected readonly isLoading: Signal = computed(() => this.transports.isLoading() || this.offeredKinds.isLoading()); + + /** + * Whether the transports couldn't be loaded. + */ + protected readonly loadingFailed: Signal = computed(() => this.transports.error() != undefined || this.offeredKinds.error() != undefined); + + /** + * The kinds a transport can be added of: those the api offers that the view knows, and a folder of a WebDAV server or + * a Nextcloud only in an app with the WebDAV connections. + */ + protected readonly kindOptions: Signal[]> = computed(() => { + const offered: TenantBackupTransportKindModel[] = this.offeredKinds.hasValue() ? this.offeredKinds.value() ?? [] : []; + return offered + .filter(kind => kind.name in KNOWN_KINDS && (KNOWN_KINDS[kind.name] == undefined || this.webDavConfig.baseUrl != undefined)) + .map(kind => ({ label: this.resolveKindLabel(kind.name), value: kind.name })); + }); + + /** + * Whether the button adding a transport shows: with canManage, and a kind to add. + */ + protected readonly canAdd: Signal = computed(() => this.canManage() && this.kindOptions().length > 0); + + /** + * Whether the form adding a transport shows. + */ + protected readonly adding: Signal = computed(() => this.form()?.kind === 'add'); + + /** + * Whether the form that shows changes a transport, whose secret is then kept unless the user sets a new one. + */ + protected readonly isEditing: Signal = computed(() => this.form()?.kind === 'edit'); + + /** + * The kind of the transport of the form. + */ + protected readonly formKind: Signal = computed(() => { + const form: TransportForm | undefined = this.form(); + return form?.kind === 'edit' ? form.transport.kind : this.kind(); + }); + + /** + * Whether the view knows the fields of the kind of the form. + */ + protected readonly isKnownKind: Signal = computed(() => { + const kind: string | undefined = this.formKind(); + return kind != undefined && kind in KNOWN_KINDS; + }); + + /** + * The ways an SFTP server can be logged in to, and in the form changing one, keeping the login it has. + */ + protected readonly loginOptions: Signal[]> = computed(() => { + const logins: InputOption[] = [ + { label: this.labels.logins.password, value: 'password' }, + { label: this.labels.logins.privateKey, value: 'privateKey' } + ]; + return this.isEditing() ? [{ label: this.labels.keepLogin, value: 'keep' }, ...logins] : logins; + }); + + /** + * The connections of the server the kind of the form reaches its folder through. + */ + protected readonly connectionOptions: Signal[]> = computed(() => { + const kind: string | undefined = this.formKind(); + const server: WebDavConnectionKind | undefined = kind == undefined ? undefined : KNOWN_KINDS[kind]; + return this.connections() + .filter(connection => connection.kind === server) + .map(connection => ({ label: connection.name, value: connection.id })); + }); + + /** + * The hint of the connection, which says when there is none to choose. + */ + protected readonly connectionHint: Signal = computed(() => { + if (!this.connectionOptions().length) { + return this.labels.noConnections; + } + return this.formKind() === ZIBRI_BACKUP_TRANSPORT_KINDS.NEXTCLOUD ? this.labels.nextcloudConnectionHint : this.labels.connectionHint; + }); + + /** + * The transports as they show, by name. + */ + protected readonly rows: Signal = computed(() => { + const transports: TenantBackupTransportModel[] = this.transports.hasValue() ? this.transports.value() ?? [] : []; + const form: TransportForm | undefined = this.form(); + return transports.map(transport => ({ + transport, + kind: this.resolveKindLabel(transport.kind), + details: this.resolveDetails(transport), + headingId: `${this.idPrefix}-${transport.id}`, + editing: form?.kind === 'edit' && form.transport.id === transport.id + })); + }); + + /** + * Whether the view says there are no transports: once they loaded. + */ + protected readonly isEmpty: Signal = computed(() => this.transports.hasValue() && !this.rows().length); + + /** + * Shows the empty form adding a transport, or hides it. + * @param event - The click on the button that toggles it. + */ + protected toggleAdd(event: Event): void { + if (this.adding()) { + this.closeForm(); + return; + } + this.open({ kind: 'add' }, undefined, event); + } + + /** + * Shows the form changing a transport, filled with its name and settings, or hides it. + * @param transport - The transport. + * @param event - The click on the button that toggles it. + */ + protected toggleEdit(transport: TenantBackupTransportModel, event: Event): void { + const form: TransportForm | undefined = this.form(); + if (form?.kind === 'edit' && form.transport.id === transport.id) { + this.closeForm(); + return; + } + this.open({ kind: 'edit', transport, initialSettings: undefined }, transport, event); + } + + /** + * Hides the form without saving it, and gives the focus back to the button that opened it. + */ + protected closeForm(): void { + this.form.set(undefined); + this.formError.set([]); + this.clearSecrets(); + const opener: HTMLElement | undefined = this.opener; + this.focusAfterRender(() => opener); + } + + /** + * Adds the transport of the form, which the api tests first. + */ + protected async add(): Promise { + const kind: string | undefined = this.kind(); + const settings: Record | undefined = kind == undefined ? undefined : this.resolveSettings(kind); + const secret: Record | undefined = kind == undefined ? undefined : this.resolveSecret(kind); + // the select is required, so the form submits only once a kind the view knows is chosen + if (kind == undefined || settings == undefined || secret == undefined) { + return; + } + await this.send(async () => { + const created: TenantBackupTransportModel = await this.transportsService.createTransport({ name: this.name().trim(), kind, settings, secret }); + this.transports.update(transports => this.sorted([...transports ?? [], created])); + return this.labels.added(created.name); + }); + } + + /** + * Saves what of the form differs from the transport: its name, its settings when one of them changed, and a new + * secret when the user set one. Changed settings and a new secret are tested by the api. + */ + protected async save(): Promise { + const form: TransportForm | undefined = this.form(); + if (form?.kind !== 'edit') { + return; + } + const { transport } = form; + const name: string = this.name().trim(); + const settings: Record | undefined = this.resolveSettings(transport.kind); + const secret: Record | undefined = this.resolveSecret(transport.kind); + const change: TenantBackupTransportChangeModel = { + ...name === transport.name ? {} : { name }, + ...settings == undefined || JSON.stringify(settings) === form.initialSettings ? {} : { settings }, + ...secret == undefined ? {} : { secret } + }; + if (!Object.keys(change).length) { + this.closeForm(); + return; + } + await this.send(async () => { + const saved: TenantBackupTransportModel = await this.transportsService.updateTransport(transport.id, change); + this.transports.update(transports => this.sorted((transports ?? []).map(candidate => candidate.id === saved.id ? saved : candidate))); + return this.labels.saved(saved.name); + }); + } + + /** + * Removes a transport, after asking. The api refuses it while backups are stored on it, and names them. + * @param transport - The transport. + */ + protected async delete(transport: TenantBackupTransportModel): Promise { + this.error.set([]); + this.announcement.set(''); + const confirmed: boolean | undefined = await this.dialogService.open(ConfirmDialogComponent, { + title: this.labels.deleteQuestion(transport.name), + paragraphs: [this.labels.deleteWarning], + confirmButtonLabel: this.labels.delete, + cancelButtonLabel: this.labels.cancel, + confirmButtonColor: 'error' + }).closed; + if (confirmed !== true) { + return; + } + try { + await this.transportsService.deleteTransport(transport.id); + } + catch (error) { + this.error.set(this.resolveErrorParagraphs(error)); + return; + } + this.transports.update(transports => transports?.filter(candidate => candidate.id !== transport.id)); + const form: TransportForm | undefined = this.form(); + if (form?.kind === 'edit' && form.transport.id === transport.id) { + this.form.set(undefined); + } + this.announcement.set(this.labels.deleted(transport.name)); + // the button that was focused is gone with its row + this.focusAfterRender(() => this.addButton()?.nativeElement ?? this.element.querySelector('li button') ?? undefined); + } + + private open(form: TransportForm, transport: TenantBackupTransportModel | undefined, event: Event): void { + // Safari doesn't focus a button that is clicked, so it is the target of the click rather than the active element + this.opener = event.currentTarget instanceof HTMLElement ? event.currentTarget : undefined; + const settings: Record = transport?.settings ?? {}; + this.name.set(transport?.name ?? ''); + this.kind.set(undefined); + this.endpoint.set(this.readString(settings, 'endpoint')); + this.bucket.set(this.readString(settings, 'bucket')); + this.region.set(this.readString(settings, 'region')); + this.accessKeyId.set(this.readString(settings, 'accessKeyId')); + this.prefix.set(this.readString(settings, 'prefix')); + this.addressingStyle.set(S3_ADDRESSING_STYLES.find(style => style === settings['addressingStyle']) ?? 'virtual-hosted'); + this.host.set(this.readString(settings, 'host')); + const port: unknown = settings['port']; + this.port.set(typeof port === 'number' ? port : undefined); + this.username.set(this.readString(settings, 'username')); + this.hostKeyFingerprint.set(this.readString(settings, 'hostKeyFingerprint')); + this.path.set(this.readString(settings, 'path')); + this.login.set(transport == undefined ? 'password' : 'keep'); + const connectionId: string = this.readString(settings, 'connectionId'); + this.connectionId.set(connectionId === '' ? undefined : connectionId); + this.folder.set(this.readString(settings, 'folder')); + this.sharedWithUsers.set(this.readStrings(settings, 'sharedWithUsers')); + this.sharedWithGroups.set(this.readStrings(settings, 'sharedWithGroups')); + this.clearSecrets(); + this.formError.set([]); + this.error.set([]); + // the settings as the form holds them, which a save compares against, so a setting the form leaves as it is + // isn't sent and tested again + const initial: Record | undefined = transport == undefined ? undefined : this.resolveSettings(transport.kind); + this.form.set(form.kind === 'edit' ? { ...form, initialSettings: initial == undefined ? undefined : JSON.stringify(initial) } : form); + // only one form shows at a time + this.focusAfterRender(() => this.element.querySelector('form input, form select') ?? undefined); + } + + // a change the form sends: what the api refuses shows in the form, which stays; what it does is announced, and the + // form closes + private async send(change: () => Promise): Promise { + if (this.saving()) { + return; + } + this.saving.set(true); + this.formError.set([]); + this.announcement.set(this.labels.testing); + try { + const announcement: string = await change(); + this.closeForm(); + this.announcement.set(announcement); + } + catch (error) { + this.announcement.set(''); + this.formError.set(this.resolveErrorParagraphs(error)); + } + finally { + this.saving.set(false); + } + } + + /** + * Resolves the settings of the form for a kind the view knows. + * @param kind - The kind. + * @returns The settings, or undefined for a kind the view doesn't know. + */ + private resolveSettings(kind: string): Record | undefined { + switch (kind) { + case ZIBRI_BACKUP_TRANSPORT_KINDS.S3: { + const settings: TenantS3TransportSettingsModel = { + endpoint: this.endpoint().trim(), + bucket: this.bucket().trim(), + region: this.region().trim(), + accessKeyId: this.accessKeyId().trim(), + prefix: this.prefix().trim() === '' ? null : this.prefix().trim(), + addressingStyle: this.addressingStyle() ?? 'virtual-hosted' + }; + return settings; + } + case ZIBRI_BACKUP_TRANSPORT_KINDS.SFTP: { + const settings: TenantSftpTransportSettingsModel = { + host: this.host().trim(), + port: this.port() ?? null, + username: this.username().trim(), + hostKeyFingerprint: this.hostKeyFingerprint().trim(), + path: this.path().trim() + }; + return settings; + } + case ZIBRI_BACKUP_TRANSPORT_KINDS.WEB_DAV: { + const settings: TenantWebDavTransportSettingsModel = { connectionId: this.connectionId() ?? '', folder: this.folder().trim() }; + return settings; + } + case ZIBRI_BACKUP_TRANSPORT_KINDS.NEXTCLOUD: { + const settings: TenantNextcloudTransportSettingsModel = { + connectionId: this.connectionId() ?? '', + folder: this.folder().trim(), + sharedWithUsers: this.sharedWithUsers(), + sharedWithGroups: this.sharedWithGroups() + }; + return settings; + } + default: { + return undefined; + } + } + } + + /** + * Resolves the secret of the form for a kind the view knows: all of it when a transport is added, and in the form + * changing one only what the user set, as the api never answers the secret it has. + * @param kind - The kind. + * @returns The secret, or undefined to keep the one the transport has. + */ + private resolveSecret(kind: string): Record | undefined { + const editing: boolean = this.isEditing(); + switch (kind) { + case ZIBRI_BACKUP_TRANSPORT_KINDS.S3: { + return editing && this.secretAccessKey() === '' ? undefined : { secretAccessKey: this.secretAccessKey() }; + } + case ZIBRI_BACKUP_TRANSPORT_KINDS.SFTP: { + return this.resolveSftpSecret(); + } + // the password is the one of the connection + case ZIBRI_BACKUP_TRANSPORT_KINDS.WEB_DAV: + case ZIBRI_BACKUP_TRANSPORT_KINDS.NEXTCLOUD: { + return editing ? undefined : {}; + } + default: { + return undefined; + } + } + } + + /** + * Resolves the secret of an SFTP server of the form: a password, or a private key with its passphrase if it has one. + * @returns The secret, or undefined to keep the login the server has. + */ + private resolveSftpSecret(): TenantSftpTransportSecretModel | undefined { + switch (this.login()) { + case 'password': { + return { password: this.password() }; + } + case 'privateKey': { + return this.passphrase() === '' ? { privateKey: this.privateKey() } : { privateKey: this.privateKey(), passphrase: this.passphrase() }; + } + case 'keep': + case undefined: { + return undefined; + } + } + } + + /** + * Resolves the settings of a transport in words: those of the kinds the view knows each with its label, and those of + * another kind as they are. + * @param transport - The transport. + * @returns The settings. + */ + private resolveDetails(transport: TenantBackupTransportModel): TransportDetail[] { + const { settings } = transport; + switch (transport.kind) { + case ZIBRI_BACKUP_TRANSPORT_KINDS.S3: { + const style: S3AddressingStyle | undefined = S3_ADDRESSING_STYLES.find(candidate => candidate === settings['addressingStyle']); + return [ + { label: this.labels.endpoint, value: this.readString(settings, 'endpoint') }, + { label: this.labels.bucket, value: this.readString(settings, 'bucket') }, + { label: this.labels.region, value: this.readString(settings, 'region') }, + { label: this.labels.prefix, value: this.readString(settings, 'prefix') || this.labels.topOfBucket }, + { label: this.labels.addressingStyle, value: style == undefined ? '' : this.labels.addressingStyles[style] }, + { label: this.labels.accessKeyId, value: this.readString(settings, 'accessKeyId') } + ]; + } + case ZIBRI_BACKUP_TRANSPORT_KINDS.SFTP: { + const port: unknown = settings['port']; + return [ + { label: this.labels.host, value: this.readString(settings, 'host') }, + { label: this.labels.port, value: typeof port === 'number' ? String(port) : this.labels.defaultPort }, + { label: this.labels.username, value: this.readString(settings, 'username') }, + { label: this.labels.path, value: this.readString(settings, 'path') }, + { label: this.labels.hostKeyFingerprint, value: this.readString(settings, 'hostKeyFingerprint') } + ]; + } + case ZIBRI_BACKUP_TRANSPORT_KINDS.WEB_DAV: + case ZIBRI_BACKUP_TRANSPORT_KINDS.NEXTCLOUD: { + const connectionId: string = this.readString(settings, 'connectionId'); + const details: TransportDetail[] = [ + { label: this.labels.connection, value: this.connections().find(connection => connection.id === connectionId)?.name ?? connectionId }, + { label: this.labels.folder, value: this.readString(settings, 'folder') || this.labels.folderOfConnection } + ]; + if (transport.kind === ZIBRI_BACKUP_TRANSPORT_KINDS.WEB_DAV) { + return details; + } + return [ + ...details, + { label: this.labels.sharedWithUsers, value: this.readStrings(settings, 'sharedWithUsers').join(', ') || this.labels.nobody }, + { label: this.labels.sharedWithGroups, value: this.readStrings(settings, 'sharedWithGroups').join(', ') || this.labels.nobody } + ]; + } + default: { + return Object.entries(settings).map(([label, value]) => ({ label, value: typeof value === 'string' ? value : JSON.stringify(value) })); + } + } + } + + private resolveKindLabel(kind: string): string { + return this.labels.kinds[kind] ?? kind; + } + + private readString(settings: Record, key: string): string { + const value: unknown = settings[key]; + return typeof value === 'string' ? value : ''; + } + + private readStrings(settings: Record, key: string): string[] { + const value: unknown = settings[key]; + return Array.isArray(value) ? value.filter(item => typeof item === 'string') : []; + } + + private clearSecrets(): void { + this.secretAccessKey.set(''); + this.password.set(''); + this.privateKey.set(''); + this.passphrase.set(''); + } + + private sorted(transports: TenantBackupTransportModel[]): TenantBackupTransportModel[] { + return transports.sort((a, b) => a.name.localeCompare(b.name)); + } + + private focusAfterRender(findElement: () => HTMLElement | undefined): void { + afterNextRender({ write: () => findElement()?.focus() }, { injector: this.injector }); + } + + // the paragraphs of the message of the api, all of them, like each backup stored on a transport + private resolveErrorParagraphs(error: unknown): string[] { + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + const body: ErrorResponseBody | undefined = ErrorResponseUtilities.findErrorResponseBody(error); + if (body == undefined) { + return [this.labels.requestFailed]; + } + return body.paragraphs.length ? body.paragraphs : [body.message]; + } +} diff --git a/projects/ngx-backup/tenant-transports/tenant-transports.stories.ts b/projects/ngx-backup/tenant-transports/tenant-transports.stories.ts new file mode 100644 index 0000000..5b25f7d --- /dev/null +++ b/projects/ngx-backup/tenant-transports/tenant-transports.stories.ts @@ -0,0 +1,63 @@ +import { Meta, StoryObj } from '@storybook/angular'; + +import { BackupStoryUtilities } from '../fixtures/backup-story.utilities'; +import { BACKUP_TRANSPORT_IDS, BACKUP_TRANSPORT_SECRET, BACKUP_TRANSPORTS, BUCKET_BACKUPS, TAPE_TRANSPORT } from '../fixtures/backup.fixtures'; +import { TenantTransportsComponent } from './tenant-transports.component'; + +const meta: Meta = { + title: 'Backup/Tenant transports', + component: TenantTransportsComponent, + render: args => ({ + props: args, + template: '' + }) +}; +export default meta; + +type Story = StoryObj; + +// adds, changes and removes storage of every kind, and every secret passes the test. +export const List: Story = { + args: { canManage: true }, + decorators: [BackupStoryUtilities.provideBackend()] +}; + +// lists the storage without the controls that change it, like without `backup-transports.manage`. +export const ReadOnly: Story = { + args: { canManage: false }, + decorators: [BackupStoryUtilities.provideBackend()] +}; + +export const Empty: Story = { + args: { canManage: true }, + decorators: [BackupStoryUtilities.provideBackend({ transports: [] })] +}; + +export const Loading: Story = { + args: { canManage: true }, + decorators: [BackupStoryUtilities.provideBackend({ loading: true })] +}; + +export const LoadingFailed: Story = { + args: { canManage: true }, + decorators: [BackupStoryUtilities.provideBackend({ unavailable: true })] +}; + +// the storage refuses every secret but `storage-secret`, so adding a bucket or an SFTP server, or setting a new secret, +// shows the message of the api. +export const AddRefused: Story = { + args: { canManage: true }, + decorators: [BackupStoryUtilities.provideBackend({ secret: BACKUP_TRANSPORT_SECRET })] +}; + +// removing the bucket, or changing its settings, shows the backups the api names; the others are removed. +export const DeleteRefused: Story = { + args: { canManage: true }, + decorators: [BackupStoryUtilities.provideBackend({ backups: { [BACKUP_TRANSPORT_IDS.bucket]: BUCKET_BACKUPS } })] +}; + +// a tape library of a kind of the app the view doesn't know, whose settings show as they are, and only its name changes. +export const OtherKind: Story = { + args: { canManage: true }, + decorators: [BackupStoryUtilities.provideBackend({ transports: [...BACKUP_TRANSPORTS, TAPE_TRANSPORT] })] +}; diff --git a/projects/ngx-backup/test-setup.ts b/projects/ngx-backup/test-setup.ts new file mode 100644 index 0000000..6d36f89 --- /dev/null +++ b/projects/ngx-backup/test-setup.ts @@ -0,0 +1,4 @@ +import { DialogTestingUtilities } from 'testing/dialog'; + +// jsdom has no modal dialogs, which ask before a transport is removed. +DialogTestingUtilities.addModalDialogs(); diff --git a/projects/ngx-backup/tsconfig.lib.json b/projects/ngx-backup/tsconfig.lib.json new file mode 100644 index 0000000..dcadbca --- /dev/null +++ b/projects/ngx-backup/tsconfig.lib.json @@ -0,0 +1,18 @@ +/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ +/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ +{ + "compilerOptions": { + "declaration": true, + "declarationMap": true, + "outDir": "../../out-tsc/lib", + // the paths of the workspace point to the sources of the other libraries, which the build would then compile + // into this one. Without them, they resolve from node_modules like for a consumer, so ui, ngx-error-handling + // and ngx-web-dav have to be built first. + "paths": {}, + "types": ["@angular/localize"] + }, + // the fixtures are the fake api the specs and stories render against, never part of the package. + "exclude": ["**/*.spec.ts", "**/*.stories.ts", "fixtures/**", "test-setup.ts"], + "extends": "../../tsconfig.json", + "include": ["**/*.ts"] +} diff --git a/projects/ngx-backup/tsconfig.lib.prod.json b/projects/ngx-backup/tsconfig.lib.prod.json new file mode 100644 index 0000000..a416f78 --- /dev/null +++ b/projects/ngx-backup/tsconfig.lib.prod.json @@ -0,0 +1,11 @@ +/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ +/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ +{ + "angularCompilerOptions": { + "compilationMode": "partial" + }, + "compilerOptions": { + "declarationMap": false + }, + "extends": "./tsconfig.lib.json" +} diff --git a/projects/ngx-backup/tsconfig.spec.json b/projects/ngx-backup/tsconfig.spec.json new file mode 100644 index 0000000..7a9cb00 --- /dev/null +++ b/projects/ngx-backup/tsconfig.spec.json @@ -0,0 +1,10 @@ +/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ +/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ +{ + "compilerOptions": { + "outDir": "../../out-tsc/spec", + "types": ["vitest/globals", "@angular/localize"] + }, + "extends": "../../tsconfig.json", + "include": ["**/*.d.ts", "**/*.spec.ts", "fixtures/**/*.ts", "test-setup.ts"] +} diff --git a/projects/ngx-bank/CHANGELOG.md b/projects/ngx-bank/CHANGELOG.md new file mode 100644 index 0000000..3e836f4 --- /dev/null +++ b/projects/ngx-bank/CHANGELOG.md @@ -0,0 +1,14 @@ +# Changelog + +## 22.4.0 + +First release. + +### Features +- `@service-soft/ngx-bank/api`: `BankService`, its config and the utilities for amounts, IBANs, days and matches. +- `@service-soft/ngx-bank/bank-accounts`: the bank accounts, adding one with its IBAN checked. +- `@service-soft/ngx-bank/statement-upload`: uploading a CAMT.053 statement. +- `@service-soft/ngx-bank/bank-statements`: the statements with their balances. +- `@service-soft/ngx-bank/bank-transactions`: the transactions, the details of one, and reversing its match. +- `@service-soft/ngx-bank/bank-matching`: reviewing the suggested matches as approval requests, and matching by hand. +- The German translation of the texts ships with the package (`locale/messages.de.xlf`). diff --git a/projects/ngx-bank/LICENSE b/projects/ngx-bank/LICENSE new file mode 100644 index 0000000..959f86e --- /dev/null +++ b/projects/ngx-bank/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Tim Fabian + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/projects/ngx-bank/README.md b/projects/ngx-bank/README.md new file mode 100644 index 0000000..bfe65fc --- /dev/null +++ b/projects/ngx-bank/README.md @@ -0,0 +1,203 @@ +# ngx-bank +The views of the bank accounts your api keeps: adding an account, uploading a CAMT.053 statement, the statements with their balances, the transactions with what of each is open, and matching a transaction with what it pays. A suggested match is an approval request, which a person reviews and approves with [@service-soft/ngx-approval-requests](https://www.npmjs.com/package/@service-soft/ngx-approval-requests) before it is recorded, and a match of the user is proposed the same way. Every amount is written in the language of your app with the currency of its account. + +It reads and sends the bank data through the models of [zibri-contract](https://www.npmjs.com/package/zibri-contract), like `BankTransactionModel` and `BankMatchModel`, which any api can answer; the bank plugin of [zibri](https://www.npmjs.com/package/zibri) is one that does. It is built on [@service-soft/ui](https://www.npmjs.com/package/@service-soft/ui), shows the messages of the api with [@service-soft/ngx-error-handling](https://www.npmjs.com/package/@service-soft/ngx-error-handling), and is styled with Tailwind CSS. + +# Table of Contents +- [ngx-bank](#ngx-bank) +- [Table of Contents](#table-of-contents) +- [Requirements](#requirements) +- [Setup](#setup) +- [Days and amounts](#days-and-amounts) +- [The bank accounts](#the-bank-accounts) +- [The statement upload](#the-statement-upload) +- [The statements](#the-statements) +- [The transactions](#the-transactions) +- [The matching](#the-matching) + - [Matching by hand](#matching-by-hand) +- [The routes of the api](#the-routes-of-the-api) +- [Configuration](#configuration) + - [Translating](#translating) +- [License](#license) + +# Requirements +Angular 22 with `@angular/localize`, which [translates the texts](#translating), and `@angular/aria`, which the selects are built on, and Tailwind CSS 4. The models come from [zibri-contract](https://www.npmjs.com/package/zibri-contract) 3.3 or later. The matching shows the review of a suggestion with `@service-soft/ngx-approval-requests/approval-request`, which shows its changes with [@service-soft/ngx-change-sets](https://www.npmjs.com/package/@service-soft/ngx-change-sets). + +```sh +npm install @service-soft/ngx-bank @service-soft/ngx-approval-requests @service-soft/ngx-change-sets @service-soft/ngx-error-handling @service-soft/ui @angular/aria zibri-contract +ng add @angular/localize +``` + +# Setup +Your Tailwind generates the css. Add the packages to your global stylesheet: + +```css +@import "tailwindcss"; +@import "@service-soft/ui"; +@import "@service-soft/ngx-error-handling"; +@import "@service-soft/ngx-change-sets"; +@import "@service-soft/ngx-approval-requests"; +@import "@service-soft/ngx-bank"; +``` + +Give it the url of the bank routes of your api, the urls of its invoicing and bookkeeping routes, where the invoices, expenses and accounts of the books a user matches a transaction with are found, and the url of its approval request routes, where the suggestions are decided and the matches of the user are proposed, and `HttpClient`, which it sends the requests with: + +```ts +// app.config.ts +import { provideHttpClient } from '@angular/common/http'; +import { provideRouter, withComponentInputBinding } from '@angular/router'; +import { provideApprovalRequestsConfig } from '@service-soft/ngx-approval-requests/api'; +import { provideBankConfig } from '@service-soft/ngx-bank/api'; + +export const appConfig: ApplicationConfig = { + providers: [ + provideHttpClient(), + provideRouter(routes, withComponentInputBinding()), + provideBankConfig({ + baseUrl: 'https://api.example.com/bank', + invoicingUrl: 'https://api.example.com/invoicing', + bookkeepingUrl: 'https://api.example.com/bookkeeping' + }), + provideApprovalRequestsConfig({ + baseUrl: 'https://api.example.com/approval-requests', + actions: { 'bank.match': 'Match a bank transaction' } + }) + ] +}; +``` + +```ts +// app.routes.ts +export const routes: Routes = [ + { + path: 'bank/accounts', + title: 'Bank accounts', + loadComponent: async () => (await import('@service-soft/ngx-bank/bank-accounts')).BankAccountsComponent + }, + { + path: 'bank/upload', + title: 'Import a statement', + loadComponent: async () => (await import('@service-soft/ngx-bank/statement-upload')).StatementUploadComponent + }, + { + path: 'bank/statements', + title: 'Statements', + loadComponent: async () => (await import('@service-soft/ngx-bank/bank-statements')).BankStatementsComponent + }, + { + path: 'bank/transactions', + title: 'Transactions', + loadComponent: async () => (await import('@service-soft/ngx-bank/bank-transactions')).BankTransactionsComponent + } +]; +``` + +Every view is an entry point of its own, so each page loads only its own code. They read the `BankService` and the config of `@service-soft/ngx-bank/api`. The headline of each page is yours, like the `title` of its route; the headings inside the views start at the `headingLevel` of the config, `2` by default. The views load again after every change the app makes through the `BankService`, like an added account or an imported statement, and after every decision of the `ApprovalRequestService`. + +# Days and amounts +The day a transaction was booked on is held by the api as its midnight UTC, and the views show it as it is, written with `Intl` in the `LOCALE_ID` of your app like the date inputs write it, `11/30/2026` in `en-US` or `30.11.2026` in `de` (`dateFormat` of the config changes the options); the date inputs of ui hold the midnight of a day in the time zone of the browser, so a period sends the days the user chose wherever the browser is. The period of a statement and the moment it was imported are shown in the time zone of the browser. `BankDayUtilities` of the api entry point converts both ways for code of your own. + +Amounts are the decimal strings of the api, like `'1190'` or `'-9.9'`, negative for money paid. The views write them with `Intl` in the `LOCALE_ID` of your app, in the currency of the account they are of, with its minor units, like `€1,190.00` in `en-US` or `1.190,00 €` in `de`. What of a transaction is open is its amount without the sign, less what its matches match, a reversal matching a negative amount; the views show it with the sign of the transaction, like its amount, so money paid is open as `-€850.00`. The list of the transactions shows what the api answers for each; a transaction opened, and the matching, which load the matches of their one transaction anyway, add it up from those in minor units. `BankAmountUtilities` and `BankMatchUtilities` have the same for your own code. + +# The bank accounts +```html + +``` + +The accounts by name, with their IBAN in groups of four, and a form that adds one: its IBAN, its name and its currency, the `defaultCurrency` of the config at first. The browser checks the IBAN before it is sent, its form and its check digits (ISO 13616), and shows the error at the input like any other, so an IBAN with a typing error never reaches the api. `BankIbanUtilities` checks and writes IBANs for your own code. The api stores the IBAN in capitals and without spaces, and refuses one the tenant has an account of already, which the form shows. + +A statement is imported into the account of its IBAN, so add an account before its first statement. + +# The statement upload +```html + +``` + +Takes a CAMT.053 file, the statement export every SEPA bank offers, and imports every statement of it. It then shows what was stored: the statements with their account, period and opening and closing balance, how many statements and transactions were new, and how many were imported before and skipped, so the same file twice, or files whose periods overlap, store each transaction once. A file the api refuses imports nothing, and the view shows the message of the api, like for a statement of an IBAN the tenant has no account of, or one that doesn't continue the statement imported before it, which names the statement to import first. + +# The statements +```html + +``` + +The statements of the account chosen, the first by name at first, the latest period first, a page at a time, with their opening and closing balances. A statement opened from the table shows its period, balances, format and file, and the transactions first imported with it; its heading takes the focus. + +# The transactions +```html + +``` + +The transactions of an account, or of every account, booked in a period, the latest first, a page at a time, each with its amount, what of it is open, and whether it is open, partly matched or matched. The period is the current month at first, or the one you bind with `[(period)]`; an empty period shows every transaction. The status filter shows the transactions with something open, or those matched in full. The api filters and pages them, `GET /transactions` with the account, the days, the status and the page, and answers what of each is open, so the view loads one page whatever the period; a filter starts over on the first page. The api reads the matches of every transaction of the other filters for a status, so a long history is best narrowed by the period. + +A transaction opened from the table loads its matches, `GET /matches?transactionId`, and shows what the bank says of it, like its counterparty, IBAN, payment reference and references, and its matches, each with its target, amount, the payment difference it accepts as paid of an invoice, and who confirmed it when. A match is reversed after a confirmation: the api records a match of the negative amount, and what it matched is open again on both sides. Neither a reversal nor a match reversed already can be reversed. Below is the [matching](#the-matching) of the transaction. It stays open while the table shows another page or loads again, like after a decision. + +# The matching +```html + +``` + +`BankMatchingComponent` of `@service-soft/ngx-bank/bank-matching` is the matching of a transaction, as the transactions show it below an opened one, or anywhere you have a `BankTransactionModel`: what of it is open, from its matches, and the matches the api suggests for it that wait for a decision, `GET /transactions/:id/suggestions`, the most confident first. Each shows what its target is, the summary of the api, the amount, its score and the reasons for it, and the payment difference approving it accepts as paid of its invoice, like a cent a customer paid short. A match with an account of the books, like a deposit of share capital, is marked as one a person confirms, as the api never approves one on its own, whatever its score. + +Review opens the review of the approval request of the suggestion in [@service-soft/ngx-approval-requests](https://www.npmjs.com/package/@service-soft/ngx-approval-requests) below the suggestions, by its `requestId`, headed one level below them, where a person approves or rejects it with a note after confirming. Once decided, the matching loads again, and the review stays with its outcome. Suggest matches again has the api suggest matches for every transaction not matched in full, like once the invoice of a payment was created after its statement was imported. + +## Matching by hand +The form below the suggestions proposes a match of the user: the type of the target, an invoice, an expense or an account of the books, the target, the amount, what of the transaction is open at first, and why. The amount is at most what is open. The match is proposed as an approval request of the `matchAction` of the config, `'bank.match'`, with a `BankMatchInputModel` as its input, which another person who confirms matches approves; the api refuses the proposer approving their own. + +The targets are searched by what the user typed, its number or the name of whom it is of, and each shows its number and that name: + +- **Invoices**: the issued invoices with something open, `GET /invoices?search&issued=true&open=true&type=INVOICE` of the invoicing routes, at the `invoicingUrl`. +- **Expenses**: `GET /expenses?search` of the bookkeeping routes, at the `bookkeepingUrl`. +- **Accounts of the books**: the open accounts, `GET /accounts?search&open=true` of the bookkeeping routes, whose number starts with the search or whose name contains it. + +The matches of a transaction name their target the same way, each target once, by `GET /invoices/:id`, `GET /expenses/:id` and `GET /accounts/:id`, a closed account as well. A target whose request fails, like one the api has no more, shows its id, and the others their names. `findTargets` and `resolveTargetNames` of the `BankService` do the same for your own code. Who confirmed a match is named by `resolveActorName` of the `ApprovalRequestService`, see [the names of users](https://www.npmjs.com/package/@service-soft/ngx-approval-requests#the-names-of-users). + +# The routes of the api +The `BankService` sends these requests, those of the bank below the `baseUrl`, as the `BankController` of the bank plugin of zibri answers them, those of the invoices below the `invoicingUrl`, as its `InvoicingController` answers them, and those of the expenses and the accounts of the books below the `bookkeepingUrl`, as its `BookkeepingController` answers them. Those of the approval requests go through the `ApprovalRequestService` of ngx-approval-requests. The dates of the models arrive as the strings of json, and the services answer them as `Date`, as the models declare them. + +| Request | Answers | Used by | Permission in zibri | +|---|---|---|---| +| `GET /accounts` | every `BankAccountModel`, by name | the accounts, the upload, the statements, the transactions | `bank.transactions.read` | +| `POST /accounts` with a `NewBankAccountModel` | the `BankAccountModel` added | the accounts | `bank.accounts.manage` | +| `POST /statements` with the file as the part `file` of a multipart body | the `BankStatementImportModel` | the upload | `bank.statements.import` | +| `GET /statements?page&limit&accountId` | a `PaginationResult`, the latest period first | the statements | `bank.transactions.read` | +| `GET /transactions?page&limit&accountId&statementId&from&until&status` | a `PaginationResult`, each transaction with its `openAmount`, the latest booking first, `BankTransactionQueryModel` as its query | the transactions, the statements | `bank.transactions.read` | +| `GET /transactions/:id/suggestions` | every `BankTransactionSuggestionModel` waiting for a decision, the most confident first | the matching | `bank.transactions.read` | +| `GET /matches?page&limit&transactionId` | a `PaginationResult`, the latest confirmed first | an opened transaction, the matching | `bank.matches.read` | +| `POST /matches/:id/reversal` | the `BankMatchModel` reversing it | an opened transaction | `bank.matches.confirm` | +| `POST /matches/suggestions` | the `ApprovalRequestDetailsModel`s proposed | the matching | `bank.matches.suggest` | +| invoicing: `GET /invoices?page&limit&search&issued=true&open=true&type=INVOICE` | a `PaginationResult`, `InvoiceQueryModel` as its query | the matching by hand | `invoicing.invoices.read` | +| invoicing: `GET /invoices/:id` | the `InvoiceModel` | the matches of an opened transaction | `invoicing.invoices.read` | +| bookkeeping: `GET /expenses?page&limit&search` | a `PaginationResult`, `ExpenseQueryModel` as its query | the matching by hand | `bookkeeping.read` | +| bookkeeping: `GET /expenses/:id` | the `ExpenseModel` | the matches of an opened transaction | `bookkeeping.read` | +| bookkeeping: `GET /accounts?search&open=true` | the open `BookkeepingAccountModel`s of the search, by number, `BookkeepingAccountQueryModel` as its query | the matching by hand | `bookkeeping.read` | +| bookkeeping: `GET /accounts/:id` | the `BookkeepingAccountModel`, closed or not | the matches of an opened transaction | `bookkeeping.read` | +| approval requests: `GET /:id` | the `ApprovalRequestDetailsModel` of a suggestion | the review in the matching | `approval-requests.read` | +| approval requests: `POST /` with the action, a `BankMatchInputModel` as the input, and the reason | the `ApprovalRequestDetailsModel` proposed | the matching by hand | `bank.matches.suggest` | + +Deciding a suggestion in the review takes `approval-requests.decide` and `bank.matches.confirm`. A page of the bank, invoicing and bookkeeping routes holds at most 100 rows, so keep `pageSize` at 100 or below. Days in a query are written as `2026-11-30`. Change the paths with `paths` of the config. Every route answers the bank data of the active tenant, which the `authInterceptor` of ngx-auth sends. `revision` of the `BankService` changes with every change the app makes through it; read it in the params of a resource of your own to load it again after each. + +# Configuration +`provideBankConfig` sets the `baseUrl` and the defaults of the views, for the whole app, or for a part of it when you add it to the providers of a component or route. Values you leave out keep the ones of the parent, single paths, labels and dialog texts included: + +| Option | Default | +|---|---| +| `baseUrl` | required — the url of the bank routes of your api | +| `invoicingUrl` | required to match with invoices — the url of the invoicing routes of your api | +| `bookkeepingUrl` | required to match with expenses and accounts of the books — the url of the bookkeeping routes of your api | +| `paths` | the paths of the table above, like `{ transactions: 'transactions', transactionSuggestions: 'suggestions', invoices: 'invoices', expenses: 'expenses', bookkeepingAccounts: 'accounts' }` | +| `pageSize` | `20` — how many statements or transactions a page of a table has, at most 100 | +| `dateFormat` | `{ year: 'numeric', month: '2-digit', day: '2-digit' }` — the days, as the options of `Intl.DateTimeFormat` in the `LOCALE_ID`; replaced as a whole | +| `headingLevel` | `2` — the level of the headings inside the views; their sections are headed one level below | +| `defaultCurrency` | `'EUR'` — the currency a new account starts with | +| `matchAction` | `'bank.match'` — the name of the approval action whose requests match a transaction | +| `matchReasons` | what the reasons of zibri's suggestions are called, like `{ INVOICE_NUMBER: 'The payer names the invoice number' }`; a reason without one shows its name; replaced as a whole | +| `labels` | the English texts of the views, by view: `common`, `accounts`, `upload`, `statements`, `transactions` and `matching` | +| `reverseMatchConfirmDialogData` | the title, text and buttons of the question before reversing a match | + +## Translating +The default texts are `$localize` with an id of their own, like `@@ngx-bank.api.transactions.reverse`, so `ng extract-i18n` puts them into the messages of your app, and you translate them like its own texts. The library needs `@angular/localize` for that, `ng add @angular/localize`, also in an app of one language. A build with `localize` fills the texts in, so no part of `@angular/localize` reaches the browser. The defaults are made once the config is injected, so translations an app loads at runtime with `loadTranslations` apply as well. A text of `provideBankConfig` replaces the default in every language. So translate a default in your messages, and change it in the config only to say something else. + +German ships with the library: `locale/messages.de.xlf` of the package is an XLIFF 1.2 file with a German target for each of its texts, and its `package.json` names it in `"translations": { "de": "./locale/messages.de.xlf" }`. A merge of the translations of an app's dependencies reads that field and fills these targets into the German messages of the app, so German needs no translation of your own. The summaries of the suggestions, the names of the accounts and the payment references are data of your api, in the language it answers in. + +# License +MIT. \ No newline at end of file diff --git a/projects/ngx-bank/api/bank-accounts-labels.model.ts b/projects/ngx-bank/api/bank-accounts-labels.model.ts new file mode 100644 index 0000000..2ad9dc0 --- /dev/null +++ b/projects/ngx-bank/api/bank-accounts-labels.model.ts @@ -0,0 +1,33 @@ +/** + * The texts of the bank accounts, to translate them. + */ +export type BankAccountsLabels = { + /** + * What screen readers call the table of the accounts. + */ + accounts: string, + /** + * The heading of the form that adds an account, and its button. + */ + add: string, + /** + * The hint below the IBAN. + */ + ibanHint: string, + /** + * The error of an IBAN whose check digits are wrong. + */ + invalidIban: string, + /** + * The hint below the name. + */ + nameHint: string, + /** + * The hint below the currency. + */ + currencyHint: string, + /** + * What the view says once it added an account. + */ + added: (name: string) => string +}; diff --git a/projects/ngx-bank/api/bank-amount.utilities.spec.ts b/projects/ngx-bank/api/bank-amount.utilities.spec.ts new file mode 100644 index 0000000..eeab76f --- /dev/null +++ b/projects/ngx-bank/api/bank-amount.utilities.spec.ts @@ -0,0 +1,28 @@ +import { describe, expect, test } from 'vitest'; + +import { BankAmountUtilities } from './bank-amount.utilities'; + +describe('BankAmountUtilities', () => { + test('writes the decimal strings of the api in the language of the app with the currency of the account', () => { + expect(BankAmountUtilities.format('1190', BankAmountUtilities.resolveFormat('EUR', 'en-US'))).toBe('€1,190.00'); + expect(BankAmountUtilities.format('-9.9', BankAmountUtilities.resolveFormat('EUR', 'en-US'))).toBe('-€9.90'); + expect(BankAmountUtilities.format('1190', BankAmountUtilities.resolveFormat('JPY', 'en-US'))).toBe('¥1,190'); + }); + + test('adds up amounts in minor units without the rounding errors of decimals', () => { + const fractionDigits: number = BankAmountUtilities.resolveFractionDigits('EUR'); + const sum: number = ['0.1', '0.2'].reduce((total, amount) => total + BankAmountUtilities.resolveMinorUnits(amount, fractionDigits), 0); + + expect(fractionDigits).toBe(2); + expect(BankAmountUtilities.resolveFractionDigits('JPY')).toBe(0); + expect(BankAmountUtilities.resolveDecimal(sum, fractionDigits)).toBe('0.30'); + expect(BankAmountUtilities.resolveMinorUnits(12.3, fractionDigits)).toBe(1230); + expect(BankAmountUtilities.getAbsolute('-9.9')).toBe('9.9'); + }); + + test('gives what is open the sign of its transaction, and nothing open none', () => { + expect(BankAmountUtilities.getSigned('850', '-850')).toBe('-850'); + expect(BankAmountUtilities.getSigned('300', '800')).toBe('300'); + expect(BankAmountUtilities.getSigned('0.00', '-850')).toBe('0.00'); + }); +}); \ No newline at end of file diff --git a/projects/ngx-bank/api/bank-amount.utilities.ts b/projects/ngx-bank/api/bank-amount.utilities.ts new file mode 100644 index 0000000..e2a3740 --- /dev/null +++ b/projects/ngx-bank/api/bank-amount.utilities.ts @@ -0,0 +1,79 @@ +/** + * The amounts of the bank: the api writes each as a decimal string in the currency of its account, like '1190' or + * '-9.9', and the views write them in the language of the app with that currency. Amounts that are added up, like what + * of a transaction its matches leave open, are added in minor units, which have no rounding errors. + */ +export abstract class BankAmountUtilities { + /** + * Resolves how amounts of a currency are written in a language. + * @param currency - The currency, as an ISO 4217 code like 'EUR'. + * @param locale - The language, like the LOCALE_ID of the app. + * @returns The format, with the minor units of the currency, like 2 decimals for EUR. + */ + static resolveFormat(currency: string, locale: string): Intl.NumberFormat { + return new Intl.NumberFormat(locale, { style: 'currency', currency }); + } + + /** + * Formats an amount of the api. + * @param amount - The decimal string, like '1190' or '-9.9'. + * @param format - The format of the currency, from resolveFormat. + * @returns The amount as it shows, like '€1,190.00'. + */ + static format(amount: string, format: Intl.NumberFormat): string { + // a number keeps 15 significant digits, which is every amount of a bank account of a small company to the cent. + return format.format(Number(amount)); + } + + /** + * Resolves the decimals of the minor unit of a currency. + * @param currency - The currency, as an ISO 4217 code like 'EUR'. + * @returns The decimals, like 2 for EUR and 0 for JPY. + */ + static resolveFractionDigits(currency: string): number { + // Intl knows the minor units from ISO 4217, so they aren't kept in a table of our own. + return new Intl.NumberFormat('en', { style: 'currency', currency }).resolvedOptions().maximumFractionDigits ?? 2; + } + + /** + * Resolves an amount in minor units, which add up without the rounding errors of decimals. + * @param amount - The amount, a decimal string of the api like '12.3', or a number typed into an input. + * @param fractionDigits - The decimals of the currency. + * @returns The amount in minor units, like 1230. + */ + static resolveMinorUnits(amount: string | number, fractionDigits: number): number { + return Math.round(Number(amount) * (10 ** fractionDigits)); + } + + /** + * Resolves the decimal string of an amount in minor units, as the api takes it. + * @param minorUnits - The amount in minor units, like 1230. + * @param fractionDigits - The decimals of the currency. + * @returns The decimal string, like '12.30'. + */ + static resolveDecimal(minorUnits: number, fractionDigits: number): string { + return (minorUnits / (10 ** fractionDigits)).toFixed(fractionDigits); + } + + /** + * Gets an amount of the api without its sign. + * @param amount - The decimal string, like '-9.9'. + * @returns The amount without a minus, like '9.9'. + */ + static getAbsolute(amount: string): string { + const trimmed: string = amount.trim(); + return trimmed.startsWith('-') ? trimmed.slice(1) : trimmed; + } + + /** + * Gets what of a transaction is open with the sign of the transaction, so it shows like its amount: negative for + * money paid. The api, and resolveOpenAmount of BankMatchUtilities, answer it without a sign. + * @param open - What is open, without a sign, like '850'. + * @param amount - The amount of the transaction, like '-850'. + * @returns What is open with the sign of the amount, like '-850', and nothing open as it is. + */ + static getSigned(open: string, amount: string): string { + const absolute: string = this.getAbsolute(open); + return amount.trim().startsWith('-') && Number(absolute) !== 0 ? `-${absolute}` : absolute; + } +} diff --git a/projects/ngx-bank/api/bank-common-labels.model.ts b/projects/ngx-bank/api/bank-common-labels.model.ts new file mode 100644 index 0000000..1ac2dc8 --- /dev/null +++ b/projects/ngx-bank/api/bank-common-labels.model.ts @@ -0,0 +1,103 @@ +import { BankMatchTargetType } from 'zibri-contract'; + +/** + * The texts several views of the bank show, to translate them. + */ +export type BankCommonLabels = { + /** + * A bank account, like the select of the account whose statements show. + */ + account: string, + /** + * The option of the account filter that shows every account. + */ + allAccounts: string, + /** + * The IBAN of an account. + */ + iban: string, + /** + * What an account is called. + */ + name: string, + /** + * The currency of an account. + */ + currency: string, + /** + * The day the bank booked a transaction. + */ + bookingDate: string, + /** + * The day the money of a transaction counts as received or paid. + */ + valueDate: string, + /** + * Who paid or was paid. + */ + counterparty: string, + /** + * The IBAN of who paid or was paid. + */ + counterpartyIban: string, + /** + * The text the payer gave a transaction. + */ + remittanceInformation: string, + /** + * The reference the payer gave a payment. + */ + endToEndId: string, + /** + * The reference the bank gave a booking. + */ + bankReference: string, + /** + * An amount. + */ + amount: string, + /** + * What of a transaction is not matched yet. + */ + openAmount: string, + /** + * The days a list covers. + */ + period: string, + /** + * The first day of the period. + */ + periodStart: string, + /** + * The last day of the period. + */ + periodEnd: string, + /** + * The balance at the start of a statement. + */ + openingBalance: string, + /** + * The balance at the end of a statement. + */ + closingBalance: string, + /** + * What each type of target of a match is called, like 'Invoice'. + */ + targetTypes: Record, + /** + * What screen readers read while a view loads. + */ + loading: string, + /** + * What a view says when what it shows couldn't be loaded. + */ + loadingFailed: string, + /** + * What a view says when a request was refused without a message of the server, like without a connection. + */ + requestFailed: string, + /** + * What a view says when the tenant has no bank account yet. + */ + noAccounts: string +}; diff --git a/projects/ngx-bank/api/bank-config-changes.model.ts b/projects/ngx-bank/api/bank-config-changes.model.ts new file mode 100644 index 0000000..7f96a33 --- /dev/null +++ b/projects/ngx-bank/api/bank-config-changes.model.ts @@ -0,0 +1,39 @@ +import { ConfirmDialogData } from '@service-soft/ui/dialog'; + +import { BankConfig } from './bank-config.model'; +import { BankLabelsChanges } from './bank-labels-changes.model'; + +/** + * The values to change in the config of the bank. Everything is optional, including every single path, label and text + * of the confirm dialog, but the requests need the baseUrl once. + */ +export type BankConfigChanges = Partial> & { + /** + * The url of the bank routes of your api, like 'https://api.example.com/bank'. + */ + baseUrl?: string, + /** + * The url of the invoicing routes of your api, like 'https://api.example.com/invoicing', for matching with invoices. + */ + invoicingUrl?: string, + /** + * The url of the bookkeeping routes of your api, like 'https://api.example.com/bookkeeping', for matching with + * expenses and accounts of the books. + */ + bookkeepingUrl?: string, + /** + * The paths to change. + */ + paths?: Partial, + /** + * The labels to change, by the view that shows them. + */ + labels?: BankLabelsChanges, + /** + * The texts of the question before reversing a match to change. + */ + reverseMatchConfirmDialogData?: Partial +}; diff --git a/projects/ngx-bank/api/bank-config.model.ts b/projects/ngx-bank/api/bank-config.model.ts new file mode 100644 index 0000000..4d36a08 --- /dev/null +++ b/projects/ngx-bank/api/bank-config.model.ts @@ -0,0 +1,69 @@ +import { ConfirmDialogData } from '@service-soft/ui/dialog'; +import { HeadingLevel } from '@service-soft/ui/heading'; + +import { BankLabels } from './bank-labels.model'; +import { BankPaths } from './bank-paths.model'; + +/** + * Where the bank accounts are, and the values their views use. + */ +export type BankConfig = { + /** + * The url of the bank routes of your api, like 'https://api.example.com/bank'. Undefined until provideBankConfig + * sets it, which every request needs. + */ + baseUrl: string | undefined, + /** + * The url of the invoicing routes of your api, like 'https://api.example.com/invoicing', where the invoices a + * transaction is matched with by hand are found and named. Undefined until provideBankConfig sets it, which + * matching with an invoice needs. + */ + invoicingUrl: string | undefined, + /** + * The url of the bookkeeping routes of your api, like 'https://api.example.com/bookkeeping', where the expenses and + * the accounts of the books a transaction is matched with by hand are found and named. Undefined until + * provideBankConfig sets it, which matching with an expense or an account needs. + */ + bookkeepingUrl: string | undefined, + /** + * The paths of the routes below their urls. + */ + paths: BankPaths, + /** + * How many statements or transactions a page of a table has. + */ + pageSize: number, + /** + * How the days of the bank are shown, as the options of Intl.DateTimeFormat in the LOCALE_ID of the app. By default + * like the date inputs of ui write them: '12/31/2026' in 'en-US' or '31.12.2026' in 'de'. + */ + dateFormat: Intl.DateTimeFormatOptions, + /** + * The level of the headings inside the views, like the one of a transaction opened from the table. Their sections + * are headed one level below. + */ + headingLevel: HeadingLevel, + /** + * The currency a new account starts with, as an ISO 4217 code like 'EUR'. + */ + defaultCurrency: string, + /** + * The name of the approval action whose requests match a transaction, as your api registers it. The suggestions of + * a transaction are the pending requests of it, and a match of the user is proposed as one. + */ + matchAction: string, + /** + * What the reasons of a suggestion are called, by the name the api gives them, like + * `{ INVOICE_NUMBER: 'The payer names the invoice number' }`. A reason without one shows its name. Replaced as a + * whole by provideBankConfig. + */ + matchReasons: Record, + /** + * The texts of the views. + */ + labels: BankLabels, + /** + * The question before reversing a match. + */ + reverseMatchConfirmDialogData: ConfirmDialogData +}; diff --git a/projects/ngx-bank/api/bank-config.provider.ts b/projects/ngx-bank/api/bank-config.provider.ts new file mode 100644 index 0000000..58d07f0 --- /dev/null +++ b/projects/ngx-bank/api/bank-config.provider.ts @@ -0,0 +1,219 @@ +import { inject, InjectionToken, Provider } from '@angular/core'; +import { BankMatchTargetType } from 'zibri-contract'; + +import { BankConfigChanges } from './bank-config-changes.model'; +import { BankConfig } from './bank-config.model'; +import { BankLabelsChanges } from './bank-labels-changes.model'; +import { BankLabels } from './bank-labels.model'; + +/** + * The texts of the views when nothing changes them, as $localize, which an app translates like its own. + * @returns The default labels. + */ +function getDefaultBankLabels(): BankLabels { + return { + common: { + account: $localize`:@@ngx-bank.api.common.account:Account`, + allAccounts: $localize`:@@ngx-bank.api.common.allAccounts:All accounts`, + iban: $localize`:@@ngx-bank.api.common.iban:IBAN`, + name: $localize`:@@ngx-bank.api.common.name:Name`, + currency: $localize`:@@ngx-bank.api.common.currency:Currency`, + bookingDate: $localize`:@@ngx-bank.api.common.bookingDate:Booking date`, + valueDate: $localize`:@@ngx-bank.api.common.valueDate:Value date`, + counterparty: $localize`:@@ngx-bank.api.common.counterparty:Counterparty`, + counterpartyIban: $localize`:@@ngx-bank.api.common.counterpartyIban:IBAN of the counterparty`, + remittanceInformation: $localize`:@@ngx-bank.api.common.remittanceInformation:Payment reference`, + endToEndId: $localize`:@@ngx-bank.api.common.endToEndId:End-to-end reference`, + bankReference: $localize`:@@ngx-bank.api.common.bankReference:Reference of the bank`, + amount: $localize`:@@ngx-bank.api.common.amount:Amount`, + openAmount: $localize`:@@ngx-bank.api.common.openAmount:Open`, + period: $localize`:@@ngx-bank.api.common.period:Period`, + periodStart: $localize`:@@ngx-bank.api.common.periodStart:From`, + periodEnd: $localize`:@@ngx-bank.api.common.periodEnd:Until`, + openingBalance: $localize`:@@ngx-bank.api.common.openingBalance:Opening balance`, + closingBalance: $localize`:@@ngx-bank.api.common.closingBalance:Closing balance`, + targetTypes: { + [BankMatchTargetType.INVOICE]: $localize`:@@ngx-bank.api.common.targetTypes.invoice:Invoice`, + [BankMatchTargetType.EXPENSE]: $localize`:@@ngx-bank.api.common.targetTypes.expense:Expense`, + [BankMatchTargetType.ACCOUNT]: $localize`:@@ngx-bank.api.common.targetTypes.account:Account of the books` + }, + loading: $localize`:@@ngx-bank.api.common.loading:Loading`, + loadingFailed: $localize`:@@ngx-bank.api.common.loadingFailed:The bank data couldn't be loaded.`, + requestFailed: $localize`:@@ngx-bank.api.common.requestFailed:The request couldn't be sent. Please try again.`, + noAccounts: $localize`:@@ngx-bank.api.common.noAccounts:There is no bank account yet.` + }, + accounts: { + accounts: $localize`:@@ngx-bank.api.accounts.accounts:Bank accounts`, + add: $localize`:@@ngx-bank.api.accounts.add:Add a bank account`, + ibanHint: $localize`:@@ngx-bank.api.accounts.ibanHint:Like DE89 3704 0044 0532 0130 00`, + invalidIban: $localize`:@@ngx-bank.api.accounts.invalidIban:This is no valid IBAN. Check it for a typing error.`, + nameHint: $localize`:@@ngx-bank.api.accounts.nameHint:What you call the account, like "Business account"`, + currencyHint: $localize`:@@ngx-bank.api.accounts.currencyHint:The code of its currency, like EUR`, + added: name => $localize`:@@ngx-bank.api.accounts.added:The account ${name}:name: was added.` + }, + upload: { + file: $localize`:@@ngx-bank.api.upload.file:CAMT.053 file`, + fileHint: $localize`:@@ngx-bank.api.upload.fileHint:The statement export of your bank, an XML file`, + import: $localize`:@@ngx-bank.api.upload.import:Import`, + result: $localize`:@@ngx-bank.api.upload.result:Imported`, + statementsImported: $localize`:@@ngx-bank.api.upload.statementsImported:New statements`, + transactionsImported: $localize`:@@ngx-bank.api.upload.transactionsImported:New transactions`, + statementsSkipped: $localize`:@@ngx-bank.api.upload.statementsSkipped:Statements imported before`, + transactionsSkipped: $localize`:@@ngx-bank.api.upload.transactionsSkipped:Transactions imported before`, + statements: $localize`:@@ngx-bank.api.upload.statements:Statements of the file`, + nothingNew: $localize`:@@ngx-bank.api.upload.nothingNew:The file holds nothing that wasn't imported before.`, + imported: $localize`:@@ngx-bank.api.upload.imported:The file was imported.` + }, + statements: { + statements: $localize`:@@ngx-bank.api.statements.statements:Statements`, + statement: $localize`:@@ngx-bank.api.statements.statement:Statement`, + importedAt: $localize`:@@ngx-bank.api.statements.importedAt:Imported`, + format: $localize`:@@ngx-bank.api.statements.format:Format`, + file: $localize`:@@ngx-bank.api.statements.file:File`, + statementTitle: statement => $localize`:@@ngx-bank.api.statements.statementTitle:Statement ${statement}:statement:`, + transactions: statement => $localize`:@@ngx-bank.api.statements.transactions:Transactions of statement ${statement}:statement:` + }, + transactions: { + transactions: $localize`:@@ngx-bank.api.transactions.transactions:Transactions`, + periodHint: $localize`:@@ngx-bank.api.transactions.periodHint:Every transaction when empty`, + status: $localize`:@@ngx-bank.api.transactions.status:Status`, + allStatuses: $localize`:@@ngx-bank.api.transactions.allStatuses:All`, + open: $localize`:@@ngx-bank.api.transactions.open:Open`, + partlyMatched: $localize`:@@ngx-bank.api.transactions.partlyMatched:Partly matched`, + matched: $localize`:@@ngx-bank.api.transactions.matched:Matched`, + transactionTitle: day => $localize`:@@ngx-bank.api.transactions.transactionTitle:Transaction of ${day}:day:`, + matches: $localize`:@@ngx-bank.api.transactions.matches:Matches`, + noMatches: $localize`:@@ngx-bank.api.transactions.noMatches:The transaction is not matched yet.`, + difference: $localize`:@@ngx-bank.api.transactions.difference:Payment difference`, + confirmedBy: (name, day) => $localize`:@@ngx-bank.api.transactions.confirmedBy:Confirmed by ${name}:name: on ${day}:day:`, + reversal: $localize`:@@ngx-bank.api.transactions.reversal:Reversal`, + reversed: $localize`:@@ngx-bank.api.transactions.reversed:Reversed`, + reverse: $localize`:@@ngx-bank.api.transactions.reverse:Reverse`, + reverseMatch: target => $localize`:@@ngx-bank.api.transactions.reverseMatch:Reverse the match with ${target}:target:`, + matchReversed: target => $localize`:@@ngx-bank.api.transactions.matchReversed:The match with ${target}:target: was reversed.` + }, + matching: { + open: (open, amount) => $localize`:@@ngx-bank.api.matching.open:${open}:open: of ${amount}:amount: are open.`, + matchedInFull: $localize`:@@ngx-bank.api.matching.matchedInFull:The transaction is matched in full.`, + suggestions: $localize`:@@ngx-bank.api.matching.suggestions:Suggestions`, + noSuggestions: $localize`:@@ngx-bank.api.matching.noSuggestions:No suggestion waits for a decision.`, + score: score => $localize`:@@ngx-bank.api.matching.score:Score ${score}:score:`, + reasons: $localize`:@@ngx-bank.api.matching.reasons:Why`, + paymentDifference: $localize`:@@ngx-bank.api.matching.paymentDifference:Payment difference`, + needsPerson: $localize`:@@ngx-bank.api.matching.needsPerson:Confirmed by a person`, + needsPersonHint: $localize`:@@ngx-bank.api.matching.needsPersonHint:A match with an account of the books is never approved automatically.`, + review: $localize`:@@ngx-bank.api.matching.review:Review`, + reviewOf: summary => $localize`:@@ngx-bank.api.matching.reviewOf:Review: ${summary}:summary:`, + closeReview: $localize`:@@ngx-bank.api.matching.closeReview:Close the review`, + suggestAgain: $localize`:@@ngx-bank.api.matching.suggestAgain:Suggest matches again`, + suggested: $localize`:@@ngx-bank.api.matching.suggested:The matches were suggested again.`, + manual: $localize`:@@ngx-bank.api.matching.manual:Match by hand`, + targetType: $localize`:@@ngx-bank.api.matching.targetType:Match with`, + targetHint: $localize`:@@ngx-bank.api.matching.targetHint:Search by number or name`, + amountHint: open => $localize`:@@ngx-bank.api.matching.amountHint:At most ${open}:open:, what of the transaction is open`, + reason: $localize`:@@ngx-bank.api.matching.reason:Reason`, + reasonHint: $localize`:@@ngx-bank.api.matching.reasonHint:For the person who approves the match`, + propose: $localize`:@@ngx-bank.api.matching.propose:Propose the match`, + proposed: $localize`:@@ngx-bank.api.matching.proposed:The match was proposed. It is recorded once a person who confirms matches approves it.` + } + }; +} + +/** + * The values of the bank when nothing changes them. Their texts are $localize, which an app translates like its own, + * and resolved once the config is injected, so translations an app loads at runtime apply as well. + * @returns The default config. + */ +function getDefaultBankConfig(): BankConfig { + return { + baseUrl: undefined, + invoicingUrl: undefined, + bookkeepingUrl: undefined, + paths: { + accounts: 'accounts', + statements: 'statements', + transactions: 'transactions', + transactionSuggestions: 'suggestions', + matches: 'matches', + suggestions: 'matches/suggestions', + reversal: 'reversal', + invoices: 'invoices', + expenses: 'expenses', + bookkeepingAccounts: 'accounts' + }, + pageSize: 20, + // the parts of the date inputs of ui, so a day reads the same in a list as in an input. + dateFormat: { year: 'numeric', month: '2-digit', day: '2-digit' }, + headingLevel: 2, + defaultCurrency: 'EUR', + matchAction: 'bank.match', + matchReasons: { + INVOICE_NUMBER: $localize`:@@ngx-bank.api.matchReasons.invoiceNumber:The payer names the invoice number`, + DOCUMENT_NUMBER: $localize`:@@ngx-bank.api.matchReasons.documentNumber:The payment names the document number of the expense`, + AMOUNT: $localize`:@@ngx-bank.api.matchReasons.amount:The amount is what is open`, + COUNTERPARTY_NAME: $localize`:@@ngx-bank.api.matchReasons.counterpartyName:The counterparty has the name of the recipient or supplier`, + COUNTERPARTY_IBAN: $localize`:@@ngx-bank.api.matchReasons.counterpartyIban:The account of the payer paid the recipient before`, + ACCOUNT_RULE: $localize`:@@ngx-bank.api.matchReasons.accountRule:A rule of the books names the counterparty or the text` + }, + labels: getDefaultBankLabels(), + reverseMatchConfirmDialogData: { + title: $localize`:@@ngx-bank.api.reverseMatchConfirmDialogData.title:Reverse this match?`, + paragraphs: [$localize`:@@ngx-bank.api.reverseMatchConfirmDialogData.paragraphs:What it matched is open again on both sides, and is suggested again. The match itself is kept, and a reversal is recorded next to it. This can't be undone.`], + confirmButtonLabel: $localize`:@@ngx-bank.api.reverseMatchConfirmDialogData.confirmButtonLabel:Reverse`, + cancelButtonLabel: $localize`:@@ngx-bank.api.reverseMatchConfirmDialogData.cancelButtonLabel:Cancel`, + confirmButtonColor: 'error' + } + }; +} + +/** + * Merges the labels to change into the ones of the parent, view by view. + * @param parent - The labels of the parent injector. + * @param changes - The labels to change. + * @returns The merged labels. + */ +function mergeLabels(parent: BankLabels, changes: BankLabelsChanges | undefined): BankLabels { + return { + common: { ...parent.common, ...changes?.common }, + accounts: { ...parent.accounts, ...changes?.accounts }, + upload: { ...parent.upload, ...changes?.upload }, + statements: { ...parent.statements, ...changes?.statements }, + transactions: { ...parent.transactions, ...changes?.transactions }, + matching: { ...parent.matching, ...changes?.matching } + }; +} + +/** + * Where the bank accounts are, and the values their views use, below this injector. Change them with + * provideBankConfig. + */ +export const BANK_CONFIG: InjectionToken = new InjectionToken( + 'BANK_CONFIG', + { providedIn: 'root', factory: () => getDefaultBankConfig() } +); + +/** + * Sets where the bank accounts are, `{ baseUrl }`, and changes the values their views use, like the labels to translate + * them. Provide it in the application config for the whole app, or in a component or route for only that part of it. + * Values you leave out are taken from the parent injector, including single paths, labels and texts of the dialog. + * @param config - The values to change. + * @returns The provider for BANK_CONFIG. + */ +export function provideBankConfig(config: BankConfigChanges): Provider { + return { + provide: BANK_CONFIG, + useFactory: (): BankConfig => { + const parent: BankConfig = inject(BANK_CONFIG, { skipSelf: true, optional: true }) ?? getDefaultBankConfig(); + return { + ...parent, + ...config, + baseUrl: config.baseUrl ?? parent.baseUrl, + invoicingUrl: config.invoicingUrl ?? parent.invoicingUrl, + bookkeepingUrl: config.bookkeepingUrl ?? parent.bookkeepingUrl, + paths: { ...parent.paths, ...config.paths }, + labels: mergeLabels(parent.labels, config.labels), + reverseMatchConfirmDialogData: { ...parent.reverseMatchConfirmDialogData, ...config.reverseMatchConfirmDialogData } + }; + } + }; +} \ No newline at end of file diff --git a/projects/ngx-bank/api/bank-day.utilities.ts b/projects/ngx-bank/api/bank-day.utilities.ts new file mode 100644 index 0000000..7e93388 --- /dev/null +++ b/projects/ngx-bank/api/bank-day.utilities.ts @@ -0,0 +1,35 @@ +/** + * The days of the bank. The api holds the day a transaction was booked on as its midnight UTC, while the date inputs of + * ui hold the midnight of the day in the time zone of the browser. These convert between both, so a day stays the same + * day wherever the browser is. + */ +export abstract class BankDayUtilities { + /** + * Resolves the day of the bank of a date of an input. + * @param date - The date, at any time of its day in the time zone of the browser. + * @returns The same day at midnight UTC, as the api takes it. + */ + static resolveDay(date: Date): Date { + return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())); + } + + /** + * Gets a day as the api takes it in a query, like `2026-11-30`. + * @param day - The day, at midnight UTC. + * @returns The day in ISO format. + */ + static getQueryValue(day: Date): string { + return day.toISOString().slice(0, 10); + } + + /** + * Formats a day of the bank in a language, the same day in every time zone. + * @param day - The day, at midnight UTC. + * @param format - The options of Intl.DateTimeFormat, like `{ year: 'numeric', month: '2-digit', day: '2-digit' }`. + * @param locale - The locale, like the LOCALE_ID of the app. + * @returns The formatted day, like '11/30/2026' in 'en-US' or '30.11.2026' in 'de'. + */ + static format(day: Date, format: Intl.DateTimeFormatOptions, locale: string): string { + return new Intl.DateTimeFormat(locale, { ...format, timeZone: 'UTC' }).format(day); + } +} diff --git a/projects/ngx-bank/api/bank-iban.utilities.spec.ts b/projects/ngx-bank/api/bank-iban.utilities.spec.ts new file mode 100644 index 0000000..a88611a --- /dev/null +++ b/projects/ngx-bank/api/bank-iban.utilities.spec.ts @@ -0,0 +1,26 @@ +import { describe, expect, test } from 'vitest'; + +import { BankIbanUtilities } from './bank-iban.utilities'; + +describe('BankIbanUtilities', () => { + test('writes an IBAN as the api stores it, and in groups of four as it is printed', () => { + expect(BankIbanUtilities.normalize(' de89 3704 0044 0532 0130 00 ')).toBe('DE89370400440532013000'); + expect(BankIbanUtilities.format('DE89370400440532013000')).toBe('DE89 3704 0044 0532 0130 00'); + expect(BankIbanUtilities.format('AT611904300234573201')).toBe('AT61 1904 3002 3457 3201'); + }); + + test('accepts IBANs whose check digits are right, in any spacing and case', () => { + expect(BankIbanUtilities.isValid('DE89 3704 0044 0532 0130 00')).toBe(true); + expect(BankIbanUtilities.isValid('de02120300000000202051')).toBe(true); + expect(BankIbanUtilities.isValid('AT611904300234573201')).toBe(true); + }); + + test('refuses an IBAN with a typing error, and what is no IBAN at all', () => { + // two digits swapped + expect(BankIbanUtilities.isValid('DE89 3704 0044 0532 0103 00')).toBe(false); + expect(BankIbanUtilities.isValid('DE88 3704 0044 0532 0130 00')).toBe(false); + expect(BankIbanUtilities.isValid('DE89')).toBe(false); + expect(BankIbanUtilities.isValid('1234 5678 9012 3456 78')).toBe(false); + expect(BankIbanUtilities.isValid('DE89 3704 0044 0532 0130 0!')).toBe(false); + }); +}); \ No newline at end of file diff --git a/projects/ngx-bank/api/bank-iban.utilities.ts b/projects/ngx-bank/api/bank-iban.utilities.ts new file mode 100644 index 0000000..9b0bc50 --- /dev/null +++ b/projects/ngx-bank/api/bank-iban.utilities.ts @@ -0,0 +1,45 @@ +/** + * The IBANs of bank accounts: checked in the browser before an account is added, and shown in groups of four. + */ +export abstract class BankIbanUtilities { + /** + * Writes an IBAN in capitals and without spaces, as the api stores it. + * @param iban - The IBAN as typed, like 'de89 3704 0044 0532 0130 00'. + * @returns The IBAN, like 'DE89370400440532013000'. + */ + static normalize(iban: string): string { + return iban.replaceAll(/\s+/g, '').toUpperCase(); + } + + /** + * Writes an IBAN in groups of four, as it is printed. + * @param iban - The IBAN, in any spacing. + * @returns The IBAN, like 'DE89 3704 0044 0532 0130 00'. + */ + static format(iban: string): string { + return this.normalize(iban).replaceAll(/(.{4})(?=.)/g, '$1 '); + } + + /** + * Whether an IBAN is one: a country code, its check digits and up to 30 letters and digits, whose check digits + * prove it has no typing error (ISO 13616, modulo 97). + * @param iban - The IBAN, in any spacing and case. + * @returns True for a valid IBAN. + */ + static isValid(iban: string): boolean { + const normalized: string = this.normalize(iban); + if (!/^[A-Z]{2}\d{2}[A-Z\d]{11,30}$/.test(normalized)) { + return false; + } + // the country and the check digits move to the end, and every letter becomes its two digits, A as 10. + const digits: string = [...`${normalized.slice(4)}${normalized.slice(0, 4)}`] + .map(character => Number.parseInt(character, 36).toString()) + .join(''); + // the remainder digit by digit, as the number has far more digits than a number holds exactly. + let remainder: number = 0; + for (const digit of digits) { + remainder = ((remainder * 10) + Number(digit)) % 97; + } + return remainder === 1; + } +} diff --git a/projects/ngx-bank/api/bank-json.utilities.ts b/projects/ngx-bank/api/bank-json.utilities.ts new file mode 100644 index 0000000..f2d1498 --- /dev/null +++ b/projects/ngx-bank/api/bank-json.utilities.ts @@ -0,0 +1,66 @@ +import { BankMatchModel, BankStatementImportModel, BankStatementModel, BankTransactionDetailsModel, BankTransactionModel } from 'zibri-contract'; + +/** + * The models of the api as json answers them: its dates arrive as the strings of json, which the models of + * zibri-contract declare as Date. Each turns them into Date again. Only used by the BankService. + */ +export abstract class BankJsonUtilities { + /** + * Turns the dates of a statement into Date. + * @param statement - The statement, as json answers it. + * @returns The statement with Date. + */ + static toStatement(statement: BankStatementModel): BankStatementModel { + return { + ...statement, + retainUntil: new Date(statement.retainUntil), + issuedAt: new Date(statement.issuedAt), + periodStart: new Date(statement.periodStart), + periodEnd: new Date(statement.periodEnd), + openingBalanceDate: new Date(statement.openingBalanceDate), + closingBalanceDate: new Date(statement.closingBalanceDate), + importedAt: new Date(statement.importedAt) + }; + } + + /** + * Turns the dates of what an import stored into Date. + * @param result - The result of the import, as json answers it. + * @returns The result with Date. + */ + static toImport(result: BankStatementImportModel): BankStatementImportModel { + return { ...result, statements: result.statements.map(statement => this.toStatement(statement)) }; + } + + /** + * Turns the dates of a transaction into Date. + * @param transaction - The transaction, as json answers it. + * @returns The transaction with Date. + */ + static toTransaction(transaction: BankTransactionModel): BankTransactionModel { + return { + ...transaction, + bookingDate: new Date(transaction.bookingDate), + // null and absent stay as they are, as the model tells them apart. + valueDate: transaction.valueDate == undefined ? transaction.valueDate : new Date(transaction.valueDate) + }; + } + + /** + * Turns the dates of a transaction with what of it is open into Date. + * @param details - The transaction with what of it is open, as json answers it. + * @returns The transaction with Date. + */ + static toTransactionDetails(details: BankTransactionDetailsModel): BankTransactionDetailsModel { + return { ...details, transaction: this.toTransaction(details.transaction) }; + } + + /** + * Turns the dates of a match into Date. + * @param match - The match, as json answers it. + * @returns The match with Date. + */ + static toMatch(match: BankMatchModel): BankMatchModel { + return { ...match, confirmedAt: new Date(match.confirmedAt) }; + } +} diff --git a/projects/ngx-bank/api/bank-labels-changes.model.ts b/projects/ngx-bank/api/bank-labels-changes.model.ts new file mode 100644 index 0000000..4775b9f --- /dev/null +++ b/projects/ngx-bank/api/bank-labels-changes.model.ts @@ -0,0 +1,8 @@ +import { BankLabels } from './bank-labels.model'; + +/** + * The texts of the views to change, by the view that shows them. Each text left out keeps its default. + */ +export type BankLabelsChanges = { + [View in keyof BankLabels]?: Partial +}; diff --git a/projects/ngx-bank/api/bank-labels.model.ts b/projects/ngx-bank/api/bank-labels.model.ts new file mode 100644 index 0000000..f7bb914 --- /dev/null +++ b/projects/ngx-bank/api/bank-labels.model.ts @@ -0,0 +1,36 @@ +import { BankAccountsLabels } from './bank-accounts-labels.model'; +import { BankCommonLabels } from './bank-common-labels.model'; +import { BankMatchingLabels } from './bank-matching-labels.model'; +import { BankStatementUploadLabels } from './bank-statement-upload-labels.model'; +import { BankStatementsLabels } from './bank-statements-labels.model'; +import { BankTransactionsLabels } from './bank-transactions-labels.model'; + +/** + * The texts of the views of the bank, to translate them, by the view that shows them. + */ +export type BankLabels = { + /** + * The texts several views show. + */ + common: BankCommonLabels, + /** + * The texts of the bank accounts. + */ + accounts: BankAccountsLabels, + /** + * The texts of the upload of a statement. + */ + upload: BankStatementUploadLabels, + /** + * The texts of the statements. + */ + statements: BankStatementsLabels, + /** + * The texts of the transactions. + */ + transactions: BankTransactionsLabels, + /** + * The texts of matching a transaction. + */ + matching: BankMatchingLabels +}; diff --git a/projects/ngx-bank/api/bank-match-target-option.model.ts b/projects/ngx-bank/api/bank-match-target-option.model.ts new file mode 100644 index 0000000..6c71b9b --- /dev/null +++ b/projects/ngx-bank/api/bank-match-target-option.model.ts @@ -0,0 +1,13 @@ +/** + * Something a transaction can be matched with, as the user chooses it, like an invoice. + */ +export type BankMatchTargetOption = { + /** + * Its id, which the match names as its target. + */ + id: string, + /** + * What it is called, its number and the name of whom it is of, like '2026-0002 Example Ltd.'. + */ + label: string +}; diff --git a/projects/ngx-bank/api/bank-match.utilities.spec.ts b/projects/ngx-bank/api/bank-match.utilities.spec.ts new file mode 100644 index 0000000..2b309fb --- /dev/null +++ b/projects/ngx-bank/api/bank-match.utilities.spec.ts @@ -0,0 +1,15 @@ +import { describe, expect, test } from 'vitest'; + +import { INVOICE_PAYMENT, MATCHES, PARTIAL_PAYMENT, RENT, SHORT_PAYMENT } from '../fixtures/bank.fixtures'; +import { BankMatchUtilities } from './bank-match.utilities'; + +describe('BankMatchUtilities', () => { + test('leaves open what the matches of a transaction don\'t match, a reversal opening it again', () => { + expect(BankMatchUtilities.resolveOpenAmount(INVOICE_PAYMENT, [])).toBe('1190.00'); + expect(BankMatchUtilities.resolveOpenAmount(PARTIAL_PAYMENT, MATCHES[PARTIAL_PAYMENT.id] ?? [])).toBe('300.00'); + // money paid is open by its amount without the sign + expect(BankMatchUtilities.resolveOpenAmount(RENT, MATCHES[RENT.id] ?? [])).toBe('850.00'); + // the payment difference is the invoice's, not the transaction's + expect(BankMatchUtilities.resolveOpenAmount(SHORT_PAYMENT, MATCHES[SHORT_PAYMENT.id] ?? [])).toBe('0.00'); + }); +}); \ No newline at end of file diff --git a/projects/ngx-bank/api/bank-match.utilities.ts b/projects/ngx-bank/api/bank-match.utilities.ts new file mode 100644 index 0000000..04ab53c --- /dev/null +++ b/projects/ngx-bank/api/bank-match.utilities.ts @@ -0,0 +1,24 @@ +import { BankMatchModel, BankTransactionModel } from 'zibri-contract'; + +import { BankAmountUtilities } from './bank-amount.utilities'; + +/** + * The matches of transactions: what of a transaction its matches leave open. + */ +export abstract class BankMatchUtilities { + /** + * Resolves what of a transaction its matches leave open: its amount without its sign, less what each match matched. + * A reversal matches a negative amount, so what it reversed is open again. + * @param transaction - The transaction. + * @param matches - Its matches, reversals included. + * @returns The decimal string of what is open, in the decimals of its currency, like '50.00'. + */ + static resolveOpenAmount(transaction: BankTransactionModel, matches: BankMatchModel[]): string { + const fractionDigits: number = BankAmountUtilities.resolveFractionDigits(transaction.currency); + const matched: number = matches + .filter(match => match.transactionId === transaction.id) + .reduce((sum, match) => sum + BankAmountUtilities.resolveMinorUnits(match.amount, fractionDigits), 0); + const amount: number = BankAmountUtilities.resolveMinorUnits(BankAmountUtilities.getAbsolute(transaction.amount), fractionDigits); + return BankAmountUtilities.resolveDecimal(amount - matched, fractionDigits); + } +} diff --git a/projects/ngx-bank/api/bank-matching-labels.model.ts b/projects/ngx-bank/api/bank-matching-labels.model.ts new file mode 100644 index 0000000..661c17e --- /dev/null +++ b/projects/ngx-bank/api/bank-matching-labels.model.ts @@ -0,0 +1,93 @@ +/** + * The texts of matching a transaction, to translate them. + */ +export type BankMatchingLabels = { + /** + * What of the transaction is open, of its whole amount. + */ + open: (open: string, amount: string) => string, + /** + * What the view says about a transaction that is matched in full. + */ + matchedInFull: string, + /** + * The heading of the suggestions waiting for a decision. + */ + suggestions: string, + /** + * What the view says when no suggestion waits for a decision. + */ + noSuggestions: string, + /** + * How sure the api is of a suggestion, like 'Score 75 %'. + */ + score: (score: string) => string, + /** + * The header of the reasons of a suggestion. + */ + reasons: string, + /** + * The part of an invoice approving a suggestion accepts as paid without being paid. + */ + paymentDifference: string, + /** + * The badge of a match of an account, which a person always confirms. + */ + needsPerson: string, + /** + * Why a match of an account waits for a person. + */ + needsPersonHint: string, + /** + * The button that opens the review of a suggestion. + */ + review: string, + /** + * What screen readers call the button that opens the review of a suggestion. + */ + reviewOf: (summary: string) => string, + /** + * The button that closes the review. + */ + closeReview: string, + /** + * The button that has the api suggest matches again. + */ + suggestAgain: string, + /** + * What the view says once the api suggested matches again. + */ + suggested: string, + /** + * The heading of the form that proposes a match of the user. + */ + manual: string, + /** + * The select of what the transaction is matched with. + */ + targetType: string, + /** + * The hint below the target. + */ + targetHint: string, + /** + * The hint below the amount, with what of the transaction is open. + */ + amountHint: (open: string) => string, + /** + * The input of why the user proposes the match. + */ + reason: string, + /** + * The hint below the reason. + */ + reasonHint: string, + /** + * The button that proposes the match. + */ + propose: string, + /** + * What the view says once it proposed a match. + */ + proposed: string +}; diff --git a/projects/ngx-bank/api/bank-paths.model.ts b/projects/ngx-bank/api/bank-paths.model.ts new file mode 100644 index 0000000..399e14d --- /dev/null +++ b/projects/ngx-bank/api/bank-paths.model.ts @@ -0,0 +1,50 @@ +/** + * The paths of the routes below their urls: the bank routes below the baseUrl, `/`, the invoices below + * the invoicingUrl, and the expenses and the accounts of the books below the bookkeepingUrl. + */ +export type BankPaths = { + /** + * The bank accounts, which a POST adds to. 'accounts' by default. + */ + accounts: string, + /** + * The statements, which a POST of a CAMT.053 file imports. 'statements' by default. + */ + statements: string, + /** + * The transactions, each with what of it is open. 'transactions' by default. + */ + transactions: string, + /** + * Below a transaction, `//`: the matches suggested for it that wait for a decision. + * 'suggestions' by default. + */ + transactionSuggestions: string, + /** + * The confirmed matches. 'matches' by default. + */ + matches: string, + /** + * Suggests matches again with a POST. 'matches/suggestions' by default. + */ + suggestions: string, + /** + * Below a match, `//`: reverses it with a POST. 'reversal' by default. + */ + reversal: string, + /** + * Below the invoicingUrl: the invoices, searched for the ones to match with, and each below it by its id. + * 'invoices' by default. + */ + invoices: string, + /** + * Below the bookkeepingUrl: the expenses, searched for the ones to match with, and each below it by its id. + * 'expenses' by default. + */ + expenses: string, + /** + * Below the bookkeepingUrl: the accounts of the books, searched for the ones to match with, and each below it by + * its id. 'accounts' by default. + */ + bookkeepingAccounts: string +}; diff --git a/projects/ngx-bank/api/bank-statement-upload-labels.model.ts b/projects/ngx-bank/api/bank-statement-upload-labels.model.ts new file mode 100644 index 0000000..4652f2a --- /dev/null +++ b/projects/ngx-bank/api/bank-statement-upload-labels.model.ts @@ -0,0 +1,49 @@ +/** + * The texts of the upload of a statement, to translate them. + */ +export type BankStatementUploadLabels = { + /** + * The input of the file. + */ + file: string, + /** + * The hint below the file. + */ + fileHint: string, + /** + * The button that imports the file. + */ + import: string, + /** + * The heading of what the import stored. + */ + result: string, + /** + * How many statements were stored. + */ + statementsImported: string, + /** + * How many transactions were stored. + */ + transactionsImported: string, + /** + * How many statements were skipped as imported before. + */ + statementsSkipped: string, + /** + * How many transactions were skipped as imported before. + */ + transactionsSkipped: string, + /** + * What screen readers call the table of the statements stored. + */ + statements: string, + /** + * What the view says when the file held nothing that wasn't imported before. + */ + nothingNew: string, + /** + * What the view says once a file was imported. + */ + imported: string +}; diff --git a/projects/ngx-bank/api/bank-statements-labels.model.ts b/projects/ngx-bank/api/bank-statements-labels.model.ts new file mode 100644 index 0000000..4e437c1 --- /dev/null +++ b/projects/ngx-bank/api/bank-statements-labels.model.ts @@ -0,0 +1,33 @@ +/** + * The texts of the statements, to translate them. + */ +export type BankStatementsLabels = { + /** + * What screen readers call the table of the statements. + */ + statements: string, + /** + * The header of the id the bank gave a statement. + */ + statement: string, + /** + * When a statement was imported. + */ + importedAt: string, + /** + * The version of CAMT.053 a statement was read from. + */ + format: string, + /** + * The file a statement was imported from. + */ + file: string, + /** + * The heading of a statement opened from the table. + */ + statementTitle: (statement: string) => string, + /** + * What screen readers call the table of the transactions of a statement. + */ + transactions: (statement: string) => string +}; diff --git a/projects/ngx-bank/api/bank-statements-query.model.ts b/projects/ngx-bank/api/bank-statements-query.model.ts new file mode 100644 index 0000000..651423d --- /dev/null +++ b/projects/ngx-bank/api/bank-statements-query.model.ts @@ -0,0 +1,17 @@ +/** + * Which page of the statements to load, as `GET /statements` takes it. + */ +export type BankStatementsQuery = { + /** + * The page, from 1 on. + */ + page: number, + /** + * How many statements a page has, at most 100. + */ + limit: number, + /** + * Only the statements of this account, by its id. Undefined for every account. + */ + accountId?: string +}; diff --git a/projects/ngx-bank/api/bank-transactions-labels.model.ts b/projects/ngx-bank/api/bank-transactions-labels.model.ts new file mode 100644 index 0000000..5ae3e11 --- /dev/null +++ b/projects/ngx-bank/api/bank-transactions-labels.model.ts @@ -0,0 +1,73 @@ +/** + * The texts of the transactions, to translate them. + */ +export type BankTransactionsLabels = { + /** + * What screen readers call the table of the transactions. + */ + transactions: string, + /** + * The hint below the period. + */ + periodHint: string, + /** + * The filter of what of a transaction is matched, and the header of its column. + */ + status: string, + /** + * The option of the status filter that shows every transaction. + */ + allStatuses: string, + /** + * A transaction nothing of which is matched. + */ + open: string, + /** + * A transaction a part of which is matched. + */ + partlyMatched: string, + /** + * A transaction that is matched in full. + */ + matched: string, + /** + * The heading of a transaction opened from the table. + */ + transactionTitle: (day: string) => string, + /** + * The heading of the matches of a transaction. + */ + matches: string, + /** + * What a transaction says without a match. + */ + noMatches: string, + /** + * The part of a payment of an invoice a match accepts as paid without being paid. + */ + difference: string, + /** + * Who confirmed a match, and when. + */ + confirmedBy: (name: string, day: string) => string, + /** + * The badge of a match that reverses another. + */ + reversal: string, + /** + * The badge of a match that was reversed. + */ + reversed: string, + /** + * The button that reverses a match. + */ + reverse: string, + /** + * What screen readers call the button that reverses a match. + */ + reverseMatch: (target: string) => string, + /** + * What the view says once it reversed a match. + */ + matchReversed: (target: string) => string +}; diff --git a/projects/ngx-bank/api/bank-view.directive.ts b/projects/ngx-bank/api/bank-view.directive.ts new file mode 100644 index 0000000..2a86b6c --- /dev/null +++ b/projects/ngx-bank/api/bank-view.directive.ts @@ -0,0 +1,120 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { Directive, inject, LOCALE_ID } from '@angular/core'; +import { ErrorResponseUtilities } from '@service-soft/ngx-error-handling/error-response'; +import { HeadingLevel } from '@service-soft/ui/heading'; + +import { BankAmountUtilities } from './bank-amount.utilities'; +import { BankCommonLabels } from './bank-common-labels.model'; +import { BankConfig } from './bank-config.model'; +import { BANK_CONFIG } from './bank-config.provider'; +import { BankDayUtilities } from './bank-day.utilities'; +import { BankIbanUtilities } from './bank-iban.utilities'; +import { BankService } from './bank.service'; + +// the sections of a view are headed one level below it, and a heading of level 6 has no level below. +const SECTION_LEVELS: Record = { 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 6 }; + +/** + * What the views of the bank share: the config, the service, and writing amounts, days and IBANs, each amount in the + * language of the app with the currency it is in. The accounts, the upload, the statements, the transactions and the + * matching extend it. + */ +@Directive() +export abstract class BankViewDirective { + /** + * The config of the bank. + */ + protected readonly config: BankConfig = inject(BANK_CONFIG); + + /** + * Sends the requests of the bank. + */ + protected readonly bankService: BankService = inject(BankService); + + /** + * The language of the app, which amounts and days are written in. + */ + protected readonly locale: string = inject(LOCALE_ID); + + /** + * The texts several views show. + */ + protected readonly commonLabels: BankCommonLabels = this.config.labels.common; + + // a format per currency, as a table formats every row with the same few. + private readonly formats: Map = new Map(); + + /** + * Formats an amount of the api in its currency. + * @param amount - The decimal string, like '-9.9'. + * @param currency - The currency of the account, like 'EUR'. + * @returns The amount as it shows, like '-€9.90'. + */ + protected formatAmount(amount: string, currency: string): string { + let format: Intl.NumberFormat | undefined = this.formats.get(currency); + if (format == undefined) { + format = BankAmountUtilities.resolveFormat(currency, this.locale); + this.formats.set(currency, format); + } + return BankAmountUtilities.format(amount, format); + } + + /** + * Formats the day a transaction was booked on, in the date format of the config. + * @param day - The day, at midnight UTC. + * @returns The day as it shows. + */ + protected formatDay(day: Date): string { + return BankDayUtilities.format(day, this.config.dateFormat, this.locale); + } + + /** + * Formats a moment, like when a statement was imported, as its day in the time zone of the browser. + * @param date - The moment. + * @returns The day as it shows. + */ + protected formatDate(date: Date): string { + return new Intl.DateTimeFormat(this.locale, this.config.dateFormat).format(date); + } + + /** + * Formats the period of a statement, from its first to its last day in the time zone of the browser. + * @param start - The start of the period. + * @param end - The end of the period. + * @returns The period as it shows, like '11/01/2026 – 11/30/2026' in 'en-US'. + */ + protected formatPeriod(start: Date, end: Date): string { + return `${this.formatDate(start)} – ${this.formatDate(end)}`; + } + + /** + * Formats an IBAN in groups of four. + * @param iban - The IBAN, as the api stores it. + * @returns The IBAN as it shows. + */ + protected formatIban(iban: string): string { + return BankIbanUtilities.format(iban); + } + + /** + * Gets the level of the headings of the sections below a heading. + * @param level - The level of the heading. + * @returns The level one below, or 6 below a heading of level 6, which has none below. + */ + protected getSectionLevel(level: HeadingLevel): HeadingLevel { + return SECTION_LEVELS[level]; + } + + /** + * Resolves what the view says about a request the api refused: its message, or that it couldn't be sent. + * @param error - What the request rejected with. + * @returns The message, its paragraphs one per line. + * @throws The error, when it is no answer of the api but a mistake for the error handler. + */ + protected resolveErrorMessage(error: unknown): string { + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + return ErrorResponseUtilities.findMessage(error) ?? this.commonLabels.requestFailed; + } +} diff --git a/projects/ngx-bank/api/bank.service.spec.ts b/projects/ngx-bank/api/bank.service.spec.ts new file mode 100644 index 0000000..cb4abe4 --- /dev/null +++ b/projects/ngx-bank/api/bank.service.spec.ts @@ -0,0 +1,161 @@ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { provideApprovalRequestsConfig } from '@service-soft/ngx-approval-requests/api'; +import { describe, expect, test } from 'vitest'; +import { BankMatchModel, BankMatchTargetType, BankStatementImportModel, BankTransactionDetailsModel, BankTransactionStatus, BankTransactionSuggestionModel, PaginationResult } from 'zibri-contract'; + +import { APPROVAL_REQUESTS_BASE_URL, BANK_BASE_URL, BANK_URLS, BOOKKEEPING_ACCOUNTS, BOOKKEEPING_BASE_URL, IDS, IMPORT_RESULT, INVOICES, INVOICING_BASE_URL, OPEN_INVOICES, PARTIAL_MATCH, RENT_EXPENSE, RENT_MATCH, RENT_REVERSAL, SHORT_MATCH, toJson, TRANSACTION_DETAILS, TRANSACTION_SUGGESTIONS } from '../fixtures/bank.fixtures'; +import { provideBankConfig } from './bank-config.provider'; +import { BankMatchTargetOption } from './bank-match-target-option.model'; +import { BankService } from './bank.service'; + +function setup(): [BankService, HttpTestingController] { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + provideBankConfig(BANK_URLS), + provideApprovalRequestsConfig({ baseUrl: APPROVAL_REQUESTS_BASE_URL }) + ] + }); + return [TestBed.inject(BankService), TestBed.inject(HttpTestingController)]; +} + +describe('BankService', () => { + test('loads a page of the transactions with the filters of the query, its days as days, and answers their dates as Date', async () => { + const [service, http] = setup(); + + const loaded: Promise> = service.resolveTransactions({ + page: 2, + limit: 20, + accountId: IDS.business, + from: new Date('2026-11-01T00:00:00.000Z'), + until: new Date('2026-11-30T00:00:00.000Z'), + status: BankTransactionStatus.OPEN + }); + const request: TestRequest = http.expectOne(({ url }) => url === `${BANK_BASE_URL}/transactions`); + expect(request.request.params.toString()) + .toBe(`page=2&limit=20&accountId=${IDS.business}&from=2026-11-01&until=2026-11-30&status=OPEN`); + request.flush(toJson({ items: TRANSACTION_DETAILS, totalAmount: 26 })); + + await expect(loaded).resolves.toEqual({ items: TRANSACTION_DETAILS, totalAmount: 26 }); + http.verify(); + }); + + test('imports a file as the part file of a multipart body, and counts the change', async () => { + const [service, http] = setup(); + const file: File = new File([''], 'statement-2026-11.xml', { type: 'application/xml' }); + + const imported: Promise = service.importStatements(file); + const request: TestRequest = http.expectOne({ method: 'POST', url: `${BANK_BASE_URL}/statements` }); + expect(request.request.body instanceof FormData && request.request.body.get('file')).toEqual(file); + request.flush(toJson(IMPORT_RESULT)); + + await expect(imported).resolves.toEqual(IMPORT_RESULT); + expect(service.revision()).toBe(1); + }); + + test('loads the suggestions of a transaction below it', async () => { + const [service, http] = setup(); + + const found: Promise = service.resolveSuggestions(IDS.partialPayment); + http.expectOne({ method: 'GET', url: `${BANK_BASE_URL}/transactions/${IDS.partialPayment}/suggestions` }) + .flush(toJson(TRANSACTION_SUGGESTIONS[IDS.partialPayment] ?? [])); + + await expect(found).resolves.toEqual(TRANSACTION_SUGGESTIONS[IDS.partialPayment]); + }); + + test('proposes a match of the user as an approval request of the match action, and counts the change', () => { + const [service, http] = setup(); + + void service.proposeMatch( + { transactionId: IDS.fee, targetType: BankMatchTargetType.EXPENSE, targetId: IDS.rentExpense, amount: '9.90' }, + 'Fee of the bank' + ); + const request: TestRequest = http.expectOne({ method: 'POST', url: APPROVAL_REQUESTS_BASE_URL }); + expect(request.request.body).toEqual({ + action: 'bank.match', + input: { transactionId: IDS.fee, targetType: BankMatchTargetType.EXPENSE, targetId: IDS.rentExpense, amount: '9.90' }, + reason: 'Fee of the bank' + }); + }); + + test('finds the issued invoices with something open of a search, and the expenses, at their own routes', async () => { + const [service, http] = setup(); + + const invoices: Promise = service.findTargets(BankMatchTargetType.INVOICE, '2026'); + const invoiceSearch: TestRequest = http.expectOne(({ url }) => url === `${INVOICING_BASE_URL}/invoices`); + expect(invoiceSearch.request.params.toString()).toBe('page=1&limit=20&search=2026&issued=true&open=true&type=INVOICE'); + invoiceSearch.flush(toJson({ items: OPEN_INVOICES, totalAmount: OPEN_INVOICES.length })); + await expect(invoices).resolves.toEqual([ + { id: IDS.invoice7, label: '2026-0007 Example Ltd.' }, + { id: IDS.invoice5, label: '2026-0005 Sample Corp' } + ]); + + // the first ones without a search + const expenses: Promise = service.findTargets(BankMatchTargetType.EXPENSE, ''); + const expenseSearch: TestRequest = http.expectOne(({ url }) => url === `${BOOKKEEPING_BASE_URL}/expenses`); + expect(expenseSearch.request.params.toString()).toBe('page=1&limit=20'); + expenseSearch.flush(toJson({ items: [RENT_EXPENSE], totalAmount: 1 })); + await expect(expenses).resolves.toEqual([{ id: IDS.rentExpense, label: 'R-2026-11 Property management Miller' }]); + }); + + test('has the api search the open accounts of the books', async () => { + const [service, http] = setup(); + + const accounts: Promise = service.findTargets(BankMatchTargetType.ACCOUNT, '08'); + const search: TestRequest = http.expectOne(({ url }) => url === `${BOOKKEEPING_BASE_URL}/accounts`); + expect(search.request.params.toString()).toBe('search=08&open=true'); + search.flush(toJson(BOOKKEEPING_ACCOUNTS.slice(0, 1))); + await expect(accounts).resolves.toEqual([{ id: IDS.capitalAccount, label: '0800 Subscribed capital' }]); + + // every open account without a search + void service.findTargets(BankMatchTargetType.ACCOUNT, ''); + expect(http.expectOne(({ url }) => url === `${BOOKKEEPING_BASE_URL}/accounts`).request.params.toString()).toBe('open=true'); + }); + + test('names the targets of matches as it finds them, each by its own route and each target once', async () => { + const [service, http] = setup(); + const capital: BankMatchModel = { ...PARTIAL_MATCH, id: 'm-capital', targetType: BankMatchTargetType.ACCOUNT, targetId: IDS.capitalAccount }; + const capitalAgain: BankMatchModel = { ...capital, id: 'm-capital-2' }; + const closed: BankMatchModel = { ...capital, id: 'm-closed', targetId: IDS.closedAccount }; + const [capitalAccount, , closedAccount] = BOOKKEEPING_ACCOUNTS; + + const names: Promise> = service.resolveTargetNames([SHORT_MATCH, RENT_REVERSAL, RENT_MATCH, capital, capitalAgain, closed]); + http.expectOne({ method: 'GET', url: `${INVOICING_BASE_URL}/invoices/${IDS.invoice6}` }).flush(toJson(INVOICES[2] ?? {})); + // the match of the rent and its reversal share their expense, the two matches of the capital their account + http.expectOne({ method: 'GET', url: `${BOOKKEEPING_BASE_URL}/expenses/${IDS.rentExpense}` }).flush(toJson(RENT_EXPENSE)); + http.expectOne({ method: 'GET', url: `${BOOKKEEPING_BASE_URL}/accounts/${IDS.capitalAccount}` }).flush(toJson(capitalAccount ?? {})); + // a closed account is named as well + http.expectOne({ method: 'GET', url: `${BOOKKEEPING_BASE_URL}/accounts/${IDS.closedAccount}` }).flush(toJson(closedAccount ?? {})); + + await expect(names).resolves.toEqual(new Map([ + [IDS.invoice6, '2026-0006 Example Ltd.'], + [IDS.rentExpense, 'R-2026-11 Property management Miller'], + [IDS.capitalAccount, '0800 Subscribed capital'], + [IDS.closedAccount, '1590 Clearing account'] + ])); + http.verify(); + }); + + test('names the targets that answer, and leaves out one the api has no more', async () => { + const [service, http] = setup(); + + const names: Promise> = service.resolveTargetNames([SHORT_MATCH, RENT_MATCH]); + http.expectOne({ method: 'GET', url: `${INVOICING_BASE_URL}/invoices/${IDS.invoice6}` }).flush(toJson(INVOICES[2] ?? {})); + http.expectOne({ method: 'GET', url: `${BOOKKEEPING_BASE_URL}/expenses/${IDS.rentExpense}` }) + .flush({ status: 404, name: 'NotFoundError', message: 'Not found', paragraphs: ['Not found'] }, { status: 404, statusText: 'Not Found' }); + + await expect(names).resolves.toEqual(new Map([[IDS.invoice6, '2026-0006 Example Ltd.']])); + }); + + test('says what is missing without a url', async () => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + const service: BankService = TestBed.inject(BankService); + + await expect(service.resolveAccounts()).rejects.toThrow('provideBankConfig({ baseUrl })'); + await expect(service.findTargets(BankMatchTargetType.INVOICE, '')).rejects.toThrow('provideBankConfig({ invoicingUrl })'); + await expect(service.resolveTargetNames([RENT_MATCH])).rejects.toThrow('provideBankConfig({ bookkeepingUrl })'); + }); +}); diff --git a/projects/ngx-bank/api/bank.service.ts b/projects/ngx-bank/api/bank.service.ts new file mode 100644 index 0000000..4439f2b --- /dev/null +++ b/projects/ngx-bank/api/bank.service.ts @@ -0,0 +1,357 @@ +import { HttpClient, HttpErrorResponse } from '@angular/common/http'; +import { inject, Service, Signal, signal, WritableSignal } from '@angular/core'; +import { ApprovalRequestService } from '@service-soft/ngx-approval-requests/api'; +import { firstValueFrom } from 'rxjs'; +import { ApprovalRequestDetailsModel, BankAccountModel, BankMatchInputModel, BankMatchModel, BankMatchTargetType, BankStatementImportModel, BankStatementModel, BankTransactionDetailsModel, BankTransactionQueryModel, BankTransactionSuggestionModel, BookkeepingAccountModel, ExpenseModel, InvoiceModel, InvoiceType, NewBankAccountModel, PaginationResult } from 'zibri-contract'; + +import { BankConfig } from './bank-config.model'; +import { BANK_CONFIG } from './bank-config.provider'; +import { BankDayUtilities } from './bank-day.utilities'; +import { BankJsonUtilities } from './bank-json.utilities'; +import { BankMatchTargetOption } from './bank-match-target-option.model'; +import { BankStatementsQuery } from './bank-statements-query.model'; + +/** + * The query of a request. + */ +type BankParams = Record; + +/** + * The urls of the config the requests are sent below. + */ +type BankUrl = 'baseUrl' | 'invoicingUrl' | 'bookkeepingUrl'; + +/** + * The most rows a page of the api holds, which the lists that load every page ask for. + */ +const MAX_LIMIT: number = 100; + +/** + * How many invoices or expenses a search offers to match with: a user who doesn't find one types more of it. + */ +const TARGET_LIMIT: number = 20; + +// what each url is for, which the error without it names. +const URL_PURPOSES: Record = { + baseUrl: 'the bank routes of your api', + invoicingUrl: 'the invoicing routes of your api to match with invoices', + bookkeepingUrl: 'the bookkeeping routes of your api to match with expenses and accounts of the books' +}; + +/** + * Sends the requests of the bank routes at the baseUrl of provideBankConfig, like `GET /transactions` for a page of the + * transactions, `POST /statements` to import a CAMT.053 file and `GET /transactions/:id/suggestions` for the matches + * suggested for a transaction. A match of the user is proposed as an approval request through the + * ApprovalRequestService of ngx-approval-requests, with a target found at the invoicingUrl or the bookkeepingUrl. It + * answers the models of zibri-contract, with their dates as Date. It needs HttpClient, from provideHttpClient. + */ +@Service() +export class BankService { + /** + * Sends the requests. + */ + protected readonly http: HttpClient = inject(HttpClient); + + private readonly config: BankConfig = inject(BANK_CONFIG); + + private readonly approvalRequestService: ApprovalRequestService = inject(ApprovalRequestService); + + private readonly revisionSignal: WritableSignal = signal(0); + + /** + * Counts what this service changed: added accounts, imported statements, reversed, suggested and proposed matches. + * Read it in the params of a resource of the bank, which then loads again after every change of the app, like the + * transactions do. + */ + readonly revision: Signal = this.revisionSignal.asReadonly(); + + /** + * Loads the bank accounts. + * @returns Every account, by name. + */ + async resolveAccounts(): Promise { + return await firstValueFrom(this.http.get(this.resolveUrl('baseUrl', this.config.paths.accounts))); + } + + /** + * Adds a bank account. Rejects with the error of the request when the api refuses it, like for an IBAN the tenant + * has an account of already. + * @param account - The account. + * @returns The account added, with its IBAN as the api stores it. + */ + async createAccount(account: NewBankAccountModel): Promise { + const created: BankAccountModel = await firstValueFrom( + this.http.post(this.resolveUrl('baseUrl', this.config.paths.accounts), account) + ); + this.revisionSignal.update(revision => revision + 1); + return created; + } + + /** + * Imports the statements of a CAMT.053 file, sent as the part `file` of a multipart body. Rejects with the error of + * the request when the api refuses the file, like for a statement of an IBAN the tenant has no account of, or one + * that doesn't continue the statement before it. + * @param file - The file. + * @returns The statements stored, and how many statements and transactions were stored and skipped. + */ + async importStatements(file: File): Promise { + const body: FormData = new FormData(); + body.append('file', file, file.name); + const result: BankStatementImportModel = BankJsonUtilities.toImport( + await firstValueFrom(this.http.post(this.resolveUrl('baseUrl', this.config.paths.statements), body)) + ); + this.revisionSignal.update(revision => revision + 1); + return result; + } + + /** + * Loads a page of the statements, the latest period first. + * @param query - The page, and the account to filter by. + * @returns The statements of the page, and how many there are on all pages together. + */ + async resolveStatements(query: BankStatementsQuery): Promise> { + const params: BankParams = { + page: query.page, + limit: query.limit, + ...query.accountId == undefined ? {} : { accountId: query.accountId } + }; + const page: PaginationResult = await firstValueFrom( + this.http.get>(this.resolveUrl('baseUrl', this.config.paths.statements), { params }) + ); + return { ...page, items: page.items.map(statement => BankJsonUtilities.toStatement(statement)) }; + } + + /** + * Loads a page of the transactions, the latest booking first, each with what of it its matches leave open. + * Rejects with the error of the request when the api refuses the query, like for an until before the from. + * @param query - The page, and the account, the statement, the days and the status to filter by, the days at + * midnight UTC. + * @returns The transactions of the page, and how many there are on all pages together. + */ + async resolveTransactions(query: BankTransactionQueryModel): Promise> { + const { page, limit, accountId, statementId, from, until, status } = query; + const params: BankParams = { + page, + limit, + ...accountId == undefined ? {} : { accountId }, + ...statementId == undefined ? {} : { statementId }, + ...from == undefined ? {} : { from: BankDayUtilities.getQueryValue(from) }, + ...until == undefined ? {} : { until: BankDayUtilities.getQueryValue(until) }, + ...status == undefined ? {} : { status } + }; + const transactions: PaginationResult = await firstValueFrom( + this.http.get>(this.resolveUrl('baseUrl', this.config.paths.transactions), { params }) + ); + return { ...transactions, items: transactions.items.map(details => BankJsonUtilities.toTransactionDetails(details)) }; + } + + /** + * Loads the matches of a transaction, reversals included. + * @param transactionId - The id of the transaction. + * @returns Every match, the latest confirmed first. + */ + async resolveMatches(transactionId: string): Promise { + return await this.resolveAllPages(async page => { + const params: BankParams = { page, limit: MAX_LIMIT, transactionId }; + const matches: PaginationResult = await firstValueFrom( + this.http.get>(this.resolveUrl('baseUrl', this.config.paths.matches), { params }) + ); + return { ...matches, items: matches.items.map(match => BankJsonUtilities.toMatch(match)) }; + }); + } + + /** + * Reverses a match: the api records a match of the negative amount, and what it matched is open again. Rejects + * with the error of the request when the api refuses it, like for a match reversed already. + * @param id - The id of the match. + * @returns The match reversing it. + */ + async reverseMatch(id: string): Promise { + const url: string = this.resolveUrl('baseUrl', this.config.paths.matches, id, this.config.paths.reversal); + const reversal: BankMatchModel = BankJsonUtilities.toMatch(await firstValueFrom(this.http.post(url, {}))); + this.revisionSignal.update(revision => revision + 1); + return reversal; + } + + /** + * Has the api suggest matches again for every transaction that is not matched in full, like once the invoice of a + * payment was created after its statement was imported. + * @returns The approval requests it proposed. + */ + async suggestMatches(): Promise { + const proposed: ApprovalRequestDetailsModel[] = await firstValueFrom( + this.http.post(this.resolveUrl('baseUrl', this.config.paths.suggestions), {}) + ); + this.revisionSignal.update(revision => revision + 1); + return proposed; + } + + /** + * Loads the matches suggested for a transaction that wait for a decision, each with the id of its approval request, + * which ngx-approval-requests approves or rejects it by. + * @param transactionId - The id of the transaction. + * @returns The suggestions, the most confident first. + */ + async resolveSuggestions(transactionId: string): Promise { + const url: string = this.resolveUrl('baseUrl', this.config.paths.transactions, transactionId, this.config.paths.transactionSuggestions); + return await firstValueFrom(this.http.get(url)); + } + + /** + * Proposes a match of the user as an approval request of the match action, which a person who confirms matches + * approves. Rejects with the error of the request when the api refuses it, like for a target the transaction can't + * be matched with. + * @param input - The transaction, the target and the amount. + * @param reason - Why the user proposes it, for the reviewer, or undefined. + * @returns The request proposed. + */ + async proposeMatch(input: BankMatchInputModel, reason: string | undefined): Promise { + const proposed: ApprovalRequestDetailsModel = await this.approvalRequestService.propose({ + action: this.config.matchAction, + input, + reason + }); + this.revisionSignal.update(revision => revision + 1); + return proposed; + } + + /** + * Finds what a user can match a transaction with by hand: the issued invoices with something open, the expenses, or + * the open accounts of the books, whose number or name contains the search. + * @param type - The type of the target. + * @param search - What the user typed, empty for the first ones. + * @returns The targets, each with its number and the name of whom it is of. + */ + async findTargets(type: BankMatchTargetType, search: string): Promise { + switch (type) { + case BankMatchTargetType.INVOICE: { + return await this.findInvoices(search); + } + case BankMatchTargetType.EXPENSE: { + return await this.findExpenses(search); + } + case BankMatchTargetType.ACCOUNT: { + return await this.findBookkeepingAccounts(search); + } + } + } + + /** + * Resolves what the targets of matches are called, as findTargets calls them, each target once, like the invoice of + * a match and of its reversal. + * @param matches - The matches. + * @returns What each target is called, by its id. A target whose request failed, like one the api has no more, is + * left out, the others are named all the same. + */ + async resolveTargetNames(matches: BankMatchModel[]): Promise> { + const targets: [string, BankMatchTargetType][] = [...new Map(matches.map(match => [match.targetId, match.targetType]))]; + const results: PromiseSettledResult[] = await Promise.allSettled( + targets.map(async ([id, type]) => await this.resolveTargetName(type, id)) + ); + const names: Map = new Map(); + for (const [index, result] of results.entries()) { + const id: string | undefined = targets[index]?.[0]; + if (result.status === 'fulfilled' && id != undefined) { + names.set(id, result.value); + } + // a failed request leaves the target to show by its id, anything else is a mistake for the error handler, + // like a missing url of the config. + else if (result.status === 'rejected' && !(result.reason instanceof HttpErrorResponse)) { + throw result.reason; + } + } + return names; + } + + private async findInvoices(search: string): Promise { + // a payment pays an invoice that was issued and has something open, never a credit note. + const params: BankParams = { + page: 1, + limit: TARGET_LIMIT, + ...search === '' ? {} : { search }, + issued: true, + open: true, + type: InvoiceType.INVOICE + }; + const invoices: PaginationResult = await firstValueFrom( + this.http.get>(this.resolveUrl('invoicingUrl', this.config.paths.invoices), { params }) + ); + return invoices.items.map(invoice => ({ id: invoice.id, label: this.getInvoiceName(invoice) })); + } + + private async findExpenses(search: string): Promise { + const params: BankParams = { page: 1, limit: TARGET_LIMIT, ...search === '' ? {} : { search } }; + const expenses: PaginationResult = await firstValueFrom( + this.http.get>(this.resolveUrl('bookkeepingUrl', this.config.paths.expenses), { params }) + ); + return expenses.items.map(expense => ({ id: expense.id, label: this.getExpenseName(expense) })); + } + + private async findBookkeepingAccounts(search: string): Promise { + // a closed account is booked on no more. The query of BookkeepingAccountQueryModel. + const params: BankParams = { ...search === '' ? {} : { search }, open: true }; + const accounts: BookkeepingAccountModel[] = await firstValueFrom( + this.http.get(this.resolveUrl('bookkeepingUrl', this.config.paths.bookkeepingAccounts), { params }) + ); + return accounts.map(account => ({ id: account.id, label: this.getBookkeepingAccountName(account) })); + } + + // a target of a match is named whatever it is now, like a closed account. + private async resolveTargetName(type: BankMatchTargetType, id: string): Promise { + switch (type) { + case BankMatchTargetType.INVOICE: { + const url: string = this.resolveUrl('invoicingUrl', this.config.paths.invoices, id); + return this.getInvoiceName(await firstValueFrom(this.http.get(url))); + } + case BankMatchTargetType.EXPENSE: { + const url: string = this.resolveUrl('bookkeepingUrl', this.config.paths.expenses, id); + return this.getExpenseName(await firstValueFrom(this.http.get(url))); + } + case BankMatchTargetType.ACCOUNT: { + const url: string = this.resolveUrl('bookkeepingUrl', this.config.paths.bookkeepingAccounts, id); + return this.getBookkeepingAccountName(await firstValueFrom(this.http.get(url))); + } + } + } + + private getInvoiceName(invoice: InvoiceModel): string { + const { company, companyName, firstName, lastName } = invoice.customerAddressData; + const customer: string = company && companyName != undefined ? companyName : `${firstName} ${lastName}`; + return `${invoice.number} ${customer}`; + } + + private getExpenseName(expense: ExpenseModel): string { + return `${expense.documentNumber} ${expense.supplier.name}`; + } + + private getBookkeepingAccountName(account: BookkeepingAccountModel): string { + return `${account.number} ${account.name}`; + } + + // loads the pages one after the other until every item of the first answer's total is there, or a page is empty. + private async resolveAllPages(resolvePage: (page: number) => Promise>): Promise { + const items: T[] = []; + for (let page: number = 1; ; page++) { + const result: PaginationResult = await resolvePage(page); + items.push(...result.items); + if (!result.items.length || items.length >= result.totalAmount) { + return items; + } + } + } + + // the paths are the config's as they are, as one holds a slash, like 'matches/suggestions'. Only ids are encoded. + private resolveUrl(url: BankUrl, path: string, id?: string, subPath?: string): string { + const base: string | undefined = this.config[url]; + if (base == undefined) { + throw new Error(`The BankService needs the url of ${URL_PURPOSES[url]}. ` + + `Add provideBankConfig({ ${url} }) to the providers of your app.`); + } + return [ + base, + path, + ...id == undefined ? [] : [encodeURIComponent(id)], + ...subPath == undefined ? [] : [subPath] + ].join('/'); + } +} diff --git a/projects/ngx-bank/api/ng-package.json b/projects/ngx-bank/api/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-bank/api/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-bank/api/public-api.ts b/projects/ngx-bank/api/public-api.ts new file mode 100644 index 0000000..425c614 --- /dev/null +++ b/projects/ngx-bank/api/public-api.ts @@ -0,0 +1,20 @@ +export * from './bank-accounts-labels.model'; +export * from './bank-amount.utilities'; +export * from './bank-common-labels.model'; +export * from './bank-config-changes.model'; +export * from './bank-config.model'; +export * from './bank-config.provider'; +export * from './bank-day.utilities'; +export * from './bank-iban.utilities'; +export * from './bank-labels-changes.model'; +export * from './bank-labels.model'; +export * from './bank-match-target-option.model'; +export * from './bank-match.utilities'; +export * from './bank-matching-labels.model'; +export * from './bank-paths.model'; +export * from './bank-statement-upload-labels.model'; +export * from './bank-statements-labels.model'; +export * from './bank-statements-query.model'; +export * from './bank-transactions-labels.model'; +export * from './bank-view.directive'; +export * from './bank.service'; diff --git a/projects/ngx-bank/bank-accounts/bank-accounts.component.html b/projects/ngx-bank/bank-accounts/bank-accounts.component.html new file mode 100644 index 0000000..0bdf520 --- /dev/null +++ b/projects/ngx-bank/bank-accounts/bank-accounts.component.html @@ -0,0 +1,34 @@ +
+ @if (loadingFailed()) { + + } + + +
+ {{ labels.add }} + + + + + @if (addError(); as message) { + + } +
+ + +

{{ announcement() }}

+
+
+
+
diff --git a/projects/ngx-bank/bank-accounts/bank-accounts.component.spec.ts b/projects/ngx-bank/bank-accounts/bank-accounts.component.spec.ts new file mode 100644 index 0000000..289000d --- /dev/null +++ b/projects/ngx-bank/bank-accounts/bank-accounts.component.spec.ts @@ -0,0 +1,108 @@ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideApprovalRequestsConfig } from '@service-soft/ngx-approval-requests/api'; +import { provideBankConfig } from '@service-soft/ngx-bank/api'; +import { FormTestingUtilities } from 'testing/form'; +import { beforeEach, describe, expect, test } from 'vitest'; +import { BankAccountModel, ErrorResponseBody } from 'zibri-contract'; + +import { BankBackendUtilities } from '../fixtures/bank-backend.utilities'; +import { BankTestingUtilities } from '../fixtures/bank-testing.utilities'; +import { ACCOUNTS, APPROVAL_REQUESTS_BASE_URL, BANK_BASE_URL, BUSINESS_ACCOUNT, toJson } from '../fixtures/bank.fixtures'; +import { BankAccountsComponent } from './bank-accounts.component'; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [BankAccountsComponent] +}) +class HostComponent {} + +const SAVINGS: BankAccountModel = { + ...BUSINESS_ACCOUNT, + id: 'a1000000-0000-4000-8000-000000000003', + iban: 'AT611904300234573201', + name: 'Savings', + currency: 'GBP' +}; + +async function render(): Promise<[ComponentFixture, HTMLElement]> { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + return [fixture, fixture.nativeElement as HTMLElement]; +} + +async function fill(fixture: ComponentFixture, root: HTMLElement, iban: string): Promise { + await BankTestingUtilities.type(fixture, FormTestingUtilities.findInput(root, 'iban'), iban); + await BankTestingUtilities.type(fixture, FormTestingUtilities.findInput(root, 'name'), ' Savings '); + await BankTestingUtilities.type(fixture, FormTestingUtilities.findInput(root, 'currency'), 'gbp'); + FormTestingUtilities.click(root, 'Add a bank account'); + await BankTestingUtilities.render(fixture); +} + +describe('BankAccountsComponent', () => { + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + provideBankConfig({ baseUrl: BANK_BASE_URL }), + provideApprovalRequestsConfig({ baseUrl: APPROVAL_REQUESTS_BASE_URL }) + ] + }); + }); + + test('lists the accounts by name with their IBAN in groups of four', async () => { + const [, root] = await render(); + + expect([...root.querySelectorAll('ui-local-table tbody tr')].map(row => BankTestingUtilities.getText(row))).toEqual([ + // each value after its column, which a phone shows as a card of the row + 'Name Business account IBAN DE89 3704 0044 0532 0130 00 Currency EUR', + 'Name Reserve account IBAN DE02 1203 0000 0000 2020 51 Currency EUR' + ]); + }); + + test('refuses an IBAN with a typing error without sending it, and says why at the IBAN', async () => { + const [fixture, root] = await render(); + + await fill(fixture, root, 'AT61 1904 3002 3457 3210'); + + TestBed.inject(HttpTestingController).expectNone(({ method }) => method === 'POST'); + const iban: HTMLInputElement | null = FormTestingUtilities.findInput(root, 'iban'); + expect(iban?.validationMessage).toBe('This is no valid IBAN. Check it for a typing error.'); + expect(BankTestingUtilities.getText(root.querySelector('ui-input-string'))).toContain('This is no valid IBAN. Check it for a typing error.'); + }); + + test('adds an account with its IBAN as the api stores it, and lists it', async () => { + const [fixture, root] = await render(); + + await fill(fixture, root, 'at61 1904 3002 3457 3201'); + const request: TestRequest = TestBed.inject(HttpTestingController).expectOne({ method: 'POST', url: `${BANK_BASE_URL}/accounts` }); + expect(request.request.body).toEqual({ iban: 'AT611904300234573201', name: 'Savings', currency: 'GBP' }); + request.flush(toJson(SAVINGS)); + await BankTestingUtilities.settle(fixture, { + ...BankBackendUtilities.getAnswers(), + [`GET ${BANK_BASE_URL}/accounts`]: { status: 200, body: toJson([...ACCOUNTS, SAVINGS]) } + }); + + expect(root.querySelector('form p[role="status"]')?.textContent.trim()).toBe('The account Savings was added.'); + expect(root.querySelectorAll('ui-local-table tbody tr')).toHaveLength(3); + expect(FormTestingUtilities.findInput(root, 'iban')?.value).toBe(''); + expect(FormTestingUtilities.findInput(root, 'currency')?.value).toBe('EUR'); + }); + + test('shows the message of the api when it refuses the account', async () => { + const [fixture, root] = await render(); + + await fill(fixture, root, 'DE89 3704 0044 0532 0130 00'); + const message: string = 'The tenant has an account of the IBAN DE89370400440532013000 already.'; + const body: ErrorResponseBody = { status: 409, name: 'ConflictError', message, paragraphs: [message] }; + TestBed.inject(HttpTestingController).expectOne({ method: 'POST' }) + .flush(body, { status: 409, statusText: 'Conflict' }); + await BankTestingUtilities.settle(fixture, {}); + + expect(BankTestingUtilities.getText(root.querySelector('[role="alert"]'))).toBe(`Error ${message}`); + }); +}); \ No newline at end of file diff --git a/projects/ngx-bank/bank-accounts/bank-accounts.component.ts b/projects/ngx-bank/bank-accounts/bank-accounts.component.ts new file mode 100644 index 0000000..d9cb639 --- /dev/null +++ b/projects/ngx-bank/bank-accounts/bank-accounts.component.ts @@ -0,0 +1,147 @@ +import { Component, computed, resource, ResourceRef, Signal, signal, WritableSignal } from '@angular/core'; +import { BankAccountsLabels, BankIbanUtilities, BankViewDirective } from '@service-soft/ngx-bank/api'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { FormComponent } from '@service-soft/ui/form'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { InputValidation } from '@service-soft/ui/input'; +import { InputStringComponent } from '@service-soft/ui/input-string'; +import { LoadingDirective } from '@service-soft/ui/loading'; +import { LocalTableColumn, LocalTableComponent } from '@service-soft/ui/local-table'; +import { BankAccountModel } from 'zibri-contract'; + +/** + * The bank accounts of the api of provideBankConfig: ``. A table lists them by name, with their + * IBAN in groups of four, and a form adds one. The browser checks the IBAN for a typing error before the account is + * sent, and the api stores it in capitals and without spaces. A statement is imported into the account of its IBAN, so + * an account is added before its first statement. + */ +@Component({ + selector: 'ngx-bank-accounts', + templateUrl: './bank-accounts.component.html', + imports: [ + ButtonComponent, + CalloutComponent, + FormComponent, + HeadingComponent, + InputStringComponent, + LoadingDirective, + LocalTableComponent + ], + host: { class: 'block' } +}) +export class BankAccountsComponent extends BankViewDirective { + /** + * The texts of the accounts. + */ + protected readonly labels: BankAccountsLabels = this.config.labels.accounts; + + /** + * The level of the heading of the form. + */ + protected readonly headingLevel: HeadingLevel = this.config.headingLevel; + + private readonly accounts: ResourceRef = resource({ + params: () => this.bankService.revision(), + loader: async () => await this.bankService.resolveAccounts() + }); + + /** + * Whether the accounts are loading. + */ + protected readonly isLoading: Signal = computed(() => this.accounts.isLoading()); + + /** + * Whether the accounts couldn't be loaded. + */ + protected readonly loadingFailed: Signal = computed(() => this.accounts.error() != undefined); + + /** + * The accounts, by name. + */ + protected readonly rows: Signal = computed(() => this.accounts.hasValue() ? this.accounts.value() ?? [] : []); + + /** + * The columns of the table. + */ + protected readonly columns: LocalTableColumn[] = [ + { key: 'name', label: this.commonLabels.name, value: account => account.name, sortable: true }, + { key: 'iban', label: this.commonLabels.iban, value: account => this.formatIban(account.iban) }, + { key: 'currency', label: this.commonLabels.currency, value: account => account.currency } + ]; + + /** + * The IBAN of the account to add, as the user types it. + */ + protected readonly iban: WritableSignal = signal(''); + + /** + * The name of the account to add. + */ + protected readonly name: WritableSignal = signal(''); + + /** + * The currency of the account to add, the one of the config at first. + */ + protected readonly currency: WritableSignal = signal(this.config.defaultCurrency); + + /** + * Whether the account is being sent. + */ + protected readonly adding: WritableSignal = signal(false); + + /** + * Why the api refused the account, its paragraphs one per line, or undefined while it refused none. + */ + protected readonly addError: WritableSignal = signal(undefined); + + /** + * What the view last said about an account it added, read by screen readers as it changes. + */ + protected readonly announcement: WritableSignal = signal(''); + + /** + * Refuses an IBAN whose check digits are wrong, which the browser then doesn't submit. An empty one is left to the + * required of the input. + * @param iban - The IBAN as typed. + * @returns The error, or undefined for a valid IBAN. + */ + protected readonly ibanValidation: InputValidation = iban => { + return iban.trim() === '' || BankIbanUtilities.isValid(iban) ? undefined : this.labels.invalidIban; + }; + + /** + * Gets the key of a row of the table. + * @param account - The account of the row. + * @returns Its id. + */ + protected readonly getRowKey: (account: BankAccountModel) => string = account => account.id; + + /** + * Adds the account, which the form only submits with a valid IBAN, a name and a currency, and says so once it is + * added. The table loads again with it. + */ + protected async add(): Promise { + this.adding.set(true); + this.addError.set(undefined); + this.announcement.set(''); + try { + const added: BankAccountModel = await this.bankService.createAccount({ + iban: BankIbanUtilities.normalize(this.iban()), + name: this.name().trim(), + currency: this.currency().trim() + .toUpperCase() + }); + this.iban.set(''); + this.name.set(''); + this.currency.set(this.config.defaultCurrency); + this.announcement.set(this.labels.added(added.name)); + } + catch (error) { + this.addError.set(this.resolveErrorMessage(error)); + } + finally { + this.adding.set(false); + } + } +} \ No newline at end of file diff --git a/projects/ngx-bank/bank-accounts/bank-accounts.stories.ts b/projects/ngx-bank/bank-accounts/bank-accounts.stories.ts new file mode 100644 index 0000000..b5b5ffa --- /dev/null +++ b/projects/ngx-bank/bank-accounts/bank-accounts.stories.ts @@ -0,0 +1,26 @@ +import { Meta, StoryObj } from '@storybook/angular'; + +import { BankStoryUtilities } from '../fixtures/bank-story.utilities'; +import { BANK_BASE_URL } from '../fixtures/bank.fixtures'; +import { BankAccountsComponent } from './bank-accounts.component'; + +const meta: Meta = { + title: 'Bank/Accounts', + component: BankAccountsComponent, + render: () => ({ template: '' }) +}; +export default meta; + +type Story = StoryObj; + +export const Default: Story = { + decorators: [BankStoryUtilities.provideBackend()] +}; + +export const NoAccounts: Story = { + decorators: [BankStoryUtilities.provideBackend({ [`GET ${BANK_BASE_URL}/accounts`]: { status: 200, body: [] } })] +}; + +export const LoadingFailed: Story = { + decorators: [BankStoryUtilities.provideBackend({ [`GET ${BANK_BASE_URL}/accounts`]: { status: 503 } })] +}; \ No newline at end of file diff --git a/projects/ngx-bank/bank-accounts/ng-package.json b/projects/ngx-bank/bank-accounts/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-bank/bank-accounts/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-bank/bank-accounts/public-api.ts b/projects/ngx-bank/bank-accounts/public-api.ts new file mode 100644 index 0000000..1e660d5 --- /dev/null +++ b/projects/ngx-bank/bank-accounts/public-api.ts @@ -0,0 +1 @@ +export * from './bank-accounts.component'; \ No newline at end of file diff --git a/projects/ngx-bank/bank-matching/bank-matching.component.html b/projects/ngx-bank/bank-matching/bank-matching.component.html new file mode 100644 index 0000000..e02d77f --- /dev/null +++ b/projects/ngx-bank/bank-matching/bank-matching.component.html @@ -0,0 +1,43 @@ +
+ @if (loadingFailed()) { + + } +

{{ openText() }}

+ +
+
+ {{ labels.suggestions }} + +
+ +

{{ announcement() }}

+ @if (suggestError(); as message) { +
+ +

{{ message }}

+
+ } + +
    + @for (suggestion of suggestionViews(); track suggestion.id) { +
  • + +
  • + } @empty { +
  • {{ labels.noSuggestions }}
  • + } +
+ @if (reviewedId(); as requestId) { +
+ +
+ +
+
+ } +
+ + +
\ No newline at end of file diff --git a/projects/ngx-bank/bank-matching/bank-matching.component.spec.ts b/projects/ngx-bank/bank-matching/bank-matching.component.spec.ts new file mode 100644 index 0000000..0100bfd --- /dev/null +++ b/projects/ngx-bank/bank-matching/bank-matching.component.spec.ts @@ -0,0 +1,250 @@ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component, input, InputSignal } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideApprovalRequestsConfig } from '@service-soft/ngx-approval-requests/api'; +import { provideBankConfig } from '@service-soft/ngx-bank/api'; +import { DialogTestingUtilities } from 'testing/dialog'; +import { FormTestingUtilities } from 'testing/form'; +import { FakeAnswer } from 'testing/http'; +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; +import { BankTransactionModel, ErrorResponseBody } from 'zibri-contract'; + +import { BankBackendUtilities } from '../fixtures/bank-backend.utilities'; +import { BankTestingUtilities } from '../fixtures/bank-testing.utilities'; +import { APPROVAL_REQUESTS_BASE_URL, APPROVED_INVOICE_SUGGESTION, BANK_BASE_URL, BANK_URLS, BOOKKEEPING_BASE_URL, CAPITAL, IDS, INVOICE_MATCH, INVOICE_PAYMENT, INVOICING_BASE_URL, PARTIAL_PAYMENT, RENT, toJson } from '../fixtures/bank.fixtures'; +import { BankMatchingComponent } from './bank-matching.component'; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [BankMatchingComponent] +}) +class HostComponent { + readonly transaction: InputSignal = input(INVOICE_PAYMENT); +} + +async function render(transaction: BankTransactionModel = INVOICE_PAYMENT): Promise<[ComponentFixture, HTMLElement, TestRequest[]]> { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + fixture.componentRef.setInput('transaction', transaction); + const requests: TestRequest[] = await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + return [fixture, fixture.nativeElement as HTMLElement, requests]; +} + +function getSuggestions(root: HTMLElement): string[] { + return [...root.querySelectorAll('ngx-bank-match-suggestion')].map(suggestion => BankTestingUtilities.getText(suggestion)); +} + +function getForm(root: HTMLElement): HTMLElement { + const form: HTMLElement | null = root.querySelector('ngx-bank-manual-match'); + if (form == undefined) { + throw new Error('There is no form.'); + } + return form; +} + +async function waitForDialog(): Promise { + return await vi.waitFor(() => { + TestBed.tick(); + const dialog: HTMLDialogElement | undefined = [...document.querySelectorAll('dialog[open]')].at(-1); + if (dialog == undefined) { + throw new Error('No dialog opened.'); + } + return dialog; + }); +} + +describe('BankMatchingComponent', () => { + let removeModalDialogs: () => void; + + beforeEach(() => { + removeModalDialogs = DialogTestingUtilities.addModalDialogs(); + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + provideBankConfig(BANK_URLS), + provideApprovalRequestsConfig({ baseUrl: APPROVAL_REQUESTS_BASE_URL }) + ] + }); + }); + + afterEach(() => { + removeModalDialogs(); + for (const dialog of document.querySelectorAll('ui-dialog')) { + dialog.remove(); + } + }); + + test('shows what is open, and the suggestions the api has for the transaction with their score, reasons and amount', async () => { + const [, root, requests] = await render(); + + const [matches] = BankTestingUtilities.findRequests(requests, `${BANK_BASE_URL}/matches`); + expect(matches?.request.params.toString()).toBe(`page=1&limit=100&transactionId=${IDS.invoicePayment}`); + expect(BankTestingUtilities.findRequests(requests, `${BANK_BASE_URL}/transactions/${IDS.invoicePayment}/suggestions`)).toHaveLength(1); + // nothing of the other transactions, like their approval requests + expect(BankTestingUtilities.findRequests(requests, APPROVAL_REQUESTS_BASE_URL)).toHaveLength(0); + expect(BankTestingUtilities.getText(root.querySelector('div > p'))).toBe('€1,190.00 of €1,190.00 are open.'); + expect(getSuggestions(root)).toEqual([ + 'Invoice €1,190.00 Score 85% Review Match 1190 EUR paid by Example Ltd. on 2026-11-11 with the invoice 2026-0007. ' + + 'Why The payer names the invoice number The amount is what is open' + ]); + }); + + test('shows the payment difference approving a suggestion accepts as paid of its invoice', async () => { + const [, root] = await render(PARTIAL_PAYMENT); + + expect(BankTestingUtilities.getText(root.querySelector('div > p'))).toBe('€300.00 of €800.00 are open.'); + expect(getSuggestions(root)).toEqual([ + 'Invoice €300.00 Score 75% Review Match 300 EUR paid by Sample Corp on 2026-11-05 with the invoice 2026-0005. ' + + 'Payment difference €0.01 ' + + 'Why The payer names the invoice number The counterparty has the name of the recipient or supplier' + ]); + }); + + test('says what of money paid is open with the sign of its amount', async () => { + const [, root] = await render(RENT); + + // the match of the rent was reversed, so all of it is open again + expect(BankTestingUtilities.getText(root.querySelector('div > p'))).toBe('-€850.00 of -€850.00 are open.'); + }); + + test('marks a suggestion of an account as one a person confirms', async () => { + const [, root] = await render(CAPITAL); + + expect(getSuggestions(root)).toEqual([ + 'Account of the books Confirmed by a person €25,000.00 Score 100% Review ' + + 'Match 25000 EUR of Jane Doe on 2026-11-02 with 0800 Subscribed capital. ' + + 'Why A rule of the books names the counterparty or the text ' + + 'A match with an account of the books is never approved automatically.' + ]); + }); + + test('reviews a suggestion with ngx-approval-requests by its request, and shows the match once it is approved there', async () => { + const [fixture, root] = await render(); + + root.querySelector(`button[aria-label="Review: ${'Match 1190 EUR paid by Example Ltd. on 2026-11-11 with the invoice 2026-0007.'}"]`)?.click(); + const requests: TestRequest[] = await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + expect(BankTestingUtilities.findRequests(requests, `${APPROVAL_REQUESTS_BASE_URL}/${IDS.invoiceSuggestion}`)).toHaveLength(1); + const review: HTMLElement | null = root.querySelector('ngx-approval-request'); + // headed below the suggestions it is opened from + expect(review?.querySelector('h3')?.textContent.trim()).toBe('Match 1190 EUR paid by Example Ltd. on 2026-11-11 with the invoice 2026-0007.'); + + FormTestingUtilities.click(review ?? root, 'Approve'); + FormTestingUtilities.click(await waitForDialog(), 'Approve'); + await BankTestingUtilities.render(fixture); + TestBed.inject(HttpTestingController) + .expectOne({ method: 'POST', url: `${APPROVAL_REQUESTS_BASE_URL}/${IDS.invoiceSuggestion}/approve` }) + .flush(toJson(APPROVED_INVOICE_SUGGESTION)); + const answers: Record = { + ...BankBackendUtilities.getAnswers(), + [`GET ${BANK_BASE_URL}/matches?transactionId=${IDS.invoicePayment}`]: BankBackendUtilities.getPage([INVOICE_MATCH]), + [`GET ${BANK_BASE_URL}/transactions/${IDS.invoicePayment}/suggestions`]: { status: 200, body: [] } + }; + await BankTestingUtilities.settle(fixture, answers); + + expect(BankTestingUtilities.getText(root.querySelector('div > p'))).toBe('The transaction is matched in full.'); + expect(BankTestingUtilities.getText(root.querySelector('section > ul'))).toBe('No suggestion waits for a decision.'); + // the review stays, with the outcome of the decision + expect(BankTestingUtilities.getText(root.querySelector('ngx-approval-request'))).toContain('The action ran.'); + }); + + test('proposes a match by hand with an expense of the bookkeeping, and the amount in the decimals of the currency', async () => { + const [fixture, root] = await render(); + const form: HTMLElement = getForm(root); + expect(FormTestingUtilities.findInput(form, 'amount')?.value).toBe('1190'); + + await BankTestingUtilities.select(fixture, form, 'Match with', 'Expense'); + // a part of the supplier, like a user types it, and the option it finds clicked + const target: HTMLInputElement | null = FormTestingUtilities.findInput(form, 'target'); + if (target == undefined) { + throw new Error('There is no target.'); + } + target.focus(); + target.value = 'Miller'; + target.dispatchEvent(new InputEvent('input', { inputType: 'insertText' })); + const searches: TestRequest[] = await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + expect(BankTestingUtilities.findRequests(searches, `${BOOKKEEPING_BASE_URL}/expenses`).at(-1)?.request.params.get('search')).toBe('Miller'); + [...document.querySelectorAll('[role="option"]')] + .find(option => option.textContent.trim() === 'R-2026-11 Property management Miller') + ?.click(); + // the label of the expense chosen is no search, which the api would find nothing for + const afterChoosing: TestRequest[] = await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + expect(BankTestingUtilities.findRequests(afterChoosing, `${BOOKKEEPING_BASE_URL}/expenses`)).toHaveLength(0); + expect(target.value).toBe('R-2026-11 Property management Miller'); + + await BankTestingUtilities.type(fixture, FormTestingUtilities.findInput(form, 'amount'), '100.5'); + await BankTestingUtilities.type(fixture, FormTestingUtilities.findInput(form, 'reason'), ' Paid twice '); + FormTestingUtilities.click(form, 'Propose the match'); + await BankTestingUtilities.render(fixture); + const request: TestRequest = TestBed.inject(HttpTestingController).expectOne({ method: 'POST', url: APPROVAL_REQUESTS_BASE_URL }); + expect(request.request.body).toEqual({ + action: 'bank.match', + input: { transactionId: IDS.invoicePayment, targetType: 'EXPENSE', targetId: IDS.rentExpense, amount: '100.50' }, + reason: 'Paid twice' + }); + // eslint-disable-next-line unicorn/no-null -- the api answers null while there is no decision + request.flush(toJson({ request: APPROVED_INVOICE_SUGGESTION.request, decision: null })); + await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + + expect(form.querySelector('p[role="status"]')?.textContent.trim()) + .toBe('The match was proposed. It is recorded once a person who confirms matches approves it.'); + }); + + test('offers the issued invoices with something open, and proposes nothing above what of the transaction is open', async () => { + const [fixture, root, requests] = await render(); + const form: HTMLElement = getForm(root); + + const [invoices] = BankTestingUtilities.findRequests(requests, `${INVOICING_BASE_URL}/invoices`); + expect(invoices?.request.params.toString()).toBe('page=1&limit=20&issued=true&open=true&type=INVOICE'); + await BankTestingUtilities.choose(fixture, FormTestingUtilities.findInput(form, 'target'), '2026-0007 Example Ltd.'); + await BankTestingUtilities.type(fixture, FormTestingUtilities.findInput(form, 'amount'), '1190.01'); + FormTestingUtilities.click(form, 'Propose the match'); + await BankTestingUtilities.render(fixture); + + TestBed.inject(HttpTestingController).expectNone(({ method }) => method === 'POST'); + }); + + test('offers the open accounts of the books the api finds', async () => { + const [fixture, root] = await render(); + const form: HTMLElement = getForm(root); + + await BankTestingUtilities.select(fixture, form, 'Match with', 'Account of the books'); + let requests: TestRequest[] = await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + expect(BankTestingUtilities.findRequests(requests, `${BOOKKEEPING_BASE_URL}/accounts`).at(-1)?.request.params.toString()) + .toBe('open=true'); + const target: HTMLInputElement | null = FormTestingUtilities.findInput(form, 'target'); + if (target == undefined) { + throw new Error('There is no target.'); + } + target.focus(); + target.value = '1'; + target.dispatchEvent(new InputEvent('input', { inputType: 'insertText' })); + requests = await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + + expect(BankTestingUtilities.findRequests(requests, `${BOOKKEEPING_BASE_URL}/accounts`).at(-1)?.request.params.toString()) + .toBe('search=1&open=true'); + // the money in transit, not the clearing account, which is closed + expect([...document.querySelectorAll('[role="option"]')].map(option => option.textContent.trim())).toEqual(['1360 Money in transit']); + }); + + test('has the api suggest matches again, and shows its message when it refuses', async () => { + const [fixture, root] = await render(); + + FormTestingUtilities.click(root, 'Suggest matches again'); + await BankTestingUtilities.render(fixture); + TestBed.inject(HttpTestingController).expectOne({ method: 'POST', url: `${BANK_BASE_URL}/matches/suggestions` }) + .flush([]); + await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + expect(root.querySelector('section p[role="status"]')?.textContent.trim()).toBe('The matches were suggested again.'); + + FormTestingUtilities.click(root, 'Suggest matches again'); + await BankTestingUtilities.render(fixture); + const message: string = 'This application does not match bank transactions with invoices.'; + const body: ErrorResponseBody = { status: 409, name: 'ConflictError', message, paragraphs: [message] }; + TestBed.inject(HttpTestingController).expectOne({ method: 'POST' }) + .flush(body, { status: 409, statusText: 'Conflict' }); + await BankTestingUtilities.settle(fixture, {}); + expect(BankTestingUtilities.getText(root.querySelector('section [role="alert"]'))).toBe(`Error ${message}`); + }); +}); diff --git a/projects/ngx-bank/bank-matching/bank-matching.component.ts b/projects/ngx-bank/bank-matching/bank-matching.component.ts new file mode 100644 index 0000000..fb6d22c --- /dev/null +++ b/projects/ngx-bank/bank-matching/bank-matching.component.ts @@ -0,0 +1,218 @@ +import { Component, computed, inject, input, InputSignal, linkedSignal, resource, ResourceRef, Signal, signal, WritableSignal } from '@angular/core'; +import { APPROVAL_REQUESTS_CONFIG, ApprovalRequestsConfig, ApprovalRequestService } from '@service-soft/ngx-approval-requests/api'; +import { ApprovalRequestComponent } from '@service-soft/ngx-approval-requests/approval-request'; +import { BankAmountUtilities, BankMatchingLabels, BankMatchUtilities, BankViewDirective } from '@service-soft/ngx-bank/api'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { LoadingDirective } from '@service-soft/ui/loading'; +import { ApprovalRequestDetailsModel, BankMatchModel, BankMatchTargetType, BankTransactionModel, BankTransactionSuggestionModel } from 'zibri-contract'; + +import { ManualMatchComponent } from './manual-match.component'; +import { MatchSuggestionView } from './match-suggestion-view.model'; +import { MatchSuggestionComponent } from './match-suggestion.component'; + +/** + * What the matching loads the matches and the suggestions of a transaction for: the transaction, and the changes and + * decisions of the app, after which they load again. + */ +type MatchingParams = { + /** + * The id of the transaction. + */ + transactionId: string, + /** + * The revision of the BankService. + */ + revision: number, + /** + * The last decision of the ApprovalRequestService, like on a suggestion reviewed here. + */ + decision: ApprovalRequestDetailsModel | undefined +}; + +/** + * The matching of a transaction of the api of provideBankConfig: ``. + * It shows what of the transaction is open, and the matches the api suggests for it that wait for a decision, the most + * confident first, each with its target, score, reasons, amount and the payment difference it accepts. A suggestion + * opens the review of its approval request in ngx-approval-requests, where a person approves or rejects it. A match + * with an account of the books is marked, as the api never approves one on its own. The user proposes a match of their + * own as well, with an invoice, an expense or an account of the books found by the BankService, and has the api + * suggest matches again. + */ +@Component({ + selector: 'ngx-bank-matching', + templateUrl: './bank-matching.component.html', + imports: [ + ApprovalRequestComponent, + ButtonComponent, + CalloutComponent, + HeadingComponent, + LoadingDirective, + ManualMatchComponent, + MatchSuggestionComponent + ], + providers: [ + { + // the review is headed below the suggestions it is opened from, whatever level the approval requests have. + provide: APPROVAL_REQUESTS_CONFIG, + useFactory: (): ApprovalRequestsConfig => { + const matching: BankMatchingComponent = inject(BankMatchingComponent); + return { ...inject(APPROVAL_REQUESTS_CONFIG, { skipSelf: true }), headingLevel: matching.sectionLevel() }; + } + } + ], + host: { class: 'block' } +}) +export class BankMatchingComponent extends BankViewDirective { + private readonly approvalRequestService: ApprovalRequestService = inject(ApprovalRequestService); + + /** + * The transaction to match. + */ + readonly transaction: InputSignal = input.required(); + + /** + * The level of the headings of the suggestions and the form. The review of a suggestion is headed one below. + */ + readonly headingLevel: InputSignal = input(this.config.headingLevel); + + /** + * The level of the heading of the review. + */ + readonly sectionLevel: Signal = computed(() => this.getSectionLevel(this.headingLevel())); + + /** + * The texts of the matching. + */ + protected readonly labels: BankMatchingLabels = this.config.labels.matching; + + private readonly params: Signal = computed(() => ({ + transactionId: this.transaction().id, + revision: this.bankService.revision(), + decision: this.approvalRequestService.lastDecision() + })); + + private readonly matches: ResourceRef = resource({ + params: this.params, + loader: async ({ params }) => await this.bankService.resolveMatches(params.transactionId) + }); + + private readonly suggestions: ResourceRef = resource({ + params: this.params, + loader: async ({ params }) => await this.bankService.resolveSuggestions(params.transactionId) + }); + + /** + * Whether the matches or the suggestions are loading. + */ + protected readonly isLoading: Signal = computed(() => this.matches.isLoading() || this.suggestions.isLoading()); + + /** + * Whether the matches or the suggestions couldn't be loaded. + */ + protected readonly loadingFailed: Signal = computed(() => { + return this.matches.error() != undefined || this.suggestions.error() != undefined; + }); + + /** + * What of the transaction is open, as a decimal string, undefined until its matches are loaded. + */ + protected readonly openAmount: Signal = computed(() => { + const matches: BankMatchModel[] | undefined = this.matches.hasValue() ? this.matches.value() : undefined; + return matches == undefined ? undefined : BankMatchUtilities.resolveOpenAmount(this.transaction(), matches); + }); + + /** + * What the view says about what is open, undefined until it is known. + */ + protected readonly openText: Signal = computed(() => { + const open: string | undefined = this.openAmount(); + if (open == undefined) { + return undefined; + } + if (Number(open) === 0) { + return this.labels.matchedInFull; + } + // both with the sign of the transaction, like its amount everywhere else. + const { amount, currency } = this.transaction(); + return this.labels.open(this.formatAmount(BankAmountUtilities.getSigned(open, amount), currency), this.formatAmount(amount, currency)); + }); + + private readonly scoreFormat: Intl.NumberFormat = new Intl.NumberFormat(this.locale, { style: 'percent', maximumFractionDigits: 0 }); + + /** + * The suggestions waiting for a decision. + */ + protected readonly suggestionViews: Signal = computed(() => { + const suggestions: BankTransactionSuggestionModel[] = this.suggestions.hasValue() ? this.suggestions.value() ?? [] : []; + return suggestions.map(suggestion => this.toSuggestionView(suggestion)); + }); + + /** + * The id of the approval request whose review shows, undefined while none does. It closes with another + * transaction, and stays after a decision, so the review shows its outcome. + */ + protected readonly reviewedId: WritableSignal = linkedSignal({ + source: () => this.transaction().id, + computation: () => undefined + }); + + /** + * What the view last said, read by screen readers as it changes. + */ + protected readonly announcement: WritableSignal = signal(''); + + /** + * Why the api refused to suggest matches again, its paragraphs one per line, or undefined while it refused nothing. + */ + protected readonly suggestError: WritableSignal = signal(undefined); + + /** + * Whether the api is suggesting matches again. + */ + protected readonly suggesting: WritableSignal = signal(false); + + /** + * Opens the review of a suggestion, or closes it. + * @param id - The id of its approval request, or undefined to close it. + */ + protected review(id: string | undefined): void { + this.reviewedId.set(id); + } + + /** + * Has the api suggest matches again, and says so once it did. The suggestions then load again. + */ + protected async suggestAgain(): Promise { + this.suggesting.set(true); + this.suggestError.set(undefined); + this.announcement.set(''); + try { + await this.bankService.suggestMatches(); + this.announcement.set(this.labels.suggested); + } + catch (error) { + this.suggestError.set(this.resolveErrorMessage(error)); + } + finally { + this.suggesting.set(false); + } + } + + private toSuggestionView(suggestion: BankTransactionSuggestionModel): MatchSuggestionView { + const { currency } = this.transaction(); + const { requestId, targetType, summary, amount, confidence, reasons, paymentDifference } = suggestion; + return { + id: requestId, + targetType: this.commonLabels.targetTypes[targetType], + summary, + amount: this.formatAmount(amount, currency), + score: confidence == undefined ? undefined : this.labels.score(this.scoreFormat.format(confidence)), + reasons: reasons.map(reason => this.config.matchReasons[reason] ?? reason), + paymentDifference: paymentDifference == undefined ? undefined : this.formatAmount(paymentDifference, currency), + needsPerson: targetType === BankMatchTargetType.ACCOUNT, + reviewLabel: this.labels.reviewOf(summary) + }; + } +} \ No newline at end of file diff --git a/projects/ngx-bank/bank-matching/bank-matching.stories.ts b/projects/ngx-bank/bank-matching/bank-matching.stories.ts new file mode 100644 index 0000000..c2420f9 --- /dev/null +++ b/projects/ngx-bank/bank-matching/bank-matching.stories.ts @@ -0,0 +1,35 @@ +import { Meta, StoryObj } from '@storybook/angular'; + +import { BankStoryUtilities } from '../fixtures/bank-story.utilities'; +import { CAPITAL, INVOICE_PAYMENT, PARTIAL_PAYMENT, SHORT_PAYMENT } from '../fixtures/bank.fixtures'; +import { BankMatchingComponent } from './bank-matching.component'; + +const meta: Meta = { + title: 'Bank/Matching', + component: BankMatchingComponent, + decorators: [BankStoryUtilities.provideBackend()], + render: args => ({ template: '', props: args }) +}; +export default meta; + +type Story = StoryObj; + +// the payment of an invoice, which the api suggests matching with it. Its review opens below the suggestion. +export const Default: Story = { + args: { transaction: INVOICE_PAYMENT } +}; + +// a deposit of share capital, which a person always confirms. +export const AccountSuggestion: Story = { + args: { transaction: CAPITAL } +}; + +// the rest of a payment matched in part, whose suggestion accepts a cent of the invoice as paid. +export const PaymentDifference: Story = { + args: { transaction: PARTIAL_PAYMENT } +}; + +// a payment matched in full, with nothing left to match. +export const MatchedInFull: Story = { + args: { transaction: SHORT_PAYMENT } +}; diff --git a/projects/ngx-bank/bank-matching/manual-match.component.html b/projects/ngx-bank/bank-matching/manual-match.component.html new file mode 100644 index 0000000..bce5584 --- /dev/null +++ b/projects/ngx-bank/bank-matching/manual-match.component.html @@ -0,0 +1,36 @@ +{{ labels.manual }} + + + + @if (isAccount()) { +

{{ labels.needsPersonHint }}

+ } + + + @if (proposeError(); as message) { + + } +
+ + +

{{ announcement() }}

+
+
\ No newline at end of file diff --git a/projects/ngx-bank/bank-matching/manual-match.component.ts b/projects/ngx-bank/bank-matching/manual-match.component.ts new file mode 100644 index 0000000..509dbbf --- /dev/null +++ b/projects/ngx-bank/bank-matching/manual-match.component.ts @@ -0,0 +1,241 @@ +import { Component, computed, input, InputSignal, linkedSignal, resource, ResourceRef, Signal, signal, WritableSignal } from '@angular/core'; +import { BankAmountUtilities, BankMatchingLabels, BankMatchTargetOption, BankViewDirective } from '@service-soft/ngx-bank/api'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { FormComponent } from '@service-soft/ui/form'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { InputOption } from '@service-soft/ui/input'; +import { InputAutocompleteComponent } from '@service-soft/ui/input-autocomplete'; +import { InputNumberComponent } from '@service-soft/ui/input-number'; +import { InputSelectComponent } from '@service-soft/ui/input-select'; +import { InputStringComponent } from '@service-soft/ui/input-string'; +import { BankMatchTargetType, BankTransactionModel } from 'zibri-contract'; + +/** + * What the targets to choose from are searched for. + */ +type TargetParams = { + /** + * The type of the targets. + */ + type: BankMatchTargetType, + /** + * What the user typed. + */ + search: string +}; + +/** + * What the search of the targets follows: the text of the target, and whether it is the label of a chosen one. + */ +type TargetSearch = { + /** + * The text of the target. + */ + query: string, + /** + * Whether a target is chosen. + */ + isChosen: boolean +}; + +/** + * The form that proposes a match of the user: the type of the target, the target found by the findTargets of the + * BankService among the invoices, expenses or accounts of the books, the amount, what of the transaction is open at + * first, and why. Only used by the matching. + */ +@Component({ + selector: 'ngx-bank-manual-match', + templateUrl: './manual-match.component.html', + imports: [ + ButtonComponent, + CalloutComponent, + FormComponent, + HeadingComponent, + InputAutocompleteComponent, + InputNumberComponent, + InputSelectComponent, + InputStringComponent + ], + host: { class: 'grid gap-3' } +}) +export class ManualMatchComponent extends BankViewDirective { + /** + * The transaction to match. + */ + readonly transaction: InputSignal = input.required(); + + /** + * What of the transaction is open, as a decimal string, undefined while it isn't known. + */ + readonly openAmount: InputSignal = input.required(); + + /** + * The level of the heading of the form. + */ + readonly headingLevel: InputSignal = input.required(); + + /** + * The texts of the matching. + */ + protected readonly labels: BankMatchingLabels = this.config.labels.matching; + + /** + * The types of targets the user matches with. + */ + protected readonly targetTypeOptions: InputOption[] = Object.values(BankMatchTargetType) + .map(type => ({ label: this.commonLabels.targetTypes[type], value: type })); + + /** + * The type of target the user matches with, an invoice at first. + */ + protected readonly targetType: WritableSignal = signal(BankMatchTargetType.INVOICE); + + /** + * What the user typed into the target. It starts over with another type. + */ + protected readonly targetQuery: WritableSignal = linkedSignal({ source: this.targetType, computation: () => '' }); + + /** + * The id of the target the user chose. It starts over with another type. + */ + protected readonly targetId: WritableSignal = linkedSignal({ + source: this.targetType, + computation: () => undefined + }); + + /** + * What the target is called: the name of its type, like 'Invoice'. + */ + protected readonly targetLabel: Signal = computed(() => { + const type: BankMatchTargetType | undefined = this.targetType(); + return type == undefined ? this.labels.targetType : this.commonLabels.targetTypes[type]; + }); + + /** + * Whether the user matches with an account of the books, which a person always confirms. + */ + protected readonly isAccount: Signal = computed(() => this.targetType() === BankMatchTargetType.ACCOUNT); + + // what the targets are searched for. Choosing a target makes its label the text, which no search of the api finds, + // so the search it was chosen from stays, and with it the options that hold its label. + private readonly search: Signal = linkedSignal({ + source: () => ({ query: this.targetQuery(), isChosen: this.targetId() != undefined }), + computation: (source, previous) => source.isChosen && previous != undefined ? previous.value : source.query.trim() + }); + + private readonly targets: ResourceRef = resource({ + params: (): TargetParams | undefined => { + const type: BankMatchTargetType | undefined = this.targetType(); + return type == undefined ? undefined : { type, search: this.search() }; + }, + loader: async ({ params }) => await this.bankService.findTargets(params.type, params.search) + }); + + /** + * The targets to choose from. The ones found last stay while the next search runs, so the list doesn't close while + * the user types. + */ + protected readonly targetOptions: Signal[]> = linkedSignal< + BankMatchTargetOption[] | undefined, + InputOption[] + >({ + source: () => this.targets.hasValue() ? this.targets.value() : undefined, + computation: (targets, previous) => targets?.map(target => ({ label: target.label, value: target.id })) ?? previous?.value ?? [] + }); + + private readonly fractionDigits: Signal = computed(() => { + return BankAmountUtilities.resolveFractionDigits(this.transaction().currency); + }); + + /** + * The largest amount to match: what of the transaction is open. + */ + protected readonly maxAmount: Signal = computed(() => { + const open: string | undefined = this.openAmount(); + return open == undefined ? undefined : Number(open); + }); + + /** + * The amount to match, what of the transaction is open at first, and again once that changed. + */ + protected readonly amount: WritableSignal = linkedSignal(() => this.maxAmount()); + + /** + * The smallest amount to match, and the steps of it: the minor unit of the currency, like 0.01. + */ + protected readonly step: Signal = computed(() => 10 ** -this.fractionDigits()); + + /** + * Whether nothing of the transaction is open, so nothing more can be matched with it. + */ + protected readonly isMatchedInFull: Signal = computed(() => this.maxAmount() === 0); + + /** + * The hint below the amount. + */ + protected readonly amountHint: Signal = computed(() => { + const open: string | undefined = this.openAmount(); + return open == undefined ? undefined : this.labels.amountHint(this.formatAmount(open, this.transaction().currency)); + }); + + /** + * Why the user proposes the match. + */ + protected readonly reason: WritableSignal = signal(''); + + /** + * Whether the match is being proposed. + */ + protected readonly proposing: WritableSignal = signal(false); + + /** + * Why the api refused the match, its paragraphs one per line, or undefined while it refused none. + */ + protected readonly proposeError: WritableSignal = signal(undefined); + + /** + * What the form last said, read by screen readers as it changes. + */ + protected readonly announcement: WritableSignal = signal(''); + + /** + * Proposes the match, which the form only submits with a target and an amount, and says so once it is proposed. It + * then waits for a decision like the suggestions. + */ + protected async propose(): Promise { + const targetType: BankMatchTargetType | undefined = this.targetType(); + const targetId: string | undefined = this.targetId(); + const amount: number | undefined = this.amount(); + if (targetType == undefined || targetId == undefined || amount == undefined) { + return; + } + this.proposing.set(true); + this.proposeError.set(undefined); + this.announcement.set(''); + try { + const reason: string = this.reason().trim(); + const fractionDigits: number = this.fractionDigits(); + const minorUnits: number = BankAmountUtilities.resolveMinorUnits(amount, fractionDigits); + await this.bankService.proposeMatch( + { + transactionId: this.transaction().id, + targetType, + targetId, + amount: BankAmountUtilities.resolveDecimal(minorUnits, fractionDigits) + }, + reason === '' ? undefined : reason + ); + this.targetId.set(undefined); + this.targetQuery.set(''); + this.reason.set(''); + this.announcement.set(this.labels.proposed); + } + catch (error) { + this.proposeError.set(this.resolveErrorMessage(error)); + } + finally { + this.proposing.set(false); + } + } +} \ No newline at end of file diff --git a/projects/ngx-bank/bank-matching/match-suggestion-view.model.ts b/projects/ngx-bank/bank-matching/match-suggestion-view.model.ts new file mode 100644 index 0000000..44b6b8b --- /dev/null +++ b/projects/ngx-bank/bank-matching/match-suggestion-view.model.ts @@ -0,0 +1,41 @@ +/** + * A suggestion as the matching shows it. + */ +export type MatchSuggestionView = { + /** + * The id of its approval request. + */ + id: string, + /** + * What its type of target is called, like 'Invoice'. + */ + targetType: string, + /** + * What it matches, for the reviewer, like 'Match 1190 EUR paid by Example Ltd on 2026-11-11 with the invoice 7'. + */ + summary: string, + /** + * The part of the transaction it matches, formatted. + */ + amount: string, + /** + * How sure the api is of it, like 'Score 75 %', or undefined for a match a user proposed. + */ + score: string | undefined, + /** + * Why the api suggested it, each as the config calls it. + */ + reasons: string[], + /** + * What of its invoice approving it accepts as paid without being paid, formatted, or undefined for none. + */ + paymentDifference: string | undefined, + /** + * Whether it is a match of an account, which a person always confirms. + */ + needsPerson: boolean, + /** + * What screen readers call the button that opens its review. + */ + reviewLabel: string +}; \ No newline at end of file diff --git a/projects/ngx-bank/bank-matching/match-suggestion.component.html b/projects/ngx-bank/bank-matching/match-suggestion.component.html new file mode 100644 index 0000000..be647da --- /dev/null +++ b/projects/ngx-bank/bank-matching/match-suggestion.component.html @@ -0,0 +1,41 @@ +
+ {{ suggestion().targetType }} + @if (suggestion().needsPerson) { + {{ labels.needsPerson }} + } + {{ suggestion().amount }} + @if (suggestion().score; as score) { + {{ score }} + } + +
+

{{ suggestion().summary }}

+@if (suggestion().paymentDifference; as difference) { +
+
{{ labels.paymentDifference }}
+
{{ difference }}
+
+} +@if (suggestion().reasons.length) { +
+ {{ labels.reasons }} +
    + @for (reason of suggestion().reasons; track reason) { +
  • {{ reason }}
  • + } +
+
+} +@if (suggestion().needsPerson) { +

{{ labels.needsPersonHint }}

+} \ No newline at end of file diff --git a/projects/ngx-bank/bank-matching/match-suggestion.component.ts b/projects/ngx-bank/bank-matching/match-suggestion.component.ts new file mode 100644 index 0000000..1e3971a --- /dev/null +++ b/projects/ngx-bank/bank-matching/match-suggestion.component.ts @@ -0,0 +1,34 @@ +import { Component, inject, input, InputSignal, output, OutputEmitterRef } from '@angular/core'; +import { BANK_CONFIG, BankConfig, BankMatchingLabels } from '@service-soft/ngx-bank/api'; +import { BadgeComponent } from '@service-soft/ui/badge'; +import { ButtonComponent } from '@service-soft/ui/button'; + +import { MatchSuggestionView } from './match-suggestion-view.model'; + +/** + * A suggestion of the matching, with the button that opens its review. Only used by the matching. + */ +@Component({ + selector: 'ngx-bank-match-suggestion', + templateUrl: './match-suggestion.component.html', + imports: [BadgeComponent, ButtonComponent], + host: { class: 'grid gap-2' } +}) +export class MatchSuggestionComponent { + private readonly config: BankConfig = inject(BANK_CONFIG); + + /** + * The suggestion. + */ + readonly suggestion: InputSignal = input.required(); + + /** + * Emits when the user wants to review the suggestion. + */ + readonly reviewing: OutputEmitterRef = output(); + + /** + * The texts of the matching. + */ + protected readonly labels: BankMatchingLabels = this.config.labels.matching; +} \ No newline at end of file diff --git a/projects/ngx-bank/bank-matching/ng-package.json b/projects/ngx-bank/bank-matching/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-bank/bank-matching/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-bank/bank-matching/public-api.ts b/projects/ngx-bank/bank-matching/public-api.ts new file mode 100644 index 0000000..f6b3e5f --- /dev/null +++ b/projects/ngx-bank/bank-matching/public-api.ts @@ -0,0 +1 @@ +export * from './bank-matching.component'; diff --git a/projects/ngx-bank/bank-statements/bank-statements.component.html b/projects/ngx-bank/bank-statements/bank-statements.component.html new file mode 100644 index 0000000..0e01d66 --- /dev/null +++ b/projects/ngx-bank/bank-statements/bank-statements.component.html @@ -0,0 +1,44 @@ +
+
+ +
+ @if (loadingFailed()) { + + } + @if (hasNoAccounts()) { + + } @else { + + } + + @if (statement(); as statement) { +
+ + + {{ labels.statementTitle(statement.bankStatementId) }} + + + +
+ } +
diff --git a/projects/ngx-bank/bank-statements/bank-statements.component.spec.ts b/projects/ngx-bank/bank-statements/bank-statements.component.spec.ts new file mode 100644 index 0000000..9062c85 --- /dev/null +++ b/projects/ngx-bank/bank-statements/bank-statements.component.spec.ts @@ -0,0 +1,92 @@ +import { provideHttpClient } from '@angular/common/http'; +import { provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideApprovalRequestsConfig } from '@service-soft/ngx-approval-requests/api'; +import { provideBankConfig } from '@service-soft/ngx-bank/api'; +import { FormTestingUtilities } from 'testing/form'; +import { beforeEach, describe, expect, test } from 'vitest'; + +import { BankBackendUtilities } from '../fixtures/bank-backend.utilities'; +import { BankTestingUtilities } from '../fixtures/bank-testing.utilities'; +import { APPROVAL_REQUESTS_BASE_URL, BANK_BASE_URL, IDS } from '../fixtures/bank.fixtures'; +import { BankStatementsComponent } from './bank-statements.component'; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [BankStatementsComponent] +}) +class HostComponent {} + +async function render(): Promise<[ComponentFixture, HTMLElement, TestRequest[]]> { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + const requests: TestRequest[] = await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + return [fixture, fixture.nativeElement as HTMLElement, requests]; +} + +function getRows(table: Element | null | undefined): string[] { + return [...table?.querySelectorAll('tbody tr') ?? []].map(row => BankTestingUtilities.getText(row)); +} + +describe('BankStatementsComponent', () => { + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + provideBankConfig({ baseUrl: BANK_BASE_URL }), + provideApprovalRequestsConfig({ baseUrl: APPROVAL_REQUESTS_BASE_URL }) + ] + }); + }); + + test('lists the statements of the first account, the latest period first, with their balances', async () => { + const [, root, requests] = await render(); + + const [statements] = BankTestingUtilities.findRequests(requests, `${BANK_BASE_URL}/statements`); + expect(statements?.request.params.toString()).toBe(`page=1&limit=20&accountId=${IDS.business}`); + expect(getRows(root.querySelector('ui-table'))).toEqual([ + // each value after its column, which a phone shows as a card of the row + 'Statement S-2026-011 Period 11/01/2026 – 11/30/2026 Opening balance €10,000.00 Closing balance €37,320.09 Imported 11/30/2026', + 'Statement S-2026-010 Period 10/01/2026 – 10/31/2026 Opening balance €8,000.00 Closing balance €10,000.00 Imported 10/31/2026' + ]); + }); + + test('shows a statement opened from the table with its file and the transactions first imported with it', async () => { + const [fixture, root] = await render(); + + FormTestingUtilities.click(root.querySelector('ui-table') ?? root, 'S-2026-011'); + const requests: TestRequest[] = await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + + const [transactions] = BankTestingUtilities.findRequests(requests, `${BANK_BASE_URL}/transactions`); + expect(transactions?.request.params.toString()).toBe(`page=1&limit=20&statementId=${IDS.statement11}`); + const section: HTMLElement | null = root.querySelector('section'); + expect(section?.querySelector('ui-heading')?.textContent.trim()).toBe('Statement S-2026-011'); + expect(document.activeElement).toBe(section?.querySelector('ui-heading')); + expect(BankTestingUtilities.getText(section?.querySelector('ui-data-list'))).toBe( + 'Period 11/01/2026 – 11/30/2026 Opening balance €10,000.00 Closing balance €37,320.09 Imported 11/30/2026 ' + + 'Format camt.053.001.08 File statement-2026-11.xml' + ); + const table: Element | null | undefined = section?.querySelector('ui-table'); + expect(getRows(table)).toHaveLength(6); + expect(getRows(table)[0]).toBe('Booking date 11/30/2026 Counterparty Payment reference Account fee November Amount -€9.90'); + }); + + test('says when the tenant has no bank account yet', async () => { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + await BankTestingUtilities.settle(fixture, { [`GET ${BANK_BASE_URL}/accounts`]: { status: 200, body: [] } }); + + expect(BankTestingUtilities.getText(fixture.nativeElement as HTMLElement)).toContain('There is no bank account yet.'); + }); + + test('says when the statements couldn\'t be loaded', async () => { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + await BankTestingUtilities.settle(fixture, { + ...BankBackendUtilities.getAnswers(), + [`GET ${BANK_BASE_URL}/statements`]: { status: 503 } + }); + + expect((fixture.nativeElement as HTMLElement).querySelector('[role="alert"]')?.textContent.trim()).toBe('The bank data couldn\'t be loaded.'); + }); +}); \ No newline at end of file diff --git a/projects/ngx-bank/bank-statements/bank-statements.component.ts b/projects/ngx-bank/bank-statements/bank-statements.component.ts new file mode 100644 index 0000000..3bc35a8 --- /dev/null +++ b/projects/ngx-bank/bank-statements/bank-statements.component.ts @@ -0,0 +1,278 @@ +import { afterNextRender, Component, computed, ElementRef, inject, Injector, linkedSignal, resource, ResourceRef, Signal, viewChild, WritableSignal } from '@angular/core'; +import { BankStatementsLabels, BankViewDirective } from '@service-soft/ngx-bank/api'; +import { DataListComponent, DataListItem } from '@service-soft/ui/data-list'; +import { EmptyStateComponent } from '@service-soft/ui/empty-state'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { InputOption } from '@service-soft/ui/input'; +import { InputSelectComponent } from '@service-soft/ui/input-select'; +import { TableColumn, TableComponent } from '@service-soft/ui/table'; +import { BankAccountModel, BankStatementModel, BankTransactionDetailsModel, BankTransactionModel, PaginationResult } from 'zibri-contract'; + +import { StatementRowView } from './statement-row-view.model'; +import { StatementTransactionRowView } from './statement-transaction-row-view.model'; + +/** + * What the statements load: the account, the page, and the changes of the app, after which they load again. + */ +type StatementsParams = { + /** + * The id of the account. + */ + accountId: string, + /** + * The page, from 1 on. + */ + page: number, + /** + * How many statements a page has. + */ + limit: number, + /** + * The revision of the BankService. + */ + revision: number +}; + +/** + * What the transactions of a statement load. + */ +type StatementTransactionsParams = { + /** + * The id of the statement. + */ + statementId: string, + /** + * The page, from 1 on. + */ + page: number, + /** + * How many transactions a page has. + */ + limit: number +}; + +/** + * The statements of a bank account of the api of provideBankConfig: ``. A table lists the + * statements of the account chosen, the first by name at first, the latest period first, with their opening and closing + * balances. A statement opened from the table shows its period, balances and file, and the transactions first imported + * with it. + */ +@Component({ + selector: 'ngx-bank-statements', + templateUrl: './bank-statements.component.html', + imports: [DataListComponent, EmptyStateComponent, HeadingComponent, InputSelectComponent, TableComponent], + host: { class: 'block' } +}) +export class BankStatementsComponent extends BankViewDirective { + private readonly injector: Injector = inject(Injector); + + private readonly statementHeading: Signal | undefined> = viewChild('statementHeading', { read: ElementRef }); + + /** + * The texts of the statements. + */ + protected readonly labels: BankStatementsLabels = this.config.labels.statements; + + /** + * The level of the heading of an opened statement. + */ + protected readonly headingLevel: HeadingLevel = this.config.headingLevel; + + private readonly accounts: ResourceRef = resource({ + params: () => this.bankService.revision(), + loader: async () => await this.bankService.resolveAccounts() + }); + + private readonly accountList: Signal = computed(() => this.accounts.hasValue() ? this.accounts.value() ?? [] : []); + + /** + * The accounts to choose from, by name. + */ + protected readonly accountOptions: Signal[]> = computed(() => { + return this.accountList().map(account => ({ label: `${account.name} (${this.formatIban(account.iban)})`, value: account.id })); + }); + + /** + * Whether the tenant has no bank account yet. + */ + protected readonly hasNoAccounts: Signal = computed(() => this.accounts.hasValue() && !this.accountList().length); + + /** + * The id of the account whose statements show: the first at first. It stays while it is one of the accounts. + */ + protected readonly accountId: WritableSignal = linkedSignal({ + source: this.accountList, + computation: (accounts, previous) => { + const isAccount: boolean = previous?.value != undefined && accounts.some(account => account.id === previous.value); + return isAccount ? previous?.value : accounts[0]?.id; + } + }); + + /** + * How many statements and transactions a page has. + */ + protected readonly pageSize: WritableSignal = linkedSignal(() => this.config.pageSize); + + /** + * The page of the statements. It starts over with another account. + */ + protected readonly page: WritableSignal = linkedSignal({ source: this.accountId, computation: () => 1 }); + + private readonly statements: ResourceRef | undefined> = resource({ + params: (): StatementsParams | undefined => { + const accountId: string | undefined = this.accountId(); + return accountId == undefined + ? undefined + : { accountId, page: this.page(), limit: this.pageSize(), revision: this.bankService.revision() }; + }, + loader: async ({ params }) => await this.bankService.resolveStatements(params) + }); + + private readonly statementList: Signal = computed(() => { + return this.statements.hasValue() ? this.statements.value()?.items ?? [] : []; + }); + + /** + * How many statements the account has on all pages together. + */ + protected readonly totalAmount: Signal = computed(() => { + return this.statements.hasValue() ? this.statements.value()?.totalAmount ?? 0 : 0; + }); + + /** + * Whether the accounts or the statements are loading. + */ + protected readonly isLoading: Signal = computed(() => this.accounts.isLoading() || this.statements.isLoading()); + + /** + * Whether the accounts or the statements couldn't be loaded. + */ + protected readonly loadingFailed: Signal = computed(() => { + return [this.accounts, this.statements, this.transactions].some(loaded => loaded.error() != undefined); + }); + + /** + * The statements of the page. + */ + protected readonly rows: Signal = computed(() => this.statementList().map(statement => this.toRow(statement))); + + /** + * The columns of the table of the statements. + */ + protected readonly columns: TableColumn[] = [ + { key: 'statement', label: this.labels.statement, value: row => row.statement }, + { key: 'period', label: this.commonLabels.period, value: row => row.period }, + { key: 'openingBalance', label: this.commonLabels.openingBalance, value: row => row.openingBalance, align: 'end' }, + { key: 'closingBalance', label: this.commonLabels.closingBalance, value: row => row.closingBalance, align: 'end' }, + { key: 'importedAt', label: this.labels.importedAt, value: row => row.importedAt } + ]; + + /** + * The statement opened from the table, undefined while none is. It closes with another account. + */ + protected readonly statement: WritableSignal = linkedSignal< + string | undefined, + BankStatementModel | undefined + >({ + source: this.accountId, + computation: () => undefined + }); + + /** + * The page of the transactions of the statement. It starts over with another statement. + */ + protected readonly transactionPage: WritableSignal = linkedSignal({ source: this.statement, computation: () => 1 }); + + private readonly transactions: ResourceRef | undefined> = resource({ + params: (): StatementTransactionsParams | undefined => { + const statement: BankStatementModel | undefined = this.statement(); + return statement == undefined ? undefined : { statementId: statement.id, page: this.transactionPage(), limit: this.pageSize() }; + }, + loader: async ({ params }) => await this.bankService.resolveTransactions(params) + }); + + /** + * Whether the transactions of the statement are loading. + */ + protected readonly transactionsLoading: Signal = computed(() => this.transactions.isLoading()); + + /** + * How many transactions were first imported with the statement. + */ + protected readonly transactionTotal: Signal = computed(() => { + return this.transactions.hasValue() ? this.transactions.value()?.totalAmount ?? 0 : 0; + }); + + /** + * The transactions of the page. + */ + protected readonly transactionRows: Signal = computed(() => { + const page: BankTransactionDetailsModel[] = this.transactions.hasValue() ? this.transactions.value()?.items ?? [] : []; + return page.map(details => this.toTransactionRow(details.transaction)); + }); + + /** + * The columns of the table of the transactions. + */ + protected readonly transactionColumns: TableColumn[] = [ + { key: 'bookingDate', label: this.commonLabels.bookingDate, value: row => row.bookingDate }, + { key: 'counterparty', label: this.commonLabels.counterparty, value: row => row.counterparty }, + { key: 'remittanceInformation', label: this.commonLabels.remittanceInformation, value: row => row.remittanceInformation }, + { key: 'amount', label: this.commonLabels.amount, value: row => row.amount, align: 'end' } + ]; + + /** + * What the opened statement holds beside its transactions. + */ + protected readonly details: Signal = computed(() => { + const statement: BankStatementModel | undefined = this.statement(); + if (statement == undefined) { + return []; + } + return [ + { label: this.commonLabels.period, value: this.formatPeriod(statement.periodStart, statement.periodEnd) }, + { label: this.commonLabels.openingBalance, value: this.formatAmount(statement.openingBalance, statement.currency) }, + { label: this.commonLabels.closingBalance, value: this.formatAmount(statement.closingBalance, statement.currency) }, + { label: this.labels.importedAt, value: this.formatDate(statement.importedAt) }, + { label: this.labels.format, value: statement.format }, + ...statement.file == undefined ? [] : [{ label: this.labels.file, value: statement.file.name }] + ]; + }); + + /** + * Gets the key of a row of a table. + * @param row - The row. + * @returns The id of its statement or transaction. + */ + protected readonly getRowKey: (row: StatementRowView | StatementTransactionRowView) => string = row => row.id; + + /** + * Opens a statement of the table, whose heading then takes the focus. + * @param row - The row of the statement. + */ + protected open(row: StatementRowView): void { + this.statement.set(this.statementList().find(statement => statement.id === row.id)); + afterNextRender(() => this.statementHeading()?.nativeElement.focus(), { injector: this.injector }); + } + + private toRow(statement: BankStatementModel): StatementRowView { + return { + id: statement.id, + statement: statement.bankStatementId, + period: this.formatPeriod(statement.periodStart, statement.periodEnd), + openingBalance: this.formatAmount(statement.openingBalance, statement.currency), + closingBalance: this.formatAmount(statement.closingBalance, statement.currency), + importedAt: this.formatDate(statement.importedAt) + }; + } + + private toTransactionRow(transaction: BankTransactionModel): StatementTransactionRowView { + return { + id: transaction.id, + bookingDate: this.formatDay(transaction.bookingDate), + counterparty: transaction.counterpartyName ?? '', + remittanceInformation: transaction.remittanceInformation ?? '', + amount: this.formatAmount(transaction.amount, transaction.currency) + }; + } +} \ No newline at end of file diff --git a/projects/ngx-bank/bank-statements/bank-statements.stories.ts b/projects/ngx-bank/bank-statements/bank-statements.stories.ts new file mode 100644 index 0000000..f4d803f --- /dev/null +++ b/projects/ngx-bank/bank-statements/bank-statements.stories.ts @@ -0,0 +1,27 @@ +import { Meta, StoryObj } from '@storybook/angular'; + +import { BankStoryUtilities } from '../fixtures/bank-story.utilities'; +import { BANK_BASE_URL } from '../fixtures/bank.fixtures'; +import { BankStatementsComponent } from './bank-statements.component'; + +const meta: Meta = { + title: 'Bank/Statements', + component: BankStatementsComponent, + render: () => ({ template: '' }) +}; +export default meta; + +type Story = StoryObj; + +// a statement opens from the table with its transactions. +export const Default: Story = { + decorators: [BankStoryUtilities.provideBackend()] +}; + +export const NoAccounts: Story = { + decorators: [BankStoryUtilities.provideBackend({ [`GET ${BANK_BASE_URL}/accounts`]: { status: 200, body: [] } })] +}; + +export const LoadingFailed: Story = { + decorators: [BankStoryUtilities.provideBackend({ [`GET ${BANK_BASE_URL}/statements`]: { status: 503 } })] +}; \ No newline at end of file diff --git a/projects/ngx-bank/bank-statements/ng-package.json b/projects/ngx-bank/bank-statements/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-bank/bank-statements/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-bank/bank-statements/public-api.ts b/projects/ngx-bank/bank-statements/public-api.ts new file mode 100644 index 0000000..d86207a --- /dev/null +++ b/projects/ngx-bank/bank-statements/public-api.ts @@ -0,0 +1 @@ +export * from './bank-statements.component'; diff --git a/projects/ngx-bank/bank-statements/statement-row-view.model.ts b/projects/ngx-bank/bank-statements/statement-row-view.model.ts new file mode 100644 index 0000000..2e405ba --- /dev/null +++ b/projects/ngx-bank/bank-statements/statement-row-view.model.ts @@ -0,0 +1,29 @@ +/** + * A statement as the table of the statements shows it. + */ +export type StatementRowView = { + /** + * The id of the statement. + */ + id: string, + /** + * The id the bank gave it. + */ + statement: string, + /** + * The period it covers, formatted. + */ + period: string, + /** + * Its opening balance, formatted. + */ + openingBalance: string, + /** + * Its closing balance, formatted. + */ + closingBalance: string, + /** + * When it was imported, formatted. + */ + importedAt: string +}; diff --git a/projects/ngx-bank/bank-statements/statement-transaction-row-view.model.ts b/projects/ngx-bank/bank-statements/statement-transaction-row-view.model.ts new file mode 100644 index 0000000..a00843b --- /dev/null +++ b/projects/ngx-bank/bank-statements/statement-transaction-row-view.model.ts @@ -0,0 +1,25 @@ +/** + * A transaction of a statement as its table shows it. + */ +export type StatementTransactionRowView = { + /** + * The id of the transaction. + */ + id: string, + /** + * The day it was booked on, formatted. + */ + bookingDate: string, + /** + * Who paid or was paid, or an empty string when the bank names nobody. + */ + counterparty: string, + /** + * The text the payer gave it, or an empty string. + */ + remittanceInformation: string, + /** + * Its amount, formatted, negative for money paid. + */ + amount: string +}; diff --git a/projects/ngx-bank/bank-transactions/bank-transactions.component.html b/projects/ngx-bank/bank-transactions/bank-transactions.component.html new file mode 100644 index 0000000..bfc55d8 --- /dev/null +++ b/projects/ngx-bank/bank-transactions/bank-transactions.component.html @@ -0,0 +1,44 @@ +
+
+ + + +
+ @if (loadingFailed()) { + + } + @if (hasNoAccounts()) { + + } @else { + + } + + @if (opened(); as opened) { +
+ + + {{ getTitle(opened) }} + + +
+ } +
diff --git a/projects/ngx-bank/bank-transactions/bank-transactions.component.spec.ts b/projects/ngx-bank/bank-transactions/bank-transactions.component.spec.ts new file mode 100644 index 0000000..48db64c --- /dev/null +++ b/projects/ngx-bank/bank-transactions/bank-transactions.component.spec.ts @@ -0,0 +1,261 @@ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideApprovalRequestsConfig } from '@service-soft/ngx-approval-requests/api'; +import { provideBankConfig } from '@service-soft/ngx-bank/api'; +import { DialogTestingUtilities } from 'testing/dialog'; +import { FormTestingUtilities } from 'testing/form'; +import { FakeAnswer } from 'testing/http'; +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; +import { BankMatchModel, ErrorResponseBody } from 'zibri-contract'; + +import { BankBackendUtilities } from '../fixtures/bank-backend.utilities'; +import { BankTestingUtilities } from '../fixtures/bank-testing.utilities'; +import { APPROVAL_REQUESTS_BASE_URL, BANK_BASE_URL, BANK_URLS, BOOKKEEPING_BASE_URL, IDS, PARTIAL_MATCH, PARTIAL_PAYMENT, RENT_MATCH, toJson, TRANSACTION_DETAILS } from '../fixtures/bank.fixtures'; +import { BankTransactionsComponent } from './bank-transactions.component'; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [BankTransactionsComponent] +}) +class HostComponent {} + +const PARTIAL_REVERSAL: BankMatchModel = { + ...PARTIAL_MATCH, + id: 'd4000000-0000-4000-8000-000000000009', + amount: '-500', + reversesMatchId: IDS.partialMatch, + confirmedAt: new Date('2026-11-25T09:00:00.000Z') +}; + +async function render(): Promise<[ComponentFixture, HTMLElement, TestRequest[]]> { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + const requests: TestRequest[] = await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + return [fixture, fixture.nativeElement as HTMLElement, requests]; +} + +function getRows(root: HTMLElement): string[] { + return [...root.querySelectorAll('ui-table tbody tr')].map(row => BankTestingUtilities.getText(row)); +} + +function findTransactionsRequest(requests: TestRequest[]): TestRequest | undefined { + return BankTestingUtilities.findRequests(requests, `${BANK_BASE_URL}/transactions`).at(-1); +} + +function findDialog(): HTMLDialogElement | undefined { + return [...document.querySelectorAll('dialog[open]')].at(-1) ?? undefined; +} + +// opens the transaction of a day from the table, and waits for its matches and its matching. +async function open( + fixture: ComponentFixture, + root: HTMLElement, + day: string, + answers: Record = BankBackendUtilities.getAnswers() +): Promise { + FormTestingUtilities.click(root.querySelector('ui-table') ?? root, day); + await BankTestingUtilities.settle(fixture, answers); + const details: HTMLElement | null = root.querySelector('ngx-bank-transaction-details'); + if (details == undefined) { + throw new Error('No transaction opened.'); + } + return details; +} + +// presses the button that reverses the first match, and waits for the dialog it opens. +async function openReversal(details: HTMLElement): Promise { + FormTestingUtilities.click(details.querySelector('section') ?? details, 'Reverse'); + return await vi.waitFor(() => { + TestBed.tick(); + const dialog: HTMLDialogElement | undefined = findDialog(); + if (dialog == undefined) { + throw new Error('No dialog opened.'); + } + return dialog; + }); +} + +describe('BankTransactionsComponent', () => { + let removeModalDialogs: () => void; + + beforeEach(() => { + // the transactions of the current month show at first, which is the month of the fixtures here. + vi.useFakeTimers({ toFake: ['Date'], now: new Date('2026-11-25T10:00:00') }); + removeModalDialogs = DialogTestingUtilities.addModalDialogs(); + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + provideBankConfig(BANK_URLS), + provideApprovalRequestsConfig({ baseUrl: APPROVAL_REQUESTS_BASE_URL }) + ] + }); + }); + + afterEach(() => { + vi.useRealTimers(); + removeModalDialogs(); + for (const dialog of document.querySelectorAll('ui-dialog')) { + dialog.remove(); + } + }); + + test('lists a page of the transactions of the current month with what of each is open, as the api answers it', async () => { + const [, root, requests] = await render(); + + expect(findTransactionsRequest(requests)?.request.params.toString()).toBe('page=1&limit=20&from=2026-11-01&until=2026-11-30'); + // no request per transaction + expect(BankTestingUtilities.findRequests(requests, `${BANK_BASE_URL}/matches`)).toHaveLength(0); + expect(getRows(root)).toEqual([ + // each value after its column, which a phone shows as a card of the row + // what is open with the sign of the transaction, like its amount + 'Booking date 11/30/2026 Counterparty Payment reference Account fee November Amount -€9.90 Open -€9.90 Status Open', + 'Booking date 11/20/2026 Counterparty Example Ltd. Payment reference Invoice 2026-0006 Amount €1,189.99 Open €0.00 Status Matched', + 'Booking date 11/11/2026 Counterparty Example Ltd. Payment reference Invoice 2026-0007 Amount €1,190.00 Open €1,190.00 Status Open', + 'Booking date 11/05/2026 Counterparty Sample Corp Payment reference Invoice 2026-0005 Amount €800.00 Open €300.00 ' + + 'Status Partly matched', + 'Booking date 11/03/2026 Counterparty Property management Miller Payment reference Rent November Amount -€850.00 Open -€850.00 ' + + 'Status Open', + 'Booking date 11/02/2026 Counterparty Jane Doe Payment reference Share capital deposit Amount €25,000.00 Open €25,000.00 ' + + 'Status Open' + ]); + }); + + test('has the api filter the transactions by their status, and starts over on the first page', async () => { + const [fixture, root] = await render(); + + await BankTestingUtilities.select(fixture, root, 'Status', 'Matched'); + let requests: TestRequest[] = await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + expect(findTransactionsRequest(requests)?.request.params.get('status')).toBe('MATCHED'); + expect(getRows(root).map(row => row.slice(0, 23))).toEqual(['Booking date 11/20/2026']); + + await BankTestingUtilities.select(fixture, root, 'Status', 'Open'); + requests = await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + expect(findTransactionsRequest(requests)?.request.params.get('status')).toBe('OPEN'); + expect(getRows(root)).toHaveLength(5); + }); + + test('loads the next page from the api', async () => { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + const answers: Record = { + ...BankBackendUtilities.getAnswers(), + [`GET ${BANK_BASE_URL}/transactions`]: { status: 200, body: toJson({ items: TRANSACTION_DETAILS, totalAmount: 26 }) } + }; + await BankTestingUtilities.settle(fixture, answers); + const root: HTMLElement = fixture.nativeElement as HTMLElement; + + root.querySelector('button[aria-label="Page 2"]')?.click(); + const requests: TestRequest[] = await BankTestingUtilities.settle(fixture, answers); + + expect(findTransactionsRequest(requests)?.request.params.toString()).toBe('page=2&limit=20&from=2026-11-01&until=2026-11-30'); + }); + + test('loads the transactions of the account and the period chosen', async () => { + const [fixture, root] = await render(); + + await BankTestingUtilities.select(fixture, root, 'Account', 'Reserve account (DE02 1203 0000 0000 2020 51)'); + const requests: TestRequest[] = await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + + expect(findTransactionsRequest(requests)?.request.params.get('accountId')).toBe(IDS.reserve); + expect(getRows(root)).toEqual(['Nothing found.']); + }); + + test('shows a transaction opened from the table with its matches, a reversal next to the match it reversed', async () => { + const [fixture, root] = await render(); + + const details: HTMLElement = await open(fixture, root, '11/03/2026'); + + expect(root.querySelector('ui-heading.text-headline')?.textContent.trim()).toBe('Transaction of 11/03/2026'); + expect(BankTestingUtilities.getText(details.querySelector('ui-data-list'))).toBe( + 'Amount -€850.00 Open -€850.00 Booking date 11/03/2026 Value date 11/03/2026 Counterparty Property management Miller ' + + 'Payment reference Rent November Reference of the bank REF-0003' + ); + // the expense named as the bookkeeping answers it + expect([...details.querySelectorAll(':scope > section li')].map(match => BankTestingUtilities.getText(match))).toEqual([ + 'Expense R-2026-11 Property management Miller -€850.00 Reversal Confirmed by 5e6f7a8b-9c0d-4e1f-8a2b-3c4d5e6f7a8b on 11/10/2026', + 'Expense R-2026-11 Property management Miller €850.00 Reversed Confirmed by confidence-at-least-0.95 on 11/04/2026' + ]); + // neither a reversal nor a match reversed is reversed again + expect(details.querySelector(':scope > section button[aria-label^="Reverse"]')).toBeNull(); + expect(details.querySelector('ngx-bank-matching')).not.toBeNull(); + }); + + test('names the targets that answer, and shows one the api has no more by its id', async () => { + const [fixture, root] = await render(); + const expenseMatch: BankMatchModel = { ...RENT_MATCH, id: 'd4000000-0000-4000-8000-000000000010', transactionId: IDS.partialPayment, amount: '100' }; + const answers: Record = { + ...BankBackendUtilities.getAnswers(), + [`GET ${BANK_BASE_URL}/matches?transactionId=${IDS.partialPayment}`]: BankBackendUtilities.getPage([expenseMatch, PARTIAL_MATCH]), + [`GET ${BOOKKEEPING_BASE_URL}/expenses/${IDS.rentExpense}`]: { status: 404 } + }; + + const details: HTMLElement = await open(fixture, root, '11/05/2026', answers); + + expect([...details.querySelectorAll(':scope > section li')].map(match => BankTestingUtilities.getText(match).split(' €')[0])).toEqual([ + `Expense ${IDS.rentExpense}`, + 'Invoice 2026-0005 Sample Corp' + ]); + // a missing target is no failure of the view + expect(details.querySelector('[role="alert"]')).toBeNull(); + }); + + test('shows the payment difference a match accepts as paid of its invoice', async () => { + const [fixture, root] = await render(); + + const details: HTMLElement = await open(fixture, root, '11/20/2026'); + + expect(BankTestingUtilities.getText(details.querySelector(':scope > section li'))).toBe( + 'Invoice 2026-0006 Example Ltd. €1,189.99 Reverse Payment difference €0.01 ' + + 'Confirmed by 5e6f7a8b-9c0d-4e1f-8a2b-3c4d5e6f7a8b on 11/21/2026' + ); + }); + + test('reverses a match after the user confirmed it, and shows the transaction open again', async () => { + const [fixture, root] = await render(); + const details: HTMLElement = await open(fixture, root, '11/05/2026'); + expect(BankTestingUtilities.getText(details.querySelector(':scope > section li'))) + .toBe('Invoice 2026-0005 Sample Corp €500.00 Reverse Confirmed by 5e6f7a8b-9c0d-4e1f-8a2b-3c4d5e6f7a8b on 11/06/2026'); + + const dialog: HTMLDialogElement = await openReversal(details); + expect(dialog.querySelector('h2')?.textContent.trim()).toBe('Reverse this match?'); + FormTestingUtilities.click(dialog, 'Reverse'); + await BankTestingUtilities.render(fixture); + const reversal: TestRequest = TestBed.inject(HttpTestingController) + .expectOne({ method: 'POST', url: `${BANK_BASE_URL}/matches/${IDS.partialMatch}/reversal` }); + reversal.flush(toJson(PARTIAL_REVERSAL)); + const answers: Record = { + ...BankBackendUtilities.getAnswers(), + [`GET ${BANK_BASE_URL}/matches?transactionId=${IDS.partialPayment}`]: BankBackendUtilities.getPage([PARTIAL_REVERSAL, PARTIAL_MATCH]), + [`GET ${BANK_BASE_URL}/transactions`]: BankBackendUtilities.getPage(TRANSACTION_DETAILS.map(transaction => { + return transaction.transaction.id === PARTIAL_PAYMENT.id ? { ...transaction, openAmount: '800' } : transaction; + })) + }; + await BankTestingUtilities.settle(fixture, answers); + + expect(details.querySelector(':scope > section p[role="status"]')?.textContent.trim()) + .toBe('The match with 2026-0005 Sample Corp was reversed.'); + expect(BankTestingUtilities.getText(details.querySelector('ui-data-list'))).toContain('Open €800.00'); + expect(getRows(root)[3]).toContain('Open €800.00 Status Open'); + }); + + test('reverses nothing after cancelling, and shows the message of the api when it refuses', async () => { + const [fixture, root] = await render(); + const details: HTMLElement = await open(fixture, root, '11/05/2026'); + + FormTestingUtilities.click(await openReversal(details), 'Cancel'); + await fixture.whenStable(); + TestBed.inject(HttpTestingController).expectNone(({ method }) => method === 'POST'); + + FormTestingUtilities.click(await openReversal(details), 'Reverse'); + await BankTestingUtilities.render(fixture); + const message: string = 'The match d4000000-0000-4000-8000-000000000001 is reversed already.'; + const body: ErrorResponseBody = { status: 409, name: 'ConflictError', message, paragraphs: [message] }; + TestBed.inject(HttpTestingController).expectOne({ method: 'POST' }) + .flush(body, { status: 409, statusText: 'Conflict' }); + await BankTestingUtilities.settle(fixture, {}); + + expect(BankTestingUtilities.getText(details.querySelector(':scope > section [role="alert"]'))).toBe(`Error ${message}`); + }); +}); diff --git a/projects/ngx-bank/bank-transactions/bank-transactions.component.ts b/projects/ngx-bank/bank-transactions/bank-transactions.component.ts new file mode 100644 index 0000000..82c5b03 --- /dev/null +++ b/projects/ngx-bank/bank-transactions/bank-transactions.component.ts @@ -0,0 +1,254 @@ +import { afterNextRender, Component, computed, ElementRef, inject, Injector, linkedSignal, model, ModelSignal, resource, ResourceRef, Signal, signal, viewChild, WritableSignal } from '@angular/core'; +import { ApprovalRequestService } from '@service-soft/ngx-approval-requests/api'; +import { BankAmountUtilities, BankDayUtilities, BankTransactionsLabels, BankViewDirective } from '@service-soft/ngx-bank/api'; +import { EmptyStateComponent } from '@service-soft/ui/empty-state'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { InputOption } from '@service-soft/ui/input'; +import { InputDateRange, InputDateRangeComponent } from '@service-soft/ui/input-date-range'; +import { InputSelectComponent } from '@service-soft/ui/input-select'; +import { TableColumn, TableComponent } from '@service-soft/ui/table'; +import { ApprovalRequestDetailsModel, BankAccountModel, BankTransactionDetailsModel, BankTransactionModel, BankTransactionQueryModel, BankTransactionStatus, PaginationResult } from 'zibri-contract'; + +import { TransactionDetailsComponent } from './transaction-details.component'; +import { TransactionMatchStatus } from './transaction-match-status.type'; +import { TransactionRowView } from './transaction-row-view.model'; +import { TransactionStatusFilter } from './transaction-status-filter.type'; + +/** + * What the transactions load: the page and the filters of the api, and the changes and decisions of the app, after + * which they load again. + */ +type TransactionsParams = BankTransactionQueryModel & { + /** + * The revision of the BankService. + */ + revision: number, + /** + * The last decision of the ApprovalRequestService, like on a suggestion reviewed in the matching. + */ + decision: ApprovalRequestDetailsModel | undefined +}; + +/** + * The transactions of the bank accounts of the api of provideBankConfig: ``. A table lists + * the transactions of an account, or of every account, booked in a period, the current month at first or the one of + * `[(period)]`, the latest first, a page at a time, each with what of it its matches leave open, and filters them by + * whether something of them is open, as the api answers them. A transaction opened from the table shows what the bank + * says of it and its matches, each reversed after a confirmation, and the matching of + * `@service-soft/ngx-bank/bank-matching` below. + */ +@Component({ + selector: 'ngx-bank-transactions', + templateUrl: './bank-transactions.component.html', + imports: [ + EmptyStateComponent, + HeadingComponent, + InputDateRangeComponent, + InputSelectComponent, + TableComponent, + TransactionDetailsComponent + ], + host: { class: 'block' } +}) +export class BankTransactionsComponent extends BankViewDirective { + private readonly approvalRequestService: ApprovalRequestService = inject(ApprovalRequestService); + + private readonly injector: Injector = inject(Injector); + + private readonly transactionHeading: Signal | undefined> = viewChild( + 'transactionHeading', + { read: ElementRef } + ); + + /** + * The days whose transactions show, the current month by default, in the time zone of the browser, as the date + * inputs of ui hold them. A day left out limits nothing. + */ + readonly period: ModelSignal = model(this.getCurrentMonth()); + + /** + * The texts of the transactions. + */ + protected readonly labels: BankTransactionsLabels = this.config.labels.transactions; + + /** + * The level of the heading of an opened transaction. + */ + protected readonly headingLevel: HeadingLevel = this.config.headingLevel; + + /** + * The level of the headings of its sections. + */ + protected readonly sectionLevel: HeadingLevel = this.getSectionLevel(this.config.headingLevel); + + private readonly accounts: ResourceRef = resource({ + params: () => this.bankService.revision(), + loader: async () => await this.bankService.resolveAccounts() + }); + + private readonly accountList: Signal = computed(() => this.accounts.hasValue() ? this.accounts.value() ?? [] : []); + + /** + * Whether the tenant has no bank account yet. + */ + protected readonly hasNoAccounts: Signal = computed(() => this.accounts.hasValue() && !this.accountList().length); + + /** + * The accounts to filter by, every account first. + */ + protected readonly accountOptions: Signal[]> = computed(() => [ + { label: this.commonLabels.allAccounts, value: '' }, + ...this.accountList().map(account => ({ label: `${account.name} (${this.formatIban(account.iban)})`, value: account.id })) + ]); + + /** + * The id of the account whose transactions show, an empty string for every account. + */ + protected readonly accountId: WritableSignal = signal(''); + + /** + * The statuses to filter by. + */ + protected readonly statusOptions: InputOption[] = [ + { label: this.labels.allStatuses, value: 'all' }, + { label: this.labels.open, value: BankTransactionStatus.OPEN }, + { label: this.labels.matched, value: BankTransactionStatus.MATCHED } + ]; + + /** + * Which transactions show by their status, every one at first. + */ + protected readonly status: WritableSignal = signal('all'); + + /** + * How many transactions a page of the table has. + */ + protected readonly pageSize: WritableSignal = linkedSignal(() => this.config.pageSize); + + /** + * The page of the table. It starts over when a filter changes. + */ + protected readonly page: WritableSignal = linkedSignal({ + source: () => [this.accountId(), this.period(), this.status(), this.pageSize()], + computation: () => 1 + }); + + private readonly transactions: ResourceRef | undefined> = resource({ + params: (): TransactionsParams => { + const { start, end } = this.period(); + const accountId: string | undefined = this.accountId(); + const status: TransactionStatusFilter | undefined = this.status(); + return { + page: this.page(), + limit: this.pageSize(), + accountId: accountId === '' ? undefined : accountId, + from: start == undefined ? undefined : BankDayUtilities.resolveDay(start), + until: end == undefined ? undefined : BankDayUtilities.resolveDay(end), + status: status === 'all' ? undefined : status, + revision: this.bankService.revision(), + decision: this.approvalRequestService.lastDecision() + }; + }, + loader: async ({ params }) => await this.bankService.resolveTransactions(params) + }); + + private readonly transactionList: Signal = computed(() => { + return this.transactions.hasValue() ? this.transactions.value()?.items ?? [] : []; + }); + + /** + * How many transactions match the filters on all pages together. + */ + protected readonly totalAmount: Signal = computed(() => { + return this.transactions.hasValue() ? this.transactions.value()?.totalAmount ?? 0 : 0; + }); + + /** + * Whether the accounts or the transactions are loading. + */ + protected readonly isLoading: Signal = computed(() => this.accounts.isLoading() || this.transactions.isLoading()); + + /** + * Whether the accounts or the transactions couldn't be loaded. + */ + protected readonly loadingFailed: Signal = computed(() => { + return this.accounts.error() != undefined || this.transactions.error() != undefined; + }); + + /** + * The transactions of the page. + */ + protected readonly rows: Signal = computed(() => this.transactionList().map(details => this.toRow(details))); + + /** + * The columns of the table. + */ + protected readonly columns: TableColumn[] = [ + { key: 'bookingDate', label: this.commonLabels.bookingDate, value: row => row.bookingDate }, + { key: 'counterparty', label: this.commonLabels.counterparty, value: row => row.counterparty }, + { key: 'remittanceInformation', label: this.commonLabels.remittanceInformation, value: row => row.remittanceInformation }, + { key: 'amount', label: this.commonLabels.amount, value: row => row.amount, align: 'end' }, + { key: 'openAmount', label: this.commonLabels.openAmount, value: row => row.openAmount, align: 'end' }, + { key: 'status', label: this.labels.status, value: row => row.status } + ]; + + /** + * The transaction opened from the table, undefined while none is. It stays while the table loads again or shows + * another page, so its matching keeps what it announced, like after a match was approved. + */ + protected readonly opened: WritableSignal = signal(undefined); + + /** + * Gets the key of a row of the table. + * @param row - The row. + * @returns The id of its transaction. + */ + protected readonly getRowKey: (row: TransactionRowView) => string = row => row.id; + + /** + * Opens a transaction of the table, whose heading then takes the focus. + * @param row - The row of the transaction. + */ + protected open(row: TransactionRowView): void { + this.opened.set(this.transactionList().find(details => details.transaction.id === row.id)?.transaction); + afterNextRender(() => this.transactionHeading()?.nativeElement.focus(), { injector: this.injector }); + } + + /** + * Gets the heading of a transaction. + * @param transaction - The transaction. + * @returns Its heading, by the day it was booked on. + */ + protected getTitle(transaction: BankTransactionModel): string { + return this.labels.transactionTitle(this.formatDay(transaction.bookingDate)); + } + + private resolveStatus(details: BankTransactionDetailsModel): TransactionMatchStatus { + const open: number = Number(details.openAmount); + if (open === 0) { + return 'matched'; + } + return open === Math.abs(Number(details.transaction.amount)) ? 'open' : 'partlyMatched'; + } + + private toRow(details: BankTransactionDetailsModel): TransactionRowView { + const { transaction, openAmount } = details; + return { + id: transaction.id, + bookingDate: this.formatDay(transaction.bookingDate), + counterparty: transaction.counterpartyName ?? '', + remittanceInformation: transaction.remittanceInformation ?? '', + amount: this.formatAmount(transaction.amount, transaction.currency), + openAmount: this.formatAmount(BankAmountUtilities.getSigned(openAmount, transaction.amount), transaction.currency), + status: this.labels[this.resolveStatus(details)] + }; + } + + private getCurrentMonth(): InputDateRange { + const today: Date = new Date(); + return { + start: new Date(today.getFullYear(), today.getMonth(), 1), + end: new Date(today.getFullYear(), today.getMonth() + 1, 0) + }; + } +} diff --git a/projects/ngx-bank/bank-transactions/bank-transactions.stories.ts b/projects/ngx-bank/bank-transactions/bank-transactions.stories.ts new file mode 100644 index 0000000..8475fa1 --- /dev/null +++ b/projects/ngx-bank/bank-transactions/bank-transactions.stories.ts @@ -0,0 +1,40 @@ +import { InputDateRange } from '@service-soft/ui/input-date-range'; +import { Meta, StoryObj } from '@storybook/angular'; + +import { BankStoryUtilities } from '../fixtures/bank-story.utilities'; +import { BANK_BASE_URL, toJson, TRANSACTION_DETAILS } from '../fixtures/bank.fixtures'; +import { BankTransactionsComponent } from './bank-transactions.component'; + +// the month of the fixtures, whatever month it is. +const NOVEMBER: InputDateRange = { start: new Date(2026, 10, 1), end: new Date(2026, 10, 30) }; + +const meta: Meta = { + title: 'Bank/Transactions', + component: BankTransactionsComponent, + render: () => ({ template: '', props: { period: NOVEMBER } }) +}; +export default meta; + +type Story = StoryObj; + +// a transaction opens from the table with its matches and its matching. +export const Default: Story = { + decorators: [BankStoryUtilities.provideBackend()] +}; + +// more transactions than a page holds, which the api answers a page at a time. +export const Pages: Story = { + decorators: [ + BankStoryUtilities.provideBackend({ + [`GET ${BANK_BASE_URL}/transactions`]: { status: 200, body: toJson({ items: TRANSACTION_DETAILS, totalAmount: 86 }) } + }) + ] +}; + +export const NoAccounts: Story = { + decorators: [BankStoryUtilities.provideBackend({ [`GET ${BANK_BASE_URL}/accounts`]: { status: 200, body: [] } })] +}; + +export const LoadingFailed: Story = { + decorators: [BankStoryUtilities.provideBackend({ [`GET ${BANK_BASE_URL}/transactions`]: { status: 503 } })] +}; \ No newline at end of file diff --git a/projects/ngx-bank/bank-transactions/ng-package.json b/projects/ngx-bank/bank-transactions/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-bank/bank-transactions/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-bank/bank-transactions/public-api.ts b/projects/ngx-bank/bank-transactions/public-api.ts new file mode 100644 index 0000000..1d7dfa9 --- /dev/null +++ b/projects/ngx-bank/bank-transactions/public-api.ts @@ -0,0 +1 @@ +export * from './bank-transactions.component'; diff --git a/projects/ngx-bank/bank-transactions/transaction-details.component.html b/projects/ngx-bank/bank-transactions/transaction-details.component.html new file mode 100644 index 0000000..8db134a --- /dev/null +++ b/projects/ngx-bank/bank-transactions/transaction-details.component.html @@ -0,0 +1,58 @@ + + +
+ {{ labels.matches }} + @if (loadingFailed()) { + + } + @if (reverseError(); as message) { +
+ +

{{ message }}

+
+ } + +

{{ announcement() }}

+ +
+ +
    + @for (match of matches(); track match.id) { +
  • +
    + {{ match.targetType }} + {{ match.target }} + {{ match.amount }} + @if (match.badge; as badge) { + {{ badge }} + } + @if (match.canReverse) { + + } +
    + @if (match.difference; as difference) { +
    +
    {{ labels.difference }}
    +
    {{ difference }}
    +
    + } +

    {{ match.confirmed }}

    +
  • + } @empty { +
  • {{ labels.noMatches }}
  • + } +
+
+
+ + diff --git a/projects/ngx-bank/bank-transactions/transaction-details.component.ts b/projects/ngx-bank/bank-transactions/transaction-details.component.ts new file mode 100644 index 0000000..202291e --- /dev/null +++ b/projects/ngx-bank/bank-transactions/transaction-details.component.ts @@ -0,0 +1,230 @@ +import { Component, computed, inject, input, InputSignal, resource, ResourceRef, Signal, signal, WritableSignal } from '@angular/core'; +import { ApprovalRequestService } from '@service-soft/ngx-approval-requests/api'; +import { BankAmountUtilities, BankMatchUtilities, BankTransactionsLabels, BankViewDirective } from '@service-soft/ngx-bank/api'; +import { BankMatchingComponent } from '@service-soft/ngx-bank/bank-matching'; +import { BadgeComponent } from '@service-soft/ui/badge'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { DataListComponent, DataListItem } from '@service-soft/ui/data-list'; +import { ConfirmDialogComponent, DialogService } from '@service-soft/ui/dialog'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { LoadingDirective } from '@service-soft/ui/loading'; +import { ApprovalRequestDetailsModel, BankMatchModel, BankTransactionModel } from 'zibri-contract'; + +import { TransactionMatchView } from './transaction-match-view.model'; + +/** + * What the matches of the transaction load for: the transaction, and the changes and decisions of the app, after which + * they load again. + */ +type MatchesParams = { + /** + * The id of the transaction. + */ + transactionId: string, + /** + * The revision of the BankService. + */ + revision: number, + /** + * The last decision of the ApprovalRequestService, like on a suggestion reviewed in the matching. + */ + decision: ApprovalRequestDetailsModel | undefined +}; + +/** + * What the targets and the people of the matches are called, by the id of the match. + */ +type MatchNames = Map; + +/** + * What the target and the person of a match are called. + */ +type MatchName = { + /** + * What the target is called. + */ + target: string, + /** + * Who confirmed the match. + */ + confirmedBy: string +}; + +/** + * A transaction opened from the transactions: what the bank says of it, its matches, each reversed after a + * confirmation, and its matching. Only used by the transactions. + */ +@Component({ + selector: 'ngx-bank-transaction-details', + templateUrl: './transaction-details.component.html', + imports: [ + BadgeComponent, + BankMatchingComponent, + ButtonComponent, + CalloutComponent, + DataListComponent, + HeadingComponent, + LoadingDirective + ], + host: { class: 'grid gap-6' } +}) +export class TransactionDetailsComponent extends BankViewDirective { + private readonly dialogService: DialogService = inject(DialogService); + + private readonly approvalRequestService: ApprovalRequestService = inject(ApprovalRequestService); + + /** + * The transaction. + */ + readonly transaction: InputSignal = input.required(); + + /** + * The level of the headings of its sections. + */ + readonly headingLevel: InputSignal = input.required(); + + /** + * The texts of the transactions. + */ + protected readonly labels: BankTransactionsLabels = this.config.labels.transactions; + + // the matches of this one transaction, which the list of the transactions doesn't load. + private readonly loadedMatches: ResourceRef = resource({ + params: (): MatchesParams => ({ + transactionId: this.transaction().id, + revision: this.bankService.revision(), + decision: this.approvalRequestService.lastDecision() + }), + loader: async ({ params }) => await this.bankService.resolveMatches(params.transactionId) + }); + + private readonly matchList: Signal = computed(() => { + return this.loadedMatches.hasValue() ? this.loadedMatches.value() : undefined; + }); + + /** + * Whether the matches are loading. + */ + protected readonly isLoading: Signal = computed(() => this.loadedMatches.isLoading()); + + /** + * Whether the matches couldn't be loaded. + */ + protected readonly loadingFailed: Signal = computed(() => this.loadedMatches.error() != undefined); + + /** + * What the bank says of the transaction, and what of it its matches leave open once they are loaded. + */ + protected readonly details: Signal = computed(() => { + const transaction: BankTransactionModel = this.transaction(); + const matches: BankMatchModel[] | undefined = this.matchList(); + return [ + { label: this.commonLabels.amount, value: this.formatAmount(transaction.amount, transaction.currency) }, + ...this.toItem(this.commonLabels.openAmount, matches == undefined + ? undefined + : this.formatAmount( + BankAmountUtilities.getSigned(BankMatchUtilities.resolveOpenAmount(transaction, matches), transaction.amount), + transaction.currency + )), + { label: this.commonLabels.bookingDate, value: this.formatDay(transaction.bookingDate) }, + ...this.toItem( + this.commonLabels.valueDate, + transaction.valueDate == undefined ? undefined : this.formatDay(transaction.valueDate) + ), + ...this.toItem(this.commonLabels.counterparty, transaction.counterpartyName), + ...this.toItem(this.commonLabels.counterpartyIban, transaction.counterpartyIban == undefined + ? undefined + : this.formatIban(transaction.counterpartyIban)), + ...this.toItem(this.commonLabels.remittanceInformation, transaction.remittanceInformation), + ...this.toItem(this.commonLabels.endToEndId, transaction.endToEndId), + ...this.toItem(this.commonLabels.bankReference, transaction.bankReference) + ]; + }); + + private readonly names: ResourceRef = resource({ + params: () => this.matchList(), + loader: async ({ params }) => await this.resolveNames(params) + }); + + /** + * The matches of the transaction, the latest confirmed first. + */ + protected readonly matches: Signal = computed(() => { + const matches: BankMatchModel[] = this.matchList() ?? []; + const names: MatchNames = (this.names.hasValue() ? this.names.value() : undefined) ?? new Map(); + return matches.map(match => this.toMatchView(match, matches, names.get(match.id))); + }); + + /** + * What the view last said about a reversal, read by screen readers as it changes. + */ + protected readonly announcement: WritableSignal = signal(''); + + /** + * Why the api refused the last reversal, its paragraphs one per line, or undefined while it refused none. + */ + protected readonly reverseError: WritableSignal = signal(undefined); + + /** + * Reverses a match after the user confirmed it, and says so once it is reversed. The matches and the transactions + * then load again, with the reversal. + * @param match - The match. + */ + protected async reverse(match: TransactionMatchView): Promise { + const confirmed: boolean | undefined = await this.dialogService + .open(ConfirmDialogComponent, this.config.reverseMatchConfirmDialogData) + .closed; + if (confirmed !== true) { + return; + } + this.reverseError.set(undefined); + this.announcement.set(''); + try { + await this.bankService.reverseMatch(match.id); + this.announcement.set(this.labels.matchReversed(match.target)); + } + catch (error) { + this.reverseError.set(this.resolveErrorMessage(error)); + } + } + + private async resolveNames(matches: BankMatchModel[]): Promise { + const [targets, people] = await Promise.all([ + this.bankService.resolveTargetNames(matches), + Promise.all(matches.map(async match => await this.approvalRequestService.resolveActorName(match.confirmedBy, match.confirmedByKind))) + ]); + return new Map(matches.map((match, index): [string, MatchName] => [ + match.id, + { target: targets.get(match.targetId) ?? match.targetId, confirmedBy: people[index] ?? match.confirmedBy } + ])); + } + + private toMatchView(match: BankMatchModel, matches: BankMatchModel[], name: MatchName | undefined): TransactionMatchView { + const isReversal: boolean = match.reversesMatchId != undefined; + const isReversed: boolean = matches.some(candidate => candidate.reversesMatchId === match.id); + const target: string = name?.target ?? match.targetId; + return { + id: match.id, + targetType: this.commonLabels.targetTypes[match.targetType], + target, + amount: this.formatAmount(match.amount, match.currency), + difference: match.difference == undefined ? undefined : this.formatAmount(match.difference, match.currency), + confirmed: this.labels.confirmedBy(name?.confirmedBy ?? match.confirmedBy, this.formatDate(match.confirmedAt)), + badge: this.resolveBadge(isReversal, isReversed), + canReverse: !isReversal && !isReversed, + reverseLabel: this.labels.reverseMatch(target) + }; + } + + private resolveBadge(isReversal: boolean, isReversed: boolean): string | undefined { + if (isReversal) { + return this.labels.reversal; + } + return isReversed ? this.labels.reversed : undefined; + } + + private toItem(label: string, value: string | null | undefined): DataListItem[] { + return value == undefined || value === '' ? [] : [{ label, value }]; + } +} diff --git a/projects/ngx-bank/bank-transactions/transaction-match-status.type.ts b/projects/ngx-bank/bank-transactions/transaction-match-status.type.ts new file mode 100644 index 0000000..eb26def --- /dev/null +++ b/projects/ngx-bank/bank-transactions/transaction-match-status.type.ts @@ -0,0 +1,4 @@ +/** + * How much of a transaction is matched: nothing, a part, or all of it. + */ +export type TransactionMatchStatus = 'open' | 'partlyMatched' | 'matched'; diff --git a/projects/ngx-bank/bank-transactions/transaction-match-view.model.ts b/projects/ngx-bank/bank-transactions/transaction-match-view.model.ts new file mode 100644 index 0000000..978a397 --- /dev/null +++ b/projects/ngx-bank/bank-transactions/transaction-match-view.model.ts @@ -0,0 +1,41 @@ +/** + * A match of a transaction as its details show it. + */ +export type TransactionMatchView = { + /** + * The id of the match. + */ + id: string, + /** + * What its type of target is called, like 'Invoice'. + */ + targetType: string, + /** + * What its target is called, like the number of the invoice. + */ + target: string, + /** + * The part of the transaction it matches, formatted, negative for a reversal. + */ + amount: string, + /** + * What it accepts as paid of an invoice without being paid, formatted, or undefined for none. + */ + difference: string | undefined, + /** + * Who confirmed it, and when. + */ + confirmed: string, + /** + * The badge of a reversal, or of a match that was reversed, or undefined for neither. + */ + badge: string | undefined, + /** + * Whether it can be reversed: it is no reversal, and was not reversed. + */ + canReverse: boolean, + /** + * What screen readers call the button that reverses it. + */ + reverseLabel: string +}; diff --git a/projects/ngx-bank/bank-transactions/transaction-row-view.model.ts b/projects/ngx-bank/bank-transactions/transaction-row-view.model.ts new file mode 100644 index 0000000..47cacf3 --- /dev/null +++ b/projects/ngx-bank/bank-transactions/transaction-row-view.model.ts @@ -0,0 +1,33 @@ +/** + * A transaction as the table of the transactions shows it. + */ +export type TransactionRowView = { + /** + * The id of the transaction. + */ + id: string, + /** + * The day it was booked on, formatted. + */ + bookingDate: string, + /** + * Who paid or was paid, or an empty string when the bank names nobody. + */ + counterparty: string, + /** + * The text the payer gave it, or an empty string. + */ + remittanceInformation: string, + /** + * Its amount, formatted, negative for money paid. + */ + amount: string, + /** + * What of it is open, formatted. + */ + openAmount: string, + /** + * How much of it is matched, as the config calls it. + */ + status: string +}; diff --git a/projects/ngx-bank/bank-transactions/transaction-status-filter.type.ts b/projects/ngx-bank/bank-transactions/transaction-status-filter.type.ts new file mode 100644 index 0000000..c5f44fd --- /dev/null +++ b/projects/ngx-bank/bank-transactions/transaction-status-filter.type.ts @@ -0,0 +1,7 @@ +import { BankTransactionStatus } from 'zibri-contract'; + +/** + * Which transactions the filter of their status shows: every one, or those of a status the api filters by, with + * something open or matched in full. + */ +export type TransactionStatusFilter = 'all' | BankTransactionStatus; diff --git a/projects/ngx-bank/fixtures/bank-backend.utilities.ts b/projects/ngx-bank/fixtures/bank-backend.utilities.ts new file mode 100644 index 0000000..b9a3900 --- /dev/null +++ b/projects/ngx-bank/fixtures/bank-backend.utilities.ts @@ -0,0 +1,124 @@ +import { HttpRequest } from '@angular/common/http'; +import { HttpTestingController, TestRequest } from '@angular/common/http/testing'; +import { Provider } from '@angular/core'; +import { FakeAnswer, HttpTestingUtilities } from 'testing/http'; + +import { BankTransactionDetailsModel } from 'zibri-contract'; + +import { ACCOUNTS, APPROVAL_REQUESTS_BASE_URL, BANK_BASE_URL, BOOKKEEPING_ACCOUNTS, BOOKKEEPING_BASE_URL, IDS, INVOICES, INVOICING_BASE_URL, MATCHES, OPEN_INVOICES, RENT_EXPENSE, STATEMENTS, SUGGESTIONS, toJson, TRANSACTION_DETAILS, TRANSACTION_SUGGESTIONS, TRANSACTIONS } from './bank.fixtures'; + +/** + * A backend for the specs and stories that answers like the bank, approval request, invoicing and bookkeeping routes + * would, from the fixtures. An answer is named by the method and the path of its request, like + * 'GET /api/bank/accounts', and may name values of the query the request needs to have, like + * 'GET /api/bank/matches?transactionId=…', for the routes whose answer depends on one. The answer naming the most + * values a request has wins. + */ +export abstract class BankBackendUtilities { + /** + * Gets the answers of the routes from the fixtures: the accounts, the statements and the transactions of the + * business account, filtered by their status, the matches and the suggestions of each transaction, the approval + * requests of the suggestions, and the invoices, the expense and the accounts of the books to match with. + * @returns The answers. + */ + static getAnswers(): Record { + const matches: [string, FakeAnswer][] = Object.entries(MATCHES).map(([transactionId, items]) => [ + `GET ${BANK_BASE_URL}/matches?transactionId=${transactionId}`, + this.getPage(items) + ]); + const suggestions: [string, FakeAnswer][] = TRANSACTIONS.map(transaction => [ + `GET ${BANK_BASE_URL}/transactions/${transaction.id}/suggestions`, + { status: 200, body: toJson(TRANSACTION_SUGGESTIONS[transaction.id] ?? []) } + ]); + const matched: BankTransactionDetailsModel[] = TRANSACTION_DETAILS.filter(details => Number(details.openAmount) === 0); + return { + [`GET ${BANK_BASE_URL}/accounts`]: { status: 200, body: toJson(ACCOUNTS) }, + [`GET ${BANK_BASE_URL}/statements`]: this.getPage(STATEMENTS), + [`GET ${BANK_BASE_URL}/statements?accountId=${IDS.reserve}`]: this.getPage([]), + [`GET ${BANK_BASE_URL}/transactions`]: this.getPage(TRANSACTION_DETAILS), + [`GET ${BANK_BASE_URL}/transactions?status=OPEN`]: this.getPage(TRANSACTION_DETAILS.filter(details => !matched.includes(details))), + [`GET ${BANK_BASE_URL}/transactions?status=MATCHED`]: this.getPage(matched), + [`GET ${BANK_BASE_URL}/transactions?statementId=${IDS.statement10}`]: this.getPage([]), + [`GET ${BANK_BASE_URL}/transactions?accountId=${IDS.reserve}`]: this.getPage([]), + ...Object.fromEntries(suggestions), + ...Object.fromEntries(matches), + ...Object.fromEntries(SUGGESTIONS.map(request => [ + `GET ${APPROVAL_REQUESTS_BASE_URL}/${request.id}`, + // eslint-disable-next-line unicorn/no-null -- the api answers null while there is no decision + { status: 200, body: toJson({ request, decision: null }) } + ])), + [`GET ${INVOICING_BASE_URL}/invoices`]: this.getPage(OPEN_INVOICES), + ...Object.fromEntries(INVOICES.map(invoice => [ + `GET ${INVOICING_BASE_URL}/invoices/${invoice.id}`, + { status: 200, body: toJson(invoice) } + ])), + [`GET ${BOOKKEEPING_BASE_URL}/expenses`]: this.getPage([RENT_EXPENSE]), + [`GET ${BOOKKEEPING_BASE_URL}/expenses/${RENT_EXPENSE.id}`]: { status: 200, body: toJson(RENT_EXPENSE) }, + [`GET ${BOOKKEEPING_BASE_URL}/accounts?open=true`]: { + status: 200, + body: toJson(BOOKKEEPING_ACCOUNTS.filter(account => account.closedAt == undefined)) + }, + ...Object.fromEntries(BOOKKEEPING_ACCOUNTS.map(account => [ + `GET ${BOOKKEEPING_BASE_URL}/accounts/${account.id}`, + { status: 200, body: toJson(account) } + ])) + }; + } + + /** + * Gets the answer of a page of a list that holds all of its items. + * @param items - The items. + * @returns The answer, a PaginationResult as json. + */ + static getPage(items: unknown[]): FakeAnswer { + return { status: 200, body: toJson({ items, totalAmount: items.length }) }; + } + + /** + * Finds the answer of a request. + * @param request - The request. + * @param answers - The answers, by the method, the path and the values of the query they need. + * @returns The answer naming the most values of the query of the request, or undefined for none. + */ + static findAnswer(request: HttpRequest, answers: Record): FakeAnswer | undefined { + const url: URL = new URL(request.urlWithParams, document.baseURI); + const matching: [URL, FakeAnswer][] = Object.entries(answers).flatMap(([key, answer]): [URL, FakeAnswer][] => { + const [method, path = ''] = key.split(' '); + const keyUrl: URL = new URL(path, document.baseURI); + const isMatch: boolean = method === request.method + && keyUrl.pathname === url.pathname + && [...keyUrl.searchParams].every(([name, value]) => url.searchParams.get(name) === value); + return isMatch ? [[keyUrl, answer]] : []; + }); + const best: [URL, FakeAnswer] | undefined = matching.reduce<[URL, FakeAnswer] | undefined>((found, candidate) => { + return found == undefined || [...candidate[0].searchParams].length > [...found[0].searchParams].length ? candidate : found; + }, undefined); + return best?.[1]; + } + + /** + * Provides a backend that answers requests itself, right away, so a story shows the state they lead to once it + * rendered. The answers of a story replace those of its meta, see HttpTestingUtilities.provideBackend. + * @param answers - What to answer. + * @returns The provider. A request it has no answer for fails with 404. + */ + static provideAnswers(answers: Record): Provider { + return HttpTestingUtilities.provideBackend(request => this.findAnswer(request, answers)); + } + + /** + * Answers every open request of a HttpTestingController there is an answer for. + * @param controller - The controller of the test. + * @param answers - What to answer. + * @returns The requests it answered, to check what they sent. Requests without an answer stay open. + */ + static flushAll(controller: HttpTestingController, answers: Record): TestRequest[] { + const requests: TestRequest[] = controller.match(request => this.findAnswer(request, answers) != undefined); + for (const request of requests) { + const answer: FakeAnswer = this.findAnswer(request.request, answers) ?? { status: 404 }; + // eslint-disable-next-line unicorn/no-null -- an answer without a body is null, as the browser hands it over + request.flush(answer.body ?? null, { status: answer.status, statusText: answer.status < 400 ? 'OK' : 'Error' }); + } + return requests; + } +} \ No newline at end of file diff --git a/projects/ngx-bank/fixtures/bank-story.utilities.ts b/projects/ngx-bank/fixtures/bank-story.utilities.ts new file mode 100644 index 0000000..8b54055 --- /dev/null +++ b/projects/ngx-bank/fixtures/bank-story.utilities.ts @@ -0,0 +1,35 @@ +import { provideHttpClient } from '@angular/common/http'; +import { provideApprovalRequestsConfig } from '@service-soft/ngx-approval-requests/api'; +import { BankConfigChanges, provideBankConfig } from '@service-soft/ngx-bank/api'; +import { applicationConfig } from '@storybook/angular'; +import { FakeAnswer } from 'testing/http'; + +import { BankBackendUtilities } from './bank-backend.utilities'; +import { APPROVAL_REQUESTS_BASE_URL, BANK_URLS } from './bank.fixtures'; + +/** + * Utilities for the stories of the views of the bank, which render them against the answers of the fixtures. + */ +export abstract class BankStoryUtilities { + /** + * Provides a backend answering like the bank, approval request, invoicing and bookkeeping routes would: from the + * fixtures, and with the answers of the story. + * @param answers - What else to answer, or to answer differently, like `{ 'GET /api/bank/accounts': … }`. + * @param config - The config of the story beside the urls. + * @returns The decorator of the story. + */ + static provideBackend(answers: Record = {}, config: BankConfigChanges = {}): ReturnType { + const backend: Record = { ...BankBackendUtilities.getAnswers(), ...answers }; + return applicationConfig({ + providers: [ + provideHttpClient(), + BankBackendUtilities.provideAnswers(backend), + provideBankConfig({ ...BANK_URLS, ...config }), + provideApprovalRequestsConfig({ + baseUrl: APPROVAL_REQUESTS_BASE_URL, + actions: { 'bank.match': 'Match a bank transaction' } + }) + ] + }); + } +} \ No newline at end of file diff --git a/projects/ngx-bank/fixtures/bank-testing.utilities.ts b/projects/ngx-bank/fixtures/bank-testing.utilities.ts new file mode 100644 index 0000000..8099336 --- /dev/null +++ b/projects/ngx-bank/fixtures/bank-testing.utilities.ts @@ -0,0 +1,138 @@ +import { HttpTestingController, TestRequest } from '@angular/common/http/testing'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { FakeAnswer } from 'testing/http'; + +import { BankBackendUtilities } from './bank-backend.utilities'; + +/** + * Utilities for the specs of the views of the bank, which render them against the answers of the fixtures. + */ +export abstract class BankTestingUtilities { + /** + * Answers the requests of a view until it sends none, and renders it. A view loads in rounds, like the matches of + * the transactions once these arrived. + * @param fixture - The fixture of the view. + * @param answers - What to answer, like BankBackendUtilities.getAnswers with changes. + * @returns The requests it answered, to check what they sent. + */ + static async settle(fixture: ComponentFixture, answers: Record): Promise { + const controller: HttpTestingController = TestBed.inject(HttpTestingController); + const answered: TestRequest[] = []; + let requests: TestRequest[] = []; + // a request that is still open keeps the fixture from becoming stable, so every round is answered before it is + // awaited, and the view gets the time to send the requests of the next round. + do { + TestBed.tick(); + await new Promise(resolve => setTimeout(resolve)); + TestBed.tick(); + requests = BankBackendUtilities.flushAll(controller, answers); + answered.push(...requests); + await new Promise(resolve => setTimeout(resolve)); + } + while (requests.length); + await fixture.whenStable(); + return answered; + } + + /** + * Finds the answered requests of a path. + * @param requests - The answered requests. + * @param url - The url of the path, like '/api/bank/transactions'. + * @returns The requests of the path, in the order they were answered. + */ + static findRequests(requests: TestRequest[], url: string): TestRequest[] { + return requests.filter(request => request.request.url === url); + } + + /** + * Gets the texts of an element one after the other, as a screen reader reads them. + * @param element - The element, or null. + * @returns The texts, separated by single spaces. + */ + static getText(element: Element | null | undefined): string { + if (element == undefined) { + return ''; + } + const walker: TreeWalker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT); + const texts: string[] = []; + while (walker.nextNode()) { + texts.push(walker.currentNode.textContent ?? ''); + } + return texts.join(' ').replaceAll(/\s+/g, ' ') + .trim(); + } + + /** + * Types a text into an input like a user does. + * @param fixture - The fixture to render afterwards. + * @param input - The input. + * @param text - What to type. + */ + static async type(fixture: ComponentFixture, input: HTMLInputElement | null | undefined, text: string): Promise { + if (input == undefined) { + throw new Error('There is no such input.'); + } + input.value = text; + input.dispatchEvent(new InputEvent('input', { inputType: 'insertText' })); + input.dispatchEvent(new Event('blur')); + await this.render(fixture); + } + + /** + * Chooses an option of an autocomplete like a user does: types its label and clicks it. + * @param fixture - The fixture to render afterwards. + * @param input - The input of the autocomplete. + * @param label - The label of the option. + */ + static async choose(fixture: ComponentFixture, input: HTMLInputElement | null | undefined, label: string): Promise { + if (input == undefined) { + throw new Error('There is no such autocomplete.'); + } + input.value = label; + input.dispatchEvent(new InputEvent('input', { inputType: 'insertText' })); + await this.render(fixture); + this.findOption(label).click(); + await this.render(fixture); + } + + /** + * Chooses an option of a select like a user does: opens it by its label and clicks the option. + * @param fixture - The fixture to render afterwards. + * @param root - The element the select is in. + * @param label - The label of the select. + * @param option - The label of the option. + */ + static async select(fixture: ComponentFixture, root: HTMLElement, label: string, option: string): Promise { + const labelElement: HTMLLabelElement | undefined = [...root.querySelectorAll('label')] + .find(candidate => candidate.textContent.replace('*', '').trim() === label); + const combobox: HTMLElement | null = root.querySelector(`[role="combobox"][aria-labelledby="${labelElement?.id ?? ''}"]`); + if (combobox == undefined) { + throw new Error(`There is no select "${label}".`); + } + combobox.click(); + await this.render(fixture); + this.findOption(option).click(); + await this.render(fixture); + } + + /** + * Renders what changed, without waiting for the fixture to be stable, which a request the change sent would keep + * it from: settle answers those. + * @param fixture - The fixture. + */ + static async render(fixture: ComponentFixture): Promise { + fixture.detectChanges(); + TestBed.tick(); + await new Promise(resolve => setTimeout(resolve)); + TestBed.tick(); + } + + private static findOption(label: string): HTMLElement { + const option: HTMLElement | undefined = [...document.querySelectorAll('[role="option"]')] + .find(candidate => candidate.textContent.trim() === label); + if (option == undefined) { + throw new Error(`There is no option "${label}".`); + } + return option; + } +} \ No newline at end of file diff --git a/projects/ngx-bank/fixtures/bank.fixtures.ts b/projects/ngx-bank/fixtures/bank.fixtures.ts new file mode 100644 index 0000000..c3924b3 --- /dev/null +++ b/projects/ngx-bank/fixtures/bank.fixtures.ts @@ -0,0 +1,627 @@ +/* eslint-disable unicorn/no-null -- the api answers null for every value a row doesn't have, which the fixtures mirror */ +import { BankConfigChanges } from '@service-soft/ngx-bank/api'; +import { ApprovalActorKind, ApprovalDecisionType, ApprovalRequestDetailsModel, ApprovalRequestModel, ApprovalRequestStatus, BankAccountModel, BankMatchInputModel, BankMatchModel, BankMatchReason, BankMatchTargetType, BankStatementImportModel, BankStatementModel, BankTransactionDetailsModel, BankTransactionModel, BankTransactionSuggestionModel, BookkeepingAccountModel, BookkeepingAccountType, ExpenseModel, InvoiceModel, InvoiceType } from 'zibri-contract'; + +// The bank accounts of a small company as the bank routes of zibri answer them: a business account with the statements +// of October and November 2026, and a reserve account without any. November holds a payment of an invoice the api +// suggests, a deposit of share capital it suggests booking against an account, a payment of another invoice that is +// matched in part and whose rest the api suggests with a payment difference, the rent whose match was reversed, a +// payment a cent short that is matched with a payment difference, and a fee nothing is suggested for. The invoices, +// the expense and the accounts of the books they are matched with are those the invoicing and the bookkeeping routes +// answer. The balances add up like the statements they stand for. Amounts are decimal strings without trailing zeros +// and days are midnight UTC, as the api writes them. Specs and stories send them through json first, like the api +// does, so the views read their dates as the strings of json. + +/** + * The url the specs and stories have the bank routes at. + */ +export const BANK_BASE_URL: string = '/api/bank'; + +/** + * The url the specs and stories have the approval request routes at. + */ +export const APPROVAL_REQUESTS_BASE_URL: string = '/api/approval-requests'; + +/** + * The url the specs and stories have the invoicing routes at. + */ +export const INVOICING_BASE_URL: string = '/api/invoicing'; + +/** + * The url the specs and stories have the bookkeeping routes at. + */ +export const BOOKKEEPING_BASE_URL: string = '/api/bookkeeping'; + +/** + * The urls of the bank, invoicing and bookkeeping routes, as provideBankConfig takes them. + */ +export const BANK_URLS: BankConfigChanges = { + baseUrl: BANK_BASE_URL, + invoicingUrl: INVOICING_BASE_URL, + bookkeepingUrl: BOOKKEEPING_BASE_URL +}; + +const TENANT_ID: string = '6f1c2d3e-4b5a-4c6d-8e7f-9a0b1c2d3e4f'; +const USER_ID: string = '5e6f7a8b-9c0d-4e1f-8a2b-3c4d5e6f7a8b'; +const EUR: string = 'EUR'; +const EXAMPLE_LTD: string = 'Example Ltd.'; +const EXAMPLE_LTD_IBAN: string = 'AT611904300234573201'; + +/** + * Gets a day of the bank, as the api holds it. + * @param iso - The day, like '2026-11-30'. + * @returns The day at midnight UTC. + */ +function day(iso: string): Date { + return new Date(`${iso}T00:00:00.000Z`); +} + +/** + * The ids of the rows of the fixtures, by what they are. + */ +export const IDS: Record< + 'business' | 'reserve' | 'statement10' | 'statement11' | 'invoicePayment' | 'partialPayment' | 'rent' | 'capital' | 'fee' + | 'shortPayment' | 'partialMatch' | 'rentMatch' | 'rentReversal' | 'shortMatch' | 'invoiceSuggestion' + | 'capitalSuggestion' | 'partialSuggestion' | 'invoice7' | 'invoice5' | 'invoice6' | 'rentExpense' | 'capitalAccount' + | 'transitAccount' | 'closedAccount', + string +> = { + business: 'a1000000-0000-4000-8000-000000000001', + reserve: 'a1000000-0000-4000-8000-000000000002', + statement10: 'b2000000-0000-4000-8000-000000000010', + statement11: 'b2000000-0000-4000-8000-000000000011', + invoicePayment: 'c3000000-0000-4000-8000-000000000001', + partialPayment: 'c3000000-0000-4000-8000-000000000002', + rent: 'c3000000-0000-4000-8000-000000000003', + capital: 'c3000000-0000-4000-8000-000000000004', + fee: 'c3000000-0000-4000-8000-000000000005', + shortPayment: 'c3000000-0000-4000-8000-000000000006', + partialMatch: 'd4000000-0000-4000-8000-000000000001', + rentMatch: 'd4000000-0000-4000-8000-000000000002', + rentReversal: 'd4000000-0000-4000-8000-000000000003', + shortMatch: 'd4000000-0000-4000-8000-000000000004', + invoiceSuggestion: 'e5000000-0000-4000-8000-000000000001', + capitalSuggestion: 'e5000000-0000-4000-8000-000000000002', + partialSuggestion: 'e5000000-0000-4000-8000-000000000003', + invoice7: 'f6000000-0000-4000-8000-000000000007', + invoice5: 'f6000000-0000-4000-8000-000000000005', + invoice6: 'f6000000-0000-4000-8000-000000000006', + rentExpense: 'f6000000-0000-4000-8000-0000000000e1', + capitalAccount: 'f6000000-0000-4000-8000-0000000000a1', + transitAccount: 'f6000000-0000-4000-8000-0000000000a2', + closedAccount: 'f6000000-0000-4000-8000-0000000000a3' +}; + +/** + * The business account, in euro. + */ +export const BUSINESS_ACCOUNT: BankAccountModel = { + id: IDS.business, + tenantId: TENANT_ID, + iban: 'DE89370400440532013000', + name: 'Business account', + currency: EUR +}; + +/** + * The reserve account, without a statement. + */ +export const RESERVE_ACCOUNT: BankAccountModel = { + id: IDS.reserve, + tenantId: TENANT_ID, + iban: 'DE02120300000000202051', + name: 'Reserve account', + currency: EUR +}; + +/** + * The accounts, by name. + */ +export const ACCOUNTS: BankAccountModel[] = [BUSINESS_ACCOUNT, RESERVE_ACCOUNT]; + +/** + * Creates a statement of the business account. + * @param id - Its id. + * @param sequence - The number the bank counts it with. + * @param month - The month it covers, like '2026-11'. + * @param lastDay - The last day of the month. + * @param balances - Its opening and closing balance. + * @returns The statement. + */ +function createStatement(id: string, sequence: number, month: string, lastDay: string, balances: [string, string]): BankStatementModel { + return { + id, + tenantId: TENANT_ID, + chainSequence: sequence, + chainHash: `hash-${sequence}`, + retainUntil: new Date('2034-12-31T23:00:00.000Z'), + archivedFiles: [{ id: `file-${sequence}`, sha256: 'a3f1c2d4e5b6a7980f1e2d3c4b5a69788f7e6d5c4b3a29180f1e2d3c4b5a6978', copies: [] }], + accountId: IDS.business, + bankStatementId: `S-2026-0${sequence}`, + electronicSequenceNumber: sequence, + issuedAt: day(lastDay), + periodStart: day(`${month}-01`), + periodEnd: day(lastDay), + openingBalance: balances[0], + openingBalanceDate: day(`${month}-01`), + closingBalance: balances[1], + closingBalanceDate: day(lastDay), + currency: EUR, + format: 'camt.053.001.08', + file: { name: `statement-${month}.xml`, mimeType: 'application/xml', size: 4812, url: null }, + importedAt: new Date(`${lastDay}T08:00:00.000Z`), + importedBy: USER_ID + }; +} + +/** + * The statement of October. + */ +export const OCTOBER: BankStatementModel = createStatement(IDS.statement10, 10, '2026-10', '2026-10-31', ['8000', '10000']); + +/** + * The statement of November, which holds every transaction of the fixtures. + */ +export const NOVEMBER: BankStatementModel = createStatement(IDS.statement11, 11, '2026-11', '2026-11-30', ['10000', '37320.09']); + +/** + * The statements of the business account, the latest period first. + */ +export const STATEMENTS: BankStatementModel[] = [NOVEMBER, OCTOBER]; + +/** + * Creates a transaction of the statement of November. + * @param id - Its id. + * @param booked - The day it was booked on, like '2026-11-11'. + * @param amount - Its amount, negative for money paid. + * @param counterpartyName - Who paid or was paid, or null. + * @param remittanceInformation - The text the payer gave it. + * @returns The transaction. + */ +function createTransaction( + id: string, + booked: string, + amount: string, + counterpartyName: string | null, + remittanceInformation: string +): BankTransactionModel { + return { + id, + tenantId: TENANT_ID, + accountId: IDS.business, + statementId: IDS.statement11, + bookingDate: day(booked), + valueDate: day(booked), + amount, + currency: EUR, + counterpartyName, + counterpartyIban: null, + remittanceInformation, + endToEndId: null, + mandateId: null, + creditorId: null, + bankReference: `REF-${id.slice(-4)}`, + deduplicationKey: `REF-${id.slice(-4)}` + }; +} + +/** + * A payment of invoice 2026-0007 in full, which the api suggests matching with it. + */ +export const INVOICE_PAYMENT: BankTransactionModel = { + ...createTransaction(IDS.invoicePayment, '2026-11-11', '1190', EXAMPLE_LTD, 'Invoice 2026-0007'), + counterpartyIban: EXAMPLE_LTD_IBAN, + endToEndId: 'E2E-2026-0007' +}; + +/** + * A payment of 800 of which 500 are matched with invoice 2026-0005. + */ +export const PARTIAL_PAYMENT: BankTransactionModel = createTransaction( + IDS.partialPayment, + '2026-11-05', + '800', + 'Sample Corp', + 'Invoice 2026-0005' +); + +/** + * The rent, whose match with its expense was reversed, so it is open again. + */ +export const RENT: BankTransactionModel = createTransaction(IDS.rent, '2026-11-03', '-850', 'Property management Miller', 'Rent November'); + +/** + * A deposit of share capital, which the api suggests booking against the account of the share capital. + */ +export const CAPITAL: BankTransactionModel = createTransaction(IDS.capital, '2026-11-02', '25000', 'Jane Doe', 'Share capital deposit'); + +/** + * A fee of the bank, nothing is suggested for. + */ +export const FEE: BankTransactionModel = createTransaction(IDS.fee, '2026-11-30', '-9.9', null, 'Account fee November'); + +/** + * A payment of invoice 2026-0006 a cent short, matched with a payment difference. + */ +export const SHORT_PAYMENT: BankTransactionModel = createTransaction( + IDS.shortPayment, + '2026-11-20', + '1189.99', + EXAMPLE_LTD, + 'Invoice 2026-0006' +); + +/** + * The transactions of November, the latest booking first. + */ +export const TRANSACTIONS: BankTransactionModel[] = [FEE, SHORT_PAYMENT, INVOICE_PAYMENT, PARTIAL_PAYMENT, RENT, CAPITAL]; + +/** + * The transactions of November with what of each its matches leave open, as `GET /transactions` answers them. + */ +export const TRANSACTION_DETAILS: BankTransactionDetailsModel[] = [ + { transaction: FEE, openAmount: '9.9' }, + { transaction: SHORT_PAYMENT, openAmount: '0' }, + { transaction: INVOICE_PAYMENT, openAmount: '1190' }, + { transaction: PARTIAL_PAYMENT, openAmount: '300' }, + { transaction: RENT, openAmount: '850' }, + { transaction: CAPITAL, openAmount: '25000' } +]; + +/** + * Creates a match. + * @param id - Its id. + * @param transactionId - The id of its transaction. + * @param target - The type and the id of its target. + * @param amount - What it matches. + * @param confirmedAt - When it was confirmed. + * @returns The match, confirmed by the user of the fixtures. + */ +function createMatch( + id: string, + transactionId: string, + target: [BankMatchTargetType, string], + amount: string, + confirmedAt: string +): BankMatchModel { + return { + id, + tenantId: TENANT_ID, + transactionId, + targetType: target[0], + targetId: target[1], + amount, + difference: null, + currency: EUR, + reversesMatchId: null, + requestId: null, + confirmedBy: USER_ID, + confirmedByKind: ApprovalActorKind.USER, + confirmedAt: new Date(confirmedAt) + }; +} + +/** + * The match of 500 of the partial payment with invoice 2026-0005. + */ +export const PARTIAL_MATCH: BankMatchModel = createMatch( + IDS.partialMatch, + IDS.partialPayment, + [BankMatchTargetType.INVOICE, IDS.invoice5], + '500', + '2026-11-06T09:00:00.000Z' +); + +/** + * The match of the rent with its expense, approved by the policy of the confidence. + */ +export const RENT_MATCH: BankMatchModel = { + ...createMatch(IDS.rentMatch, IDS.rent, [BankMatchTargetType.EXPENSE, IDS.rentExpense], '850', '2026-11-04T06:00:00.000Z'), + confirmedBy: 'confidence-at-least-0.95', + confirmedByKind: ApprovalActorKind.POLICY +}; + +/** + * The reversal of the match of the rent. + */ +export const RENT_REVERSAL: BankMatchModel = { + ...createMatch(IDS.rentReversal, IDS.rent, [BankMatchTargetType.EXPENSE, IDS.rentExpense], '-850', '2026-11-10T10:00:00.000Z'), + reversesMatchId: IDS.rentMatch +}; + +/** + * The match of the payment a cent short with invoice 2026-0006, which accepts the cent as paid. + */ +export const SHORT_MATCH: BankMatchModel = { + ...createMatch(IDS.shortMatch, IDS.shortPayment, [BankMatchTargetType.INVOICE, IDS.invoice6], '1189.99', '2026-11-21T09:00:00.000Z'), + difference: '0.01' +}; + +/** + * The matches of every transaction, by the id of the transaction, the latest confirmed first. + */ +export const MATCHES: Record = { + [IDS.invoicePayment]: [], + [IDS.partialPayment]: [PARTIAL_MATCH], + [IDS.rent]: [RENT_REVERSAL, RENT_MATCH], + [IDS.capital]: [], + [IDS.fee]: [], + [IDS.shortPayment]: [SHORT_MATCH] +}; + +/** + * Creates a suggestion of the api, a pending approval request of the match action. + * @param id - The id of the request. + * @param input - What it runs with. + * @param summary - What it does, for the reviewer. + * @param reason - Why the api suggests it. + * @returns The request. + */ +function createSuggestion(id: string, input: BankMatchInputModel, summary: string, reason: string): ApprovalRequestModel { + return { + id, + tenantId: TENANT_ID, + action: 'bank.match', + input, + reason, + summary, + changes: [{ entity: 'bank_match', id: null, changes: [{ key: 'amount', previousValue: null, newValue: input.amount }] }], + preconditions: [], + proposedBy: 'bank-matching', + proposedByKind: ApprovalActorKind.SYSTEM, + proposedAt: new Date('2026-11-30T08:00:00.000Z'), + status: ApprovalRequestStatus.PENDING, + expiresAt: new Date('2026-12-07T08:00:00.000Z') + }; +} + +/** + * Gets a suggestion as `GET /transactions/:id/suggestions` answers it. + * @param request - Its approval request. + * @param input - What the request runs with. + * @param paymentDifference - What of the invoice approving it accepts as paid, or null for none. + * @returns The suggestion. + */ +function toTransactionSuggestion( + request: ApprovalRequestModel, + input: BankMatchInputModel, + paymentDifference: string | null +): BankTransactionSuggestionModel { + return { + requestId: request.id, + targetType: input.targetType, + targetId: input.targetId, + amount: input.amount, + confidence: input.confidence ?? null, + reasons: input.reasons ?? [], + paymentDifference, + summary: request.summary + }; +} + +const INVOICE_SUGGESTION_INPUT: BankMatchInputModel = { + transactionId: IDS.invoicePayment, + targetType: BankMatchTargetType.INVOICE, + targetId: IDS.invoice7, + amount: '1190', + confidence: 0.85, + reasons: [BankMatchReason.INVOICE_NUMBER, BankMatchReason.AMOUNT] +}; + +const CAPITAL_SUGGESTION_INPUT: BankMatchInputModel = { + transactionId: IDS.capital, + targetType: BankMatchTargetType.ACCOUNT, + targetId: IDS.capitalAccount, + amount: '25000', + confidence: 1, + reasons: [BankMatchReason.ACCOUNT_RULE] +}; + +const PARTIAL_SUGGESTION_INPUT: BankMatchInputModel = { + transactionId: IDS.partialPayment, + targetType: BankMatchTargetType.INVOICE, + targetId: IDS.invoice5, + amount: '300', + confidence: 0.75, + reasons: [BankMatchReason.INVOICE_NUMBER, BankMatchReason.COUNTERPARTY_NAME] +}; + +/** + * The suggestion of matching the payment of invoice 2026-0007 with it. + */ +export const INVOICE_SUGGESTION: ApprovalRequestModel = createSuggestion( + IDS.invoiceSuggestion, + INVOICE_SUGGESTION_INPUT, + 'Match 1190 EUR paid by Example Ltd. on 2026-11-11 with the invoice 2026-0007.', + 'The payer names the invoice number. What is left of the transaction is what is left of the invoice.' +); + +/** + * The suggestion of booking the deposit of share capital against its account, which a person always confirms. + */ +export const CAPITAL_SUGGESTION: ApprovalRequestModel = createSuggestion( + IDS.capitalSuggestion, + CAPITAL_SUGGESTION_INPUT, + 'Match 25000 EUR of Jane Doe on 2026-11-02 with 0800 Subscribed capital.', + 'An account match rule names the counterparty and the text of the transaction.' +); + +/** + * The suggestion of matching the rest of the partial payment with invoice 2026-0005, which leaves a cent of it open. + */ +export const PARTIAL_SUGGESTION: ApprovalRequestModel = createSuggestion( + IDS.partialSuggestion, + PARTIAL_SUGGESTION_INPUT, + 'Match 300 EUR paid by Sample Corp on 2026-11-05 with the invoice 2026-0005.', + 'The payer names the invoice number. The payer has the name of the recipient of the invoice.' +); + +/** + * The pending suggestions as approval requests, which the review loads by their id. + */ +export const SUGGESTIONS: ApprovalRequestModel[] = [INVOICE_SUGGESTION, CAPITAL_SUGGESTION, PARTIAL_SUGGESTION]; + +/** + * The pending suggestions of every transaction, by the id of the transaction, the most confident first. + */ +export const TRANSACTION_SUGGESTIONS: Record = { + [IDS.invoicePayment]: [toTransactionSuggestion(INVOICE_SUGGESTION, INVOICE_SUGGESTION_INPUT, null)], + [IDS.capital]: [toTransactionSuggestion(CAPITAL_SUGGESTION, CAPITAL_SUGGESTION_INPUT, null)], + [IDS.partialPayment]: [toTransactionSuggestion(PARTIAL_SUGGESTION, PARTIAL_SUGGESTION_INPUT, '0.01')] +}; + +/** + * Creates an issued invoice of the company, to a company. + * @param id - Its id. + * @param number - Its number. + * @param companyName - The company it is to. + * @param price - The net price of its one item, taxed at 19 %. + * @returns The invoice. + */ +function createInvoice(id: string, number: string, companyName: string, price: number): InvoiceModel { + return { + id, + tenantId: TENANT_ID, + number, + items: [{ + name: 'Consulting', + amount: 1, + amountUnit: { displayName: 'Flat rate', code: 'C62' }, + vat: { rate: 19, categoryCode: 'S' }, + price + }], + date: day('2026-10-28'), + performanceDate: day('2026-10-28'), + dueDate: day('2026-11-11'), + customerAddressData: { + formOfAddress: 'Mr', + firstName: 'John', + lastName: 'Smith', + street: 'Main Street', + number: '1', + postcode: '10115', + city: 'Berlin', + countryId: 'DE', + company: true, + companyName + }, + textBeforeItems: [], + textAfterItems: [], + currency: EUR, + type: InvoiceType.INVOICE, + precedingInvoices: null, + issuedAt: new Date('2026-10-28T09:00:00.000Z') + }; +} + +const INVOICE_7: InvoiceModel = createInvoice(IDS.invoice7, '2026-0007', EXAMPLE_LTD, 1000); + +/** + * Invoice 2026-0005, of 800.01, which 500 of the partial payment pay. + */ +const INVOICE_5: InvoiceModel = createInvoice(IDS.invoice5, '2026-0005', 'Sample Corp', 672.28); + +/** + * Every invoice the transactions are matched with, by its id: 2026-0007, 2026-0005, and 2026-0006, which the payment a + * cent short paid. + */ +export const INVOICES: InvoiceModel[] = [INVOICE_7, INVOICE_5, createInvoice(IDS.invoice6, '2026-0006', EXAMPLE_LTD, 1000)]; + +/** + * The issued invoices with something open, as `GET /invoices?issued=true&open=true&type=INVOICE` answers them. + */ +export const OPEN_INVOICES: InvoiceModel[] = [INVOICE_7, INVOICE_5]; + +/** + * The expense of the rent of November, recorded. + */ +export const RENT_EXPENSE: ExpenseModel = { + id: IDS.rentExpense, + tenantId: TENANT_ID, + supplier: { name: 'Property management Miller', address: null, vatId: null }, + documentNumber: 'R-2026-11', + documentDate: day('2026-11-01'), + dueDate: day('2026-11-03'), + totals: [{ rate: 0, net: '850', tax: '0' }], + currency: EUR, + accountId: 'f6000000-0000-4000-8000-0000000000a4', + receiptId: null, + recordedAt: new Date('2026-11-01T10:00:00.000Z'), + postedEntryId: null, + correctsExpenseId: null +}; + +/** + * Creates an account of the books. + * @param id - Its id. + * @param number - Its number. + * @param name - What it is called. + * @param type - What it holds. + * @returns The account, open. + */ +function createBookkeepingAccount(id: string, number: string, name: string, type: BookkeepingAccountType): BookkeepingAccountModel { + return { id, tenantId: TENANT_ID, number, name, type, statementPosition: null, creditStatementPosition: null, closedAt: null }; +} + +/** + * The accounts of the books, by number: the subscribed capital, the money in transit, and a closed account. + */ +export const BOOKKEEPING_ACCOUNTS: BookkeepingAccountModel[] = [ + createBookkeepingAccount(IDS.capitalAccount, '0800', 'Subscribed capital', BookkeepingAccountType.EQUITY), + createBookkeepingAccount(IDS.transitAccount, '1360', 'Money in transit', BookkeepingAccountType.ASSET), + { + ...createBookkeepingAccount(IDS.closedAccount, '1590', 'Clearing account', BookkeepingAccountType.ASSET), + closedAt: day('2025-12-31') + } +]; + +/** + * The match approving the suggestion of the invoice records. + */ +export const INVOICE_MATCH: BankMatchModel = createMatch( + 'd4000000-0000-4000-8000-000000000005', + IDS.invoicePayment, + [BankMatchTargetType.INVOICE, IDS.invoice7], + '1190', + '2026-11-30T09:00:00.000Z' +); + +/** + * The suggestion of the invoice once it was approved, with the match it recorded. + */ +export const APPROVED_INVOICE_SUGGESTION: ApprovalRequestDetailsModel = { + request: { ...INVOICE_SUGGESTION, status: ApprovalRequestStatus.APPROVED }, + decision: { + id: 'a7000000-0000-4000-8000-000000000001', + tenantId: TENANT_ID, + chainSequence: 1, + chainHash: 'hash', + requestId: IDS.invoiceSuggestion, + decision: ApprovalDecisionType.APPROVED, + decidedBy: USER_ID, + decidedByKind: ApprovalActorKind.USER, + decidedAt: new Date('2026-11-30T09:00:00.000Z'), + note: null, + result: INVOICE_MATCH, + error: null + } +}; + +/** + * What importing the file of November stored: its statement, and the one of October skipped as imported before. + */ +export const IMPORT_RESULT: BankStatementImportModel = { + statements: [NOVEMBER], + skippedStatementCount: 1, + transactionCount: 6, + skippedTransactionCount: 0 +}; + +/** + * Gets what the api sends: json, whose dates are strings. + * @param value - The model. + * @returns The model as json would hand it over. + */ +export function toJson(value: unknown): object { + return JSON.parse(JSON.stringify(value)) as object; +} \ No newline at end of file diff --git a/projects/ngx-bank/locale/messages.de.xlf b/projects/ngx-bank/locale/messages.de.xlf new file mode 100644 index 0000000..5a5fd31 --- /dev/null +++ b/projects/ngx-bank/locale/messages.de.xlf @@ -0,0 +1,407 @@ + + + + + + Bank accounts + Bankkonten + + + Add a bank account + Bankkonto hinzufügen + + + The account was added. + Das Konto wurde hinzugefügt. + + + The code of its currency, like EUR + Der Code seiner Währung, etwa EUR + + + Like DE89 3704 0044 0532 0130 00 + Etwa DE89 3704 0044 0532 0130 00 + + + This is no valid IBAN. Check it for a typing error. + Das ist keine gültige IBAN. Prüfen Sie sie auf einen Tippfehler. + + + What you call the account, like "Business account" + Wie Sie das Konto nennen, etwa „Geschäftskonto“ + + + Account + Konto + + + All accounts + Alle Konten + + + Amount + Betrag + + + Reference of the bank + Referenz der Bank + + + Booking date + Buchungstag + + + Closing balance + Endsaldo + + + Counterparty + Gegenpartei + + + IBAN of the counterparty + IBAN der Gegenpartei + + + Currency + Währung + + + End-to-end reference + Ende-zu-Ende-Referenz + + + IBAN + IBAN + + + Loading + Wird geladen + + + The bank data couldn't be loaded. + Die Bankdaten konnten nicht geladen werden. + + + Name + Name + + + There is no bank account yet. + Es gibt noch kein Bankkonto. + + + Open + Offen + + + Opening balance + Anfangssaldo + + + Period + Zeitraum + + + Until + Bis + + + From + Von + + + Payment reference + Verwendungszweck + + + The request couldn't be sent. Please try again. + Die Anfrage konnte nicht gesendet werden. Bitte versuchen Sie es erneut. + + + Account of the books + Konto der Buchhaltung + + + Expense + Ausgabe + + + Invoice + Rechnung + + + Value date + Wertstellung + + + A rule of the books names the counterparty or the text + Eine Regel der Buchhaltung nennt die Gegenpartei oder den Text + + + The amount is what is open + Der Betrag ist, was offen ist + + + The account of the payer paid the recipient before + Das Konto des Zahlers hat den Empfänger schon einmal bezahlt + + + The counterparty has the name of the recipient or supplier + Die Gegenpartei hat den Namen des Empfängers oder Lieferanten + + + The payment names the document number of the expense + Die Zahlung nennt die Belegnummer der Ausgabe + + + The payer names the invoice number + Der Zahler nennt die Rechnungsnummer + + + At most , what of the transaction is open + Höchstens , was vom Umsatz offen ist + + + Close the review + Prüfung schließen + + + Match by hand + Von Hand zuordnen + + + The transaction is matched in full. + Der Umsatz ist vollständig zugeordnet. + + + Confirmed by a person + Von einer Person bestätigt + + + A match with an account of the books is never approved automatically. + Eine Zuordnung zu einem Konto der Buchhaltung wird nie automatisch genehmigt. + + + No suggestion waits for a decision. + Kein Vorschlag wartet auf eine Entscheidung. + + + of are open. + von sind offen. + + + Payment difference + Zahlungsdifferenz + + + Propose the match + Zuordnung vorschlagen + + + The match was proposed. It is recorded once a person who confirms matches approves it. + Die Zuordnung wurde vorgeschlagen. Sie wird gespeichert, sobald eine Person, die Zuordnungen bestätigt, sie genehmigt. + + + Reason + Begründung + + + For the person who approves the match + Für die Person, die die Zuordnung genehmigt + + + Why + Warum + + + Review + Prüfen + + + Review: + Prüfen: + + + Score + Wertung + + + Suggest matches again + Zuordnungen erneut vorschlagen + + + The matches were suggested again. + Die Zuordnungen wurden erneut vorgeschlagen. + + + Suggestions + Vorschläge + + + Search by number or name + Nach Nummer oder Name suchen + + + Match with + Zuordnen zu + + + Cancel + Abbrechen + + + Reverse + Stornieren + + + What it matched is open again on both sides, and is suggested again. The match itself is kept, and a reversal is recorded next to it. This can't be undone. + Was sie zugeordnet hat, ist auf beiden Seiten wieder offen und wird erneut vorgeschlagen. Die Zuordnung selbst bleibt erhalten, und ein Storno wird neben ihr gespeichert. Das kann nicht rückgängig gemacht werden. + + + Reverse this match? + Diese Zuordnung stornieren? + + + File + Datei + + + Format + Format + + + Imported + Importiert + + + Statement + Kontoauszug + + + Statement + Kontoauszug + + + Statements + Kontoauszüge + + + Transactions of statement + Umsätze des Kontoauszugs + + + All + Alle + + + Confirmed by on + Bestätigt von am + + + Payment difference + Zahlungsdifferenz + + + The match with was reversed. + Die Zuordnung zu wurde storniert. + + + Matched + Zugeordnet + + + Matches + Zuordnungen + + + The transaction is not matched yet. + Der Umsatz ist noch nicht zugeordnet. + + + Open + Offen + + + Partly matched + Teilweise zugeordnet + + + Every transaction when empty + Alle Umsätze, wenn leer + + + Reversal + Storno + + + Reverse + Stornieren + + + Reverse the match with + Die Zuordnung zu stornieren + + + Reversed + Storniert + + + Status + Status + + + Transaction of + Umsatz vom + + + Transactions + Umsätze + + + CAMT.053 file + CAMT.053-Datei + + + The statement export of your bank, an XML file + Der Export der Kontoauszüge Ihrer Bank, eine XML-Datei + + + Import + Importieren + + + The file was imported. + Die Datei wurde importiert. + + + The file holds nothing that wasn't imported before. + Die Datei enthält nichts, was nicht schon importiert wurde. + + + Imported + Importiert + + + Statements of the file + Kontoauszüge der Datei + + + New statements + Neue Kontoauszüge + + + Statements imported before + Schon importierte Kontoauszüge + + + New transactions + Neue Umsätze + + + Transactions imported before + Schon importierte Umsätze + + + + diff --git a/projects/ngx-bank/ng-package.json b/projects/ngx-bank/ng-package.json new file mode 100644 index 0000000..68e219f --- /dev/null +++ b/projects/ngx-bank/ng-package.json @@ -0,0 +1,8 @@ +{ + "$schema": "../../node_modules/ng-packagr/ng-package.schema.json", + "assets": ["tailwind.css", "locale/messages.de.xlf", "CHANGELOG.md"], + "dest": "../../dist/ngx-bank", + "lib": { + "entryFile": "src/public-api.ts" + } +} diff --git a/projects/ngx-bank/package.json b/projects/ngx-bank/package.json new file mode 100644 index 0000000..d175236 --- /dev/null +++ b/projects/ngx-bank/package.json @@ -0,0 +1,37 @@ +{ + "name": "@service-soft/ngx-bank", + "version": "22.4.0", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/Service-Soft/angular-libraries.git", + "directory": "projects/ngx-bank" + }, + "publishConfig": { + "access": "public" + }, + "dependencies": { + "tslib": "^2.3.0" + }, + "exports": { + ".": { + "style": "./tailwind.css" + } + }, + "peerDependencies": { + "@angular/aria": "^22.2.0", + "@angular/common": "^22.2.0", + "@angular/core": "^22.2.0", + "@angular/localize": "^22.2.0", + "@service-soft/ngx-approval-requests": "^22.4.0", + "@service-soft/ngx-error-handling": "^22.4.0", + "@service-soft/ui": "^22.4.0", + "rxjs": "^7.8.0", + "tailwindcss": "^4.3.3", + "zibri-contract": "^3.3.0" + }, + "sideEffects": false, + "translations": { + "de": "./locale/messages.de.xlf" + } +} diff --git a/projects/ngx-bank/src/public-api.ts b/projects/ngx-bank/src/public-api.ts new file mode 100644 index 0000000..4005bee --- /dev/null +++ b/projects/ngx-bank/src/public-api.ts @@ -0,0 +1,4 @@ +/** + * Every view lives in its own secondary entry point, eg. '@service-soft/ngx-bank/bank-transactions'. + */ +export {}; diff --git a/projects/ngx-bank/statement-upload/imported-statement-row-view.model.ts b/projects/ngx-bank/statement-upload/imported-statement-row-view.model.ts new file mode 100644 index 0000000..a0bbbcc --- /dev/null +++ b/projects/ngx-bank/statement-upload/imported-statement-row-view.model.ts @@ -0,0 +1,29 @@ +/** + * A statement an import stored, as the upload shows it. + */ +export type ImportedStatementRowView = { + /** + * The id of the statement. + */ + id: string, + /** + * The account it is of, its name and IBAN. + */ + account: string, + /** + * The id the bank gave it. + */ + statement: string, + /** + * The period it covers, formatted. + */ + period: string, + /** + * Its opening balance, formatted. + */ + openingBalance: string, + /** + * Its closing balance, formatted. + */ + closingBalance: string +}; diff --git a/projects/ngx-bank/statement-upload/ng-package.json b/projects/ngx-bank/statement-upload/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-bank/statement-upload/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-bank/statement-upload/public-api.ts b/projects/ngx-bank/statement-upload/public-api.ts new file mode 100644 index 0000000..e227911 --- /dev/null +++ b/projects/ngx-bank/statement-upload/public-api.ts @@ -0,0 +1 @@ +export * from './statement-upload.component'; diff --git a/projects/ngx-bank/statement-upload/statement-upload.component.html b/projects/ngx-bank/statement-upload/statement-upload.component.html new file mode 100644 index 0000000..f258d55 --- /dev/null +++ b/projects/ngx-bank/statement-upload/statement-upload.component.html @@ -0,0 +1,26 @@ +
+ + + @if (importError(); as message) { +
+ +

{{ message }}

+
+ } +
+ + +

{{ announcement() }}

+
+
+ + @if (result(); as result) { +
+ {{ labels.result }} + + @if (result.statements.length) { + + } +
+ } +
diff --git a/projects/ngx-bank/statement-upload/statement-upload.component.spec.ts b/projects/ngx-bank/statement-upload/statement-upload.component.spec.ts new file mode 100644 index 0000000..d8d92eb --- /dev/null +++ b/projects/ngx-bank/statement-upload/statement-upload.component.spec.ts @@ -0,0 +1,93 @@ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideApprovalRequestsConfig } from '@service-soft/ngx-approval-requests/api'; +import { provideBankConfig } from '@service-soft/ngx-bank/api'; +import { FormTestingUtilities } from 'testing/form'; +import { beforeEach, describe, expect, test } from 'vitest'; +import { ErrorResponseBody } from 'zibri-contract'; + +import { BankBackendUtilities } from '../fixtures/bank-backend.utilities'; +import { BankTestingUtilities } from '../fixtures/bank-testing.utilities'; +import { APPROVAL_REQUESTS_BASE_URL, BANK_BASE_URL, IMPORT_RESULT, toJson } from '../fixtures/bank.fixtures'; +import { StatementUploadComponent } from './statement-upload.component'; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [StatementUploadComponent] +}) +class HostComponent {} + +const FILE: File = new File([''], 'statement-2026-11.xml', { type: 'application/xml' }); + +async function render(): Promise<[ComponentFixture, HTMLElement]> { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + return [fixture, fixture.nativeElement as HTMLElement]; +} + +// chooses the file like the native picker does, and imports it. +async function upload(fixture: ComponentFixture, root: HTMLElement): Promise { + const input: HTMLInputElement | null = root.querySelector('input[type="file"]'); + Object.defineProperty(input, 'files', { value: [FILE], configurable: true }); + input?.dispatchEvent(new Event('change')); + await BankTestingUtilities.render(fixture); + FormTestingUtilities.click(root, 'Import'); + await BankTestingUtilities.render(fixture); + return TestBed.inject(HttpTestingController).expectOne({ method: 'POST', url: `${BANK_BASE_URL}/statements` }); +} + +describe('StatementUploadComponent', () => { + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + provideBankConfig({ baseUrl: BANK_BASE_URL }), + provideApprovalRequestsConfig({ baseUrl: APPROVAL_REQUESTS_BASE_URL }) + ] + }); + }); + + test('imports the file, and shows the statements stored and what was new or imported before', async () => { + const [fixture, root] = await render(); + + const request: TestRequest = await upload(fixture, root); + expect(request.request.body instanceof FormData && request.request.body.get('file')).toEqual(FILE); + request.flush(toJson(IMPORT_RESULT)); + await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + + expect(root.querySelector('p[role="status"]')?.textContent.trim()).toBe('The file was imported.'); + expect(BankTestingUtilities.getText(root.querySelector('ui-data-list'))).toBe( + 'New statements 1 New transactions 6 Statements imported before 1 Transactions imported before 0' + ); + expect([...root.querySelectorAll('ui-local-table tbody tr')].map(row => BankTestingUtilities.getText(row))).toEqual([ + 'Account Business account (DE89 3704 0044 0532 0130 00) Statement S-2026-011 Period 11/01/2026 – 11/30/2026 ' + + 'Opening balance €10,000.00 Closing balance €37,320.09' + ]); + }); + + test('says when the file holds nothing that wasn\'t imported before', async () => { + const [fixture, root] = await render(); + + (await upload(fixture, root)).flush(toJson({ ...IMPORT_RESULT, statements: [], skippedStatementCount: 2, transactionCount: 0 })); + await BankTestingUtilities.settle(fixture, BankBackendUtilities.getAnswers()); + + expect(root.querySelector('p[role="status"]')?.textContent.trim()).toBe('The file holds nothing that wasn\'t imported before.'); + expect(root.querySelector('ui-local-table')).toBeNull(); + }); + + test('shows the message of the api when it refuses the file, like for an IBAN without an account', async () => { + const [fixture, root] = await render(); + + const message: string = 'The statement "S-2026-011" is of DE02120300000000202052, which the tenant has no account of.'; + const body: ErrorResponseBody = { status: 409, name: 'ConflictError', message, paragraphs: [message] }; + (await upload(fixture, root)).flush(body, { status: 409, statusText: 'Conflict' }); + await BankTestingUtilities.settle(fixture, {}); + + expect(BankTestingUtilities.getText(root.querySelector('[role="alert"]'))).toBe(`Error ${message}`); + expect(root.querySelector('ui-data-list')).toBeNull(); + }); +}); \ No newline at end of file diff --git a/projects/ngx-bank/statement-upload/statement-upload.component.ts b/projects/ngx-bank/statement-upload/statement-upload.component.ts new file mode 100644 index 0000000..c554577 --- /dev/null +++ b/projects/ngx-bank/statement-upload/statement-upload.component.ts @@ -0,0 +1,162 @@ +import { Component, computed, resource, ResourceRef, Signal, signal, WritableSignal } from '@angular/core'; +import { BankStatementsLabels, BankStatementUploadLabels, BankViewDirective } from '@service-soft/ngx-bank/api'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { DataListComponent, DataListItem } from '@service-soft/ui/data-list'; +import { FormComponent } from '@service-soft/ui/form'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { InputFileComponent, InputFileValue } from '@service-soft/ui/input-file'; +import { LocalTableColumn, LocalTableComponent } from '@service-soft/ui/local-table'; +import { BankAccountModel, BankStatementImportModel, BankStatementModel } from 'zibri-contract'; + +import { ImportedStatementRowView } from './imported-statement-row-view.model'; + +/** + * The upload of a CAMT.053 file to the api of provideBankConfig: ``. It imports every + * statement of the file, and then shows what was stored: the statements with their account, period and balances, and + * how many statements and transactions were new or imported before. A file the api refuses, like one of an IBAN without + * an account or a statement that doesn't continue the one before it, imports nothing, and the view shows the message of + * the api. + */ +@Component({ + selector: 'ngx-bank-statement-upload', + templateUrl: './statement-upload.component.html', + imports: [ + ButtonComponent, + CalloutComponent, + DataListComponent, + FormComponent, + HeadingComponent, + InputFileComponent, + LocalTableComponent + ], + host: { class: 'block' } +}) +export class StatementUploadComponent extends BankViewDirective { + /** + * The texts of the upload. + */ + protected readonly labels: BankStatementUploadLabels = this.config.labels.upload; + + /** + * The texts of the statements. + */ + protected readonly statementLabels: BankStatementsLabels = this.config.labels.statements; + + /** + * The level of the heading of what was imported. + */ + protected readonly headingLevel: HeadingLevel = this.config.headingLevel; + + // only to name the account of each statement stored. + private readonly accounts: ResourceRef = resource({ + params: () => this.bankService.revision(), + loader: async () => await this.bankService.resolveAccounts() + }); + + /** + * The file the user chose. + */ + protected readonly files: WritableSignal = signal([]); + + /** + * Whether the file is being imported. + */ + protected readonly importing: WritableSignal = signal(false); + + /** + * Why the api refused the file, its paragraphs one per line, or undefined while it refused none. + */ + protected readonly importError: WritableSignal = signal(undefined); + + /** + * What the last import stored, undefined before the first. + */ + protected readonly result: WritableSignal = signal(undefined); + + /** + * What the view last said about an import, read by screen readers as it changes. + */ + protected readonly announcement: WritableSignal = signal(''); + + /** + * How many statements and transactions the last import stored and skipped. + */ + protected readonly counts: Signal = computed(() => { + const result: BankStatementImportModel | undefined = this.result(); + if (result == undefined) { + return []; + } + return [ + { label: this.labels.statementsImported, value: result.statements.length }, + { label: this.labels.transactionsImported, value: result.transactionCount }, + { label: this.labels.statementsSkipped, value: result.skippedStatementCount }, + { label: this.labels.transactionsSkipped, value: result.skippedTransactionCount } + ]; + }); + + /** + * The statements the last import stored. + */ + protected readonly rows: Signal = computed(() => { + const accounts: Map = new Map( + (this.accounts.hasValue() ? this.accounts.value() ?? [] : []).map(account => [account.id, account]) + ); + return (this.result()?.statements ?? []).map(statement => this.toRow(statement, accounts.get(statement.accountId))); + }); + + /** + * The columns of the table of the statements stored. + */ + protected readonly columns: LocalTableColumn[] = [ + { key: 'account', label: this.commonLabels.account, value: row => row.account }, + { key: 'statement', label: this.statementLabels.statement, value: row => row.statement }, + { key: 'period', label: this.commonLabels.period, value: row => row.period }, + { key: 'openingBalance', label: this.commonLabels.openingBalance, value: row => row.openingBalance, align: 'end' }, + { key: 'closingBalance', label: this.commonLabels.closingBalance, value: row => row.closingBalance, align: 'end' } + ]; + + /** + * Gets the key of a row of the table. + * @param row - The row. + * @returns The id of its statement. + */ + protected readonly getRowKey: (row: ImportedStatementRowView) => string = row => row.id; + + /** + * Imports the file, which the form only submits once the user chose one, and shows what was stored. + */ + protected async import(): Promise { + const file: File | undefined = this.files().find(value => value instanceof File); + if (file == undefined) { + return; + } + this.importing.set(true); + this.importError.set(undefined); + this.announcement.set(''); + try { + const result: BankStatementImportModel = await this.bankService.importStatements(file); + this.result.set(result); + this.files.set([]); + this.announcement.set(result.statements.length ? this.labels.imported : this.labels.nothingNew); + } + catch (error) { + this.result.set(undefined); + this.importError.set(this.resolveErrorMessage(error)); + } + finally { + this.importing.set(false); + } + } + + private toRow(statement: BankStatementModel, account: BankAccountModel | undefined): ImportedStatementRowView { + return { + id: statement.id, + account: account == undefined ? statement.accountId : `${account.name} (${this.formatIban(account.iban)})`, + statement: statement.bankStatementId, + period: this.formatPeriod(statement.periodStart, statement.periodEnd), + openingBalance: this.formatAmount(statement.openingBalance, statement.currency), + closingBalance: this.formatAmount(statement.closingBalance, statement.currency) + }; + } +} \ No newline at end of file diff --git a/projects/ngx-bank/statement-upload/statement-upload.stories.ts b/projects/ngx-bank/statement-upload/statement-upload.stories.ts new file mode 100644 index 0000000..18689a6 --- /dev/null +++ b/projects/ngx-bank/statement-upload/statement-upload.stories.ts @@ -0,0 +1,19 @@ +import { Meta, StoryObj } from '@storybook/angular'; + +import { BankStoryUtilities } from '../fixtures/bank-story.utilities'; +import { BANK_BASE_URL, IMPORT_RESULT, toJson } from '../fixtures/bank.fixtures'; +import { StatementUploadComponent } from './statement-upload.component'; + +const meta: Meta = { + title: 'Bank/Statement upload', + component: StatementUploadComponent, + render: () => ({ template: '' }) +}; +export default meta; + +type Story = StoryObj; + +// importing a file shows the statement of November, and the one of October imported before. +export const Default: Story = { + decorators: [BankStoryUtilities.provideBackend({ [`POST ${BANK_BASE_URL}/statements`]: { status: 200, body: toJson(IMPORT_RESULT) } })] +}; \ No newline at end of file diff --git a/projects/ngx-bank/tailwind.css b/projects/ngx-bank/tailwind.css new file mode 100644 index 0000000..4c7b7e3 --- /dev/null +++ b/projects/ngx-bank/tailwind.css @@ -0,0 +1 @@ +@source "./fesm2022"; diff --git a/projects/ngx-bank/test-setup.ts b/projects/ngx-bank/test-setup.ts new file mode 100644 index 0000000..60616f3 --- /dev/null +++ b/projects/ngx-bank/test-setup.ts @@ -0,0 +1,29 @@ +import { PopoverTestingUtilities } from 'testing/popover'; + +// jsdom has no popover api, which the lists of the selects and autocompletes and the calendars of the dates open with. +PopoverTestingUtilities.addPopovers(); + +// jsdom has no layout and no ResizeObserver, which the tables watch their widths with. Nothing is ever wider than it is +// there, so an observer that never calls back is what jsdom would answer. +globalThis.ResizeObserver ??= class implements ResizeObserver { + /** + * Observes nothing, as jsdom has no sizes. + */ + observe(): void { + // jsdom has no sizes to observe + } + + /** + * Stops observing nothing. + */ + unobserve(): void { + // nothing is observed + } + + /** + * Stops observing nothing. + */ + disconnect(): void { + // nothing is observed + } +}; \ No newline at end of file diff --git a/projects/ngx-bank/tsconfig.lib.json b/projects/ngx-bank/tsconfig.lib.json new file mode 100644 index 0000000..f627ddb --- /dev/null +++ b/projects/ngx-bank/tsconfig.lib.json @@ -0,0 +1,18 @@ +/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ +/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ +{ + "compilerOptions": { + "declaration": true, + "declarationMap": true, + "outDir": "../../out-tsc/lib", + // the paths of the workspace point to the sources of the other libraries, which the build would then compile + // into this one. Without them, they resolve from node_modules like for a consumer, so ui, ngx-error-handling and + // ngx-approval-requests have to be built first. + "paths": {}, + "types": ["@angular/localize"] + }, + // the fixtures are the answers of the api the specs and stories render, never part of the package. + "exclude": ["**/*.spec.ts", "**/*.stories.ts", "fixtures/**", "test-setup.ts"], + "extends": "../../tsconfig.json", + "include": ["**/*.ts"] +} diff --git a/projects/ngx-bank/tsconfig.lib.prod.json b/projects/ngx-bank/tsconfig.lib.prod.json new file mode 100644 index 0000000..a416f78 --- /dev/null +++ b/projects/ngx-bank/tsconfig.lib.prod.json @@ -0,0 +1,11 @@ +/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ +/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ +{ + "angularCompilerOptions": { + "compilationMode": "partial" + }, + "compilerOptions": { + "declarationMap": false + }, + "extends": "./tsconfig.lib.json" +} diff --git a/projects/ngx-bank/tsconfig.spec.json b/projects/ngx-bank/tsconfig.spec.json new file mode 100644 index 0000000..7a9cb00 --- /dev/null +++ b/projects/ngx-bank/tsconfig.spec.json @@ -0,0 +1,10 @@ +/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ +/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ +{ + "compilerOptions": { + "outDir": "../../out-tsc/spec", + "types": ["vitest/globals", "@angular/localize"] + }, + "extends": "../../tsconfig.json", + "include": ["**/*.d.ts", "**/*.spec.ts", "fixtures/**/*.ts", "test-setup.ts"] +} diff --git a/projects/ngx-bookkeeping/CHANGELOG.md b/projects/ngx-bookkeeping/CHANGELOG.md new file mode 100644 index 0000000..f3be8d5 --- /dev/null +++ b/projects/ngx-bookkeeping/CHANGELOG.md @@ -0,0 +1,21 @@ +# Changelog + +## 22.4.0 + +First release. + +### Features +- `@service-soft/ngx-bookkeeping/api`: `BookkeepingService`, `EBilanzService`, their configs and the utilities for + amounts, days and fiscal years. +- `@service-soft/ngx-bookkeeping/journal` and `/journal-entry-form`: the journal, reversing an entry, and posting a + balanced one. +- `@service-soft/ngx-bookkeeping/ledger`, `/trial-balance`, `/statement`, `/balance-sheet` and `/income-statement`: the + reports, the statements with the year before and as a pdf. +- `@service-soft/ngx-bookkeeping/fiscal-years`: the fiscal years, their closing with proposals, the export for a tax + audit, and reopening a closed year with `canReopen` of the config. A year whose E-Bilanz was filed asks for a + confirmation, once `provideFiscalYearFilingResolver(EBilanzService)` tells it which ones are. +- `@service-soft/ngx-bookkeeping/e-bilanz`: preparing, reviewing, testing and filing the E-Bilanz of a fiscal year in + steps, with its records, account mappings and certificate in tabs. The transmission runs in the background and the + view follows it. A transmission that may have been sent stays open until its result is known or it is confirmed as + not received, and a filing after the first one is a correction, with its `revisionStatus`. +- The German translation of the texts ships with the package (`locale/messages.de.xlf`). diff --git a/projects/ngx-bookkeeping/LICENSE b/projects/ngx-bookkeeping/LICENSE new file mode 100644 index 0000000..959f86e --- /dev/null +++ b/projects/ngx-bookkeeping/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Tim Fabian + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/projects/ngx-bookkeeping/README.md b/projects/ngx-bookkeeping/README.md new file mode 100644 index 0000000..f60970e --- /dev/null +++ b/projects/ngx-bookkeeping/README.md @@ -0,0 +1,365 @@ +# ngx-bookkeeping +The views of double-entry books kept by your api: the journal, a form that posts a balanced entry, the ledger of an account, the trial balance, the balance sheet, the income statement, the fiscal years with their closing and their export for a tax audit, and the E-Bilanz with its preparation and filing. Every amount is written in the language of your app with the currency of the books, and every balance is the one your api answers: the views add up nothing but the lines of the entry being typed. + +It reads and posts the books through the models of [zibri-contract](https://www.npmjs.com/package/zibri-contract), like `JournalEntryDetailsModel` and `BookkeepingStatementModel`, which any api can answer; the bookkeeping plugin of [zibri](https://www.npmjs.com/package/zibri) is one that does. It is built on [@service-soft/ui](https://www.npmjs.com/package/@service-soft/ui), shows the messages of the api with [@service-soft/ngx-error-handling](https://www.npmjs.com/package/@service-soft/ngx-error-handling), and is styled with Tailwind CSS. + +The accounts, the settings of the books, the posting rules and the expenses are plain lists, which you build with the tables and forms of [@service-soft/ngx-entity](https://www.npmjs.com/package/@service-soft/ngx-entity). + +# Table of Contents +- [ngx-bookkeeping](#ngx-bookkeeping) +- [Table of Contents](#table-of-contents) +- [Requirements](#requirements) +- [Setup](#setup) +- [Days and amounts](#days-and-amounts) +- [The journal](#the-journal) +- [The entry form](#the-entry-form) +- [The ledger](#the-ledger) +- [The trial balance](#the-trial-balance) +- [The balance sheet and the income statement](#the-balance-sheet-and-the-income-statement) +- [The fiscal years](#the-fiscal-years) +- [The E-Bilanz](#the-e-bilanz) + - [Filing it step by step](#filing-it-step-by-step) + - [Correcting it once it is filed](#correcting-it-once-it-is-filed) + - [Sending it](#sending-it) + - [Waiting for the result](#waiting-for-the-result) + - [Enabling sending and the download](#enabling-sending-and-the-download) + - [The routes of the E-Bilanz](#the-routes-of-the-e-bilanz) + - [Configuring the E-Bilanz](#configuring-the-e-bilanz) +- [Downloads](#downloads) +- [The routes of the api](#the-routes-of-the-api) +- [Configuration](#configuration) + - [Translating](#translating) +- [License](#license) + +# Requirements +Angular 22 with `@angular/localize`, which [translates the texts](#translating), and `@angular/aria`, which the account inputs are built on, and Tailwind CSS 4. The models come from [zibri-contract](https://www.npmjs.com/package/zibri-contract) 3.3 or later. + +```sh +npm install @service-soft/ngx-bookkeeping @service-soft/ngx-error-handling @service-soft/ui @angular/aria zibri-contract +ng add @angular/localize +``` + +# Setup +Your Tailwind generates the css. Add the packages to your global stylesheet: + +```css +@import "tailwindcss"; +@import "@service-soft/ui"; +@import "@service-soft/ngx-error-handling"; +@import "@service-soft/ngx-bookkeeping"; +``` + +Give it the url of the bookkeeping routes of your api, and `HttpClient`, which it sends the requests with: + +```ts +// app.config.ts +import { provideHttpClient } from '@angular/common/http'; +import { provideRouter, withComponentInputBinding } from '@angular/router'; +import { provideBookkeepingConfig } from '@service-soft/ngx-bookkeeping/api'; + +export const appConfig: ApplicationConfig = { + providers: [ + provideHttpClient(), + provideRouter(routes, withComponentInputBinding()), + provideBookkeepingConfig({ baseUrl: 'https://api.example.com/bookkeeping' }) + ] +}; +``` + +```ts +// app.routes.ts +export const routes: Routes = [ + { + path: 'bookkeeping/journal', + title: 'Journal', + loadComponent: async () => (await import('@service-soft/ngx-bookkeeping/journal')).JournalComponent + }, + { + path: 'bookkeeping/entries/new', + title: 'New entry', + loadComponent: async () => (await import('@service-soft/ngx-bookkeeping/journal-entry-form')).JournalEntryFormComponent + }, + { + path: 'bookkeeping/ledger', + title: 'Ledger', + loadComponent: async () => (await import('@service-soft/ngx-bookkeeping/ledger')).LedgerComponent + }, + { + path: 'bookkeeping/trial-balance', + title: 'Trial balance', + loadComponent: async () => (await import('@service-soft/ngx-bookkeeping/trial-balance')).TrialBalanceComponent + }, + { + path: 'bookkeeping/balance-sheet', + title: 'Balance sheet', + loadComponent: async () => (await import('@service-soft/ngx-bookkeeping/balance-sheet')).BalanceSheetComponent + }, + { + path: 'bookkeeping/income-statement', + title: 'Income statement', + loadComponent: async () => (await import('@service-soft/ngx-bookkeeping/income-statement')).IncomeStatementComponent + }, + { + path: 'bookkeeping/fiscal-years', + title: 'Fiscal years', + loadComponent: async () => (await import('@service-soft/ngx-bookkeeping/fiscal-years')).FiscalYearsComponent + } +]; +``` + +Every view is an entry point of its own, so each page loads only its own code. They read the `BookkeepingService` and the config of `@service-soft/ngx-bookkeeping/api`. The headline of each page is yours, like the `title` of its route; the headings inside the views start at the `headingLevel` of the config, `2` by default. + +# Days and amounts +The books are kept by days, which the api holds as their midnight UTC: the start of a fiscal year, or the posting day of an entry. The date inputs of ui hold the midnight of a day in the time zone of the browser, so the views send the same day the user chose wherever the browser is, and show the days of the api as they are. They are written with `Intl` in the `LOCALE_ID` of your app, like the date inputs write them, `12/31/2026` in `en-US` or `31.12.2026` in `de`, so a day reads the same in a list as in an input; `dateFormat` of the config changes the options. `BookkeepingDayUtilities` of the api entry point converts both ways for code of your own. + +Amounts are the decimal strings of the api, like `'1190'` or `'-350.5'`. The views write them with `Intl` in the `LOCALE_ID` of your app, in the currency of the settings of the books (`GET /settings`), with its minor units, like `€1,190.00` in `en-US` or `1.190,00 €` in `de`. `BookkeepingAmountUtilities` has the same for your own code. A balance is never added up in the browser: each is the one the api answers. + +# The journal +```html + +``` + +The entries of a fiscal year, the one of today at first or the latest, by posting day and number, 20 to a page. Each shows its number, its text, its posting day, the day and number of its document, and its lines with their accounts and amounts. A period narrows it to some days of the fiscal year, and an account to the entries that book on it. The api filters and pages them, `GET /entries`, so the browser loads one page at a time however long the year is, and a filter starts over on the first page. Below the journal are the debits and the credits of every entry that matches, as the api adds them up, with an account of only its lines on that account. The journal of the period downloads as the pdf of `GET /reports/journal.pdf`. + +A reversal says that it is one, and a reversed entry, which the api names by its `reversedByEntryId`, that it is reversed; both say by which entry when that is on the page. The others have a button that reverses them: a dialog asks for the day of the reversal, today at first, and its reason, its text, and reverses the entry once the user confirms with both. A refusal of the api, like for a day of a closed fiscal year, shows its message in the dialog. The journal then loads again, says that the entry was reversed and by which, and shows the reversal next to it. + +# The entry form +```html + +``` + +Posts an entry: the days of its document and of its posting, today at first, the number of its document, which is optional, its text, and two or more lines, each on an open account, searched by number and name, with a debit or a credit. Lines are added and removed below them. The debits, the credits and their difference show while the user types, added up in minor units, so `0.1` and `0.2` are `0.30`. + +The browser submits the form only once it is valid: a line without an amount or with both says so at its debit, and an entry whose sides differ is refused with "The debits and the credits differ by €200.00. An entry is posted once both are equal." That error is set on a hidden input with `setCustomValidity()`, which keeps the form from submitting like any invalid control, so an unbalanced entry is never sent. It shows below the sums, in a live region, and describes the button that adds a line, which gets the focus. + +Once the api posted the entry, the form says so with its number, emits it on `posted`, and starts over with the same days. A refusal of the api, like for a day in a closed fiscal year, shows its message and keeps what the user typed. + +# The ledger +```html + + +``` + +What was booked on an account in a fiscal year, or in a period of it: the balance before, each line with its day, entry, document, text, amount and the balance after it, the sums of both sides and the balance after. A balance shows its side after its amount, `Dr` or `Cr` (`S` or `H` in German), which screen readers read as the word. Bind `accountId` to choose the account from your app, like from the url. + +# The trial balance +```html + +``` + +The trial balance (Summen- und Saldenliste) of a fiscal year: the debits and the credits of every account booked on, and its balance in the column of its side, up to a day of the year the user chooses or to its end, with the sums of every column as the api answers them. + +# The balance sheet and the income statement +```html + + +``` + +A statement of a fiscal year: its positions in their order, each indented by its depth and the ones with positions below them in bold, with the amount of the year and the one of the year before, and below the result of the year. The column of a balance sheet is headed by its day, the one of an income statement by its fiscal year. A badge says whether the statement is final, as its fiscal year is closed and the statement the one archived then, or preliminary. + +Accounts with a balance but no position in the statement show in a warning below it, each with its amount, as their balance is in none of the positions. + +The forms a statement can be shown in are the api's, `GET /fiscal-years/:id/statement-forms`, with their names in the language of the request. The statement shows the one that applies to the fiscal year, like the shortened form of a micro corporation, and a select offers the others where there are any, the applying one marked as "(the form of the fiscal year)". A form chosen stays until another fiscal year is chosen. + +`` of `@service-soft/ngx-bookkeeping/statement` is the same, by its type. + +# The fiscal years +```html + + +``` + +A table of the fiscal years, the latest first, each with its days and whether it is open or when it was closed, and below it adding one: the first from the day the user gives, every later one from the day after the last, each up to the day the user gives or the default of the api. The fiscal year opened from the table, the one of today at first, shows below, its heading taking the focus: + +- **For the statements**: its average number of employees and the note below the balance sheet, and for the first fiscal year of the books what the company was before it, founded in it or of which size class. Saved while the year is open, and shown as it was closed with afterwards. Name the size classes of your api with `sizeClasses` of the config. +- **Closing**: the entries the conformances of the api propose before closing, like the legal reserve of a UG, each with who proposes it (`conformances` of the config names them), its day and its lines. Each is posted after the user confirms it. Then the user chooses the open equity account the result goes to, and closes the year after confirming that as well; the next fiscal year then shows in the table. A refusal, like while a proposal isn't posted, shows the message of the api. +- **Reopening**, with `canReopen`, like with `bookkeeping.reopen-fiscal-year`: a closed fiscal year has a button that reopens it to correct its books. A dialog says what that does: the closing is reversed, and the opening balances of the next fiscal year, so the year can be posted to and closed again, and nothing is deleted, the entries of the closing and the statements archived at it are kept. The user gives the reason, which is required, up to 500 characters, and the text of the reversals. A fiscal year whose E-Bilanz is filed is only reopened to correct it: the dialog says so, and a checkbox that the reopening is to correct the filed E-Bilanz is required, which sends `forCorrection: true`. The api asks for a second factor, which the `authInterceptor` of [@service-soft/ngx-auth](https://www.npmjs.com/package/@service-soft/ngx-auth) asks the user for. A refusal of the api, like while the next fiscal year is closed and is reopened first, or while a transmission of its E-Bilanz runs or has a result that is not known, shows its message in the dialog. Once reopened, the year shows as open, and its closing as above. Its default is `canReopen` of the config, `false`. +- **Export for a tax audit**: downloads the zip archive of the fiscal year, with its documents or without. + +The fiscal years know nothing of the E-Bilanz, so whether its E-Bilanz is filed comes from a `FiscalYearFilingResolver` you provide where they show, like the `EBilanzService`, which loads the E-Bilanz of the fiscal year when the dialog opens: + +```ts +// app.routes.ts +import { EBilanzService, provideFiscalYearFilingResolver } from '@service-soft/ngx-bookkeeping/api'; + +{ + path: 'bookkeeping/fiscal-years', + title: 'Fiscal years', + providers: [provideFiscalYearFilingResolver(EBilanzService)], + loadComponent: async () => (await import('@service-soft/ngx-bookkeeping/fiscal-years')).FiscalYearsComponent +} +``` + +Without one, the dialog doesn't know, and lets the user say whether the accounts of the year are filed already and the reopening is to correct them, which isn't required then. An app with accounts filed some other way provides a resolver of its own, any injectable with `resolveFiled(fiscalYearId)`. + +# The E-Bilanz +```html + +``` + +The E-Bilanz of a closed fiscal year, the latest at first, which a German company keeping balance sheets files with the tax administration, § 5b EStG. It has a config of its own, `provideEBilanzConfig` of `@service-soft/ngx-bookkeeping/api`, with the url of its routes, beside the books of `provideBookkeepingConfig`, whose days, amounts and heading level it uses: + +```ts +// app.config.ts +import { provideBookkeepingConfig, provideEBilanzConfig } from '@service-soft/ngx-bookkeeping/api'; + +export const appConfig: ApplicationConfig = { + providers: [ + provideHttpClient(), + provideBookkeepingConfig({ baseUrl: 'https://api.example.com/bookkeeping' }), + provideEBilanzConfig({ baseUrl: 'https://api.example.com/e-bilanz' }) + ] +}; +``` + +```ts +// app.routes.ts +{ + path: 'bookkeeping/e-bilanz', + title: 'E-Bilanz', + loadComponent: async () => (await import('@service-soft/ngx-bookkeeping/e-bilanz')).EBilanzComponent +} +``` + +Above its tabs, a select chooses the fiscal year, and the heading shows the status of its E-Bilanz (not prepared, prepared, prepared before the books changed, filed, or filed and being corrected) and its deadline. The tabs: + +- **Filing**: the steps of filing it, see [filing it step by step](#filing-it-step-by-step). +- **Records**: each preparation, test, transmission and filing by hand, with when it was recorded, the ticket of a transmission and where it stands (started, accepted, refused, failed, result not known, or not received), what the tax administration answered or what failed, and its protocol to download from the `url` the api gives it. A transmission has two records: the one it started with, and the one of its result. A preparation that corrects a filed E-Bilanz names the record it corrects, by its `correctsFilingId`, and what it corrects. +- **Account mappings**, with `canManage`: the accounts mapped to a position of their own, and the accounts the findings say need a position, with their balance in the fiscal year. The user maps an account, changes a mapping and removes it. +- **ELSTER certificate**, with `canManage`: whether one is uploaded and when, and uploading a new one with its PIN, which is sent once and never shown again. + +`canPrepare`, `canTransmit` and `canManage` are what the user may do, like with `bookkeeping.e-bilanz.prepare`, `.transmit` and `.manage`; the view needs `bookkeeping.e-bilanz.read`. Without one, its buttons and tabs don't show. Their defaults are `canPrepare`, `canTransmit` and `canManage` of `provideEBilanzConfig`, `false`. + +## Filing it step by step +The tab of filing it has four steps, `ui-stepper` of [@service-soft/ui](https://www.npmjs.com/package/@service-soft/ui). It opens at the step of how far the E-Bilanz is: preparing it while it isn't prepared, reviewing it once it is, the last step once a test of it was accepted, and every step done once it is filed, with how and when it was filed. A step opens once the one before is done, and the user goes back to a done step by its name. Going to a step or a tab sends nothing. + +1. **Prepare**: the user chooses the balance sheet, the commercial one that is the tax balance sheet as well (Einheitsbilanz) or a tax balance sheet of its own. There is no default, as both are legitimate; once it is prepared, the step shows the one it was prepared with. The preview (`POST /fiscal-years/:id/preview`) shows the E-Bilanz as the books state it and keeps nothing. For each row of the statement of changes in fixed assets a finding names, the inputs of the figures the books don't state show, those of the latest preparation at first. "Prepare" prepares exactly what was previewed, once it needs nothing more, and the review opens. The review only opens once it is prepared as the books state it. +2. **Review**: what it needs, each finding with the position, the field or the account it is about, linked to the figures, the row or the account that changes it, and the message of the api. A link opens the step or the tab of what it links to, and moves the focus there. Then the content, of the preview or of the latest preparation, with the version of its taxonomy, its balance sheet and the company with its tax number, in a tab each for the balance sheet, the income statement and the statement of changes in fixed assets. Each position is indented by its depth with its amount, NIL for a position the tax administration asks for that the books don't state, and the accounts it is made of below it; each row of the fixed assets is indented by the row it is summed into. The company is the one of the settings of the books (`PATCH /settings` with `company`), not of the E-Bilanz. +3. **Test**: sends it as a test. Whoever files it by hand goes on without one. +4. **Send or file by hand**: sends it for real, or downloads it and marks it as filed by hand. Its last button shows the records. + +When the books changed since it was prepared, it opens at preparing it again, and says why. + +### Correcting it once it is filed +A filed E-Bilanz is corrected (Berichtigung, § 153 AO) by preparing it again, like after [reopening its fiscal year](#the-fiscal-years), correcting the books and closing it again, or once only what it states beside the books changed, like an account mapping or the company. Its status is then "Filed, being corrected", and it opens at preparing it with a note on how. The step that prepares it then asks what the correction corrects, the `revisionStatus` of the `EBilanzPreparationInputModel`, which the api requires once it is filed and refuses before. There is no default, as only the user knows, and each choice says when it applies: + +| Choice | `revisionStatus` | When | +|---|---|---| +| Errors corrected | `corrected` | The balance sheet or the income statement had an error, which is fixed now (berichtigt, § 4 (2) sentence 1 EStG) | +| A choice changed | `changed` | Nothing was wrong, but a choice the law allows is made differently now, like how an asset is valued (geändert, § 4 (2) sentence 2 EStG) | +| Both | `corrected-and-changed` | An error is fixed, and a choice is made differently as well | +| Only more detail | `more-detail` | The same figures as filed, only with more detail, like the accounts of each position | +| Another correction | `other-correction` | Only something outside the balance sheet and the income statement changed, like the details of the company (sonstige Korrektur) | + +The preview and the preparation send it, so what is previewed is what is prepared. The correction is then tested and filed like the first E-Bilanz, and the filed one says how to correct it. + +## Sending it +Nothing is ever sent by itself: every request that files the E-Bilanz is one the user pressed a button for. It is sent from the app, or filed by hand, which never needs a test. + +| Button | Step | Needs | Disabled while | +|---|---|---|---| +| Send as a test | Test | `canTransmit` | the app can't send it, it isn't prepared, the books changed since, it is filed as prepared, a transmission runs, or a test has a result that is not known | +| Send to the tax administration | Send or file by hand | `canTransmit` | as above, with a transmission for real whose result is not known, and until a test of the same content was accepted | +| Download, one per exporter of the api | Send or file by hand | `canPrepare` | the app has no exporter, it isn't prepared, or the books changed since | +| Mark as filed by hand | Send or file by hand | `canTransmit` | it isn't prepared, the books changed since, it is filed as prepared, or a transmission runs | + +A disabled button says why and how to enable it, in words for its users: while the app can't send it, "Sending isn't set up in this app. Download the file, file it with another program and mark it as filed here. To send from here, ask your administrator to set up sending.", and to a user with `canManage` while no certificate is uploaded, that sending needs it as well. The view doesn't show the `transmitterUnavailableReason` of the api, which names what a developer sets up. Sending for real asks first, naming the company, its tax number, the fiscal year, when it was prepared, its taxonomy, its balance sheet and its accepted test, and that it is final; cancelling sends nothing. The api asks for a second factor of the user for it, which the `authInterceptor` of [@service-soft/ngx-auth](https://www.npmjs.com/package/@service-soft/ngx-auth) asks the user for with its `secondFactorPrompt`; without it, or when the user cancels, the view shows the refusal of the api. Marking it as filed by hand asks for the transmission protocol, which is required. + +### Waiting for the result +The api sends in the background, as a transmission can take minutes: both routes answer `202` with the record the transmission started with, whose `status` is `transmitting`. Above the steps, the view then says "Sending to ELSTER… This can take several minutes. You can leave this page; the result is recorded.", and every button that sends waits. It loads the E-Bilanz again (`GET /fiscal-years/:id`) after 2 seconds, then each time half as long again as before, up to every 20 seconds, until the transmission in its `transmissions` has another `status`, also when it was opened while one ran. It stops once it has the result, or once the view is destroyed. Loading it again only reads: nothing is sent again, and nothing is retried. Then it says the result: accepted, refused with what the tax administration answered, or failed, with what failed, the `paragraphs` of its `error`, and that nothing was sent when the api says so (`mayHaveBeenSent` is false), after which it can be sent again. + +A transmission whose result is not known, `unknown` or `failed` while it `mayHaveBeenSent`, may have reached the tax administration. The view warns "It may have been sent. Check in ELSTER whether it arrived before you do anything else.", with when it started and what failed, and no transmission of its kind, a test or one for real, is sent until it is settled. A user with `canTransmit` settles it once they checked ELSTER: it arrived, so they mark the E-Bilanz as filed by hand with the protocol of ELSTER, offered for a transmission for real, or it didn't, so they say "ELSTER did not receive it". A question says that it is only confirmed after checking ELSTER, and that sending it again files it twice if it did arrive; once confirmed, `POST /fiscal-years/:id/transmission-not-received` records each such transmission as `not-received`, with a second factor the `authInterceptor` asks for like for sending, and it can be sent again. + +## Enabling sending and the download +Whether the E-Bilanz can be sent from the app is `transmitterConfigured` of the `EBilanzStateModel` the api answers, and what it can be downloaded as is its `exporters`. With the E-Bilanz plugin of zibri, see [filing the E-Bilanz](https://service-soft.github.io/zibri/plugins/e-bilanz/): + +- **Sending** needs a transmitter, an `EBilanzTransmitterInterface` you provide with `E_BILANZ_TRANSMITTER_DI_VARIANT`, such as one sending through ERiC, and the ELSTER certificate of the company with its PIN, which a user with `canManage` uploads in the tab of the certificate. None is registered for you, so an app starts with filing by hand. +- **The download** needs an exporter, an `EBilanzExporterInterface` you provide with `E_BILANZ_EXPORTER_DI_VARIANT`, such as `XbrlEBilanzExporter`, which writes the XBRL the tax administration takes. + +## The routes of the E-Bilanz +The `EBilanzService` sends these requests below the `baseUrl` of `provideEBilanzConfig`, as the `EBilanzController` of the E-Bilanz plugin of zibri answers them, with the models of zibri-contract. Change the paths with `paths` of `provideEBilanzConfig`. + +| Request | Answers | Permission in zibri | +|---|---|---| +| `GET /fiscal-years/:id` | the `EBilanzStateModel` | `bookkeeping.e-bilanz.read` | +| `POST /fiscal-years/:id/preview` with an `EBilanzPreparationInputModel` | the `EBilanzPreviewModel`, the content and the findings | `bookkeeping.e-bilanz.read` | +| `POST /fiscal-years/:id/preparation` with an `EBilanzPreparationInputModel` | the `EBilanzFilingModel`, with the `correctsFilingId` of a correction | `bookkeeping.e-bilanz.prepare` | +| `GET /fiscal-years/:id/export?exporter` | the file of the exporter | `bookkeeping.e-bilanz.prepare` | +| `POST /fiscal-years/:id/test-transmission` | `202` and the `EBilanzFilingModel` it started with, `transmitting` | `bookkeeping.e-bilanz.transmit` | +| `POST /fiscal-years/:id/transmission` | the same, with a second factor | `bookkeeping.e-bilanz.transmit` | +| `POST /fiscal-years/:id/transmission-not-received` | every `EBilanzFilingModel` it wrote, with a second factor | `bookkeeping.e-bilanz.transmit` | +| `POST /fiscal-years/:id/manual-filing` with the part `protocol` | the `EBilanzFilingModel` | `bookkeeping.e-bilanz.transmit` | +| the `url` of the `protocol` of a record, `GET /:id/files/protocol` in zibri | the protocol | `bookkeeping.e-bilanz.read` | +| `GET /settings` | the `EBilanzCertificateSettingsModel`, when the certificate was uploaded | `bookkeeping.e-bilanz.read` | +| `PUT /settings/certificate` with the parts `certificate` and `pin` | the same | `bookkeeping.e-bilanz.manage` | +| `GET /account-mappings` | every `EBilanzAccountMappingModel`, the accounts mapped to a position of their own | `bookkeeping.e-bilanz.read` | +| `PUT /account-mappings/:accountId` with an `EBilanzAccountMappingChangeModel` | the `EBilanzAccountMappingModel` | `bookkeeping.e-bilanz.manage` | +| `DELETE /account-mappings/:accountId` | nothing | `bookkeeping.e-bilanz.manage` | + +The view also reads `GET /settings`, `GET /accounts`, `GET /fiscal-years` and, for the balances of accounts without a position, `GET /reports/trial-balance` of the books. + +## Configuring the E-Bilanz +`provideEBilanzConfig` sets the `baseUrl` of the E-Bilanz and the defaults of its view, for the whole app, or for a part of it when you add it to the providers of a component or route. Values you leave out keep the ones of the parent, single paths and labels included: + +| Option | Default | +|---|---| +| `baseUrl` | required — the url of the E-Bilanz routes of your api | +| `paths` | the paths of [the routes of the E-Bilanz](#the-routes-of-the-e-bilanz), like `{ preview: 'preview', certificate: 'settings/certificate' }` | +| `canPrepare`, `canTransmit`, `canManage` | `false` — the defaults of `canPrepare`, `canTransmit` and `canManage` of the view | +| `labels` | the English texts of the view, by part: `common`, `preparation`, `review`, `filing`, `records`, `accountMappings` and `certificate` | + +Its days, amounts and heading level are those of `provideBookkeepingConfig`, its texts are [translated](#translating) like the others, with ids like `@@ngx-bookkeeping.api.eBilanz.filing.testTransmission`, and the stepper's own buttons, like "Next", are those of `provideStepperConfig` of `@service-soft/ui/stepper`. + +# Downloads +Every report downloads as a pdf, the one your api renders, with the same fiscal year, form, account and period the view shows, and the fiscal years download their export. The file is saved under the name the api gives it in its `Content-Disposition`, which an api of another origin exposes with `Access-Control-Expose-Headers`, or under the name of the report. The download is a request of `HttpClient`, so it carries what your interceptors add, like the tenant and the token of `@service-soft/ngx-auth`, and the file is held in memory until it is saved, which for the export with all documents of a year can be large. A download that fails says so. + +# The routes of the api +The `BookkeepingService` sends these requests below the `baseUrl`, as the `BookkeepingController` of the bookkeeping plugin of zibri answers them. The dates of the models arrive as the strings of json, and the service answers them as `Date`, as the models declare them. + +| Request | Answers | Used by | Permission in zibri | +|---|---|---|---| +| `GET /settings` | the `BookkeepingSettingsModel`, whose `currency` the amounts are in | every view | `bookkeeping.read` | +| `GET /accounts` | every `BookkeepingAccountModel`, by number | the journal, the entry form, the ledger, the fiscal years | `bookkeeping.read` | +| `GET /fiscal-years` | every `FiscalYearModel`, the earliest first | every view but the entry form | `bookkeeping.read` | +| `POST /fiscal-years` with a `NewFiscalYearModel` | the `FiscalYearModel` added | the fiscal years | `bookkeeping.manage` | +| `PATCH /fiscal-years/:id` with a `FiscalYearChangeModel` | the `FiscalYearModel` changed | the fiscal years | `bookkeeping.manage` | +| `GET /fiscal-years/:id/statement-forms` | the `BookkeepingStatementFormChoicesModel`: the forms of both statements, and the one that applies to each | the statements | `bookkeeping.read` | +| `GET /fiscal-years/:id/closing-proposals` | every `BookkeepingClosingProposalModel` | the fiscal years | `bookkeeping.close-fiscal-year` | +| `POST /fiscal-years/:id/closing` with a `FiscalYearClosingModel` | the `FiscalYearClosingResultModel` | the fiscal years | `bookkeeping.close-fiscal-year` | +| `POST /fiscal-years/:id/reopening` with a `FiscalYearReopeningModel` | the `FiscalYearReopeningResultModel`, with a second factor | the fiscal years | `bookkeeping.reopen-fiscal-year` | +| `GET /fiscal-years/:id/export?documents` | the zip archive, `BookkeepingExportOptionsModel` as its query | the fiscal years | `bookkeeping.export` | +| `GET /entries?page&limit&fiscalYearId&from&until&accountId` | the `JournalEntryPageModel`: a page of `JournalEntryDetailsModel`s, by posting day and number, each with its `reversedByEntryId`, and the `debit` and `credit` of all entries that match, `JournalEntryQueryModel` as its query | the journal | `bookkeeping.read` | +| `POST /entries` with a `NewJournalEntryModel` | the `JournalEntryDetailsModel` posted | the entry form, the fiscal years | `bookkeeping.post` | +| `POST /entries/:id/reversal` with a `JournalEntryReversalModel` | the `JournalEntryDetailsModel` of the reversal | the journal | `bookkeeping.post` | +| `GET /reports/journal.pdf?from&until` | the journal of the period as a pdf | the journal | `bookkeeping.read` | +| `GET /reports/ledger?accountId&from&until` | the `BookkeepingLedgerReportModel` | the ledger | `bookkeeping.read` | +| `GET /reports/trial-balance?fiscalYearId&until` | the `BookkeepingTrialBalanceModel` | the trial balance | `bookkeeping.read` | +| `GET /reports/balance-sheet?fiscalYearId&form` | the `BookkeepingStatementModel` | the balance sheet | `bookkeeping.read` | +| `GET /reports/income-statement?fiscalYearId&form` | the `BookkeepingStatementModel` | the income statement | `bookkeeping.read` | +| `GET /reports/.pdf` | each report above as a pdf, with the same query | the view of the report | `bookkeeping.read` | + +Days in a query are written as `2026-03-31`, and in a body as their midnight UTC. A page of `GET /entries` holds at most 100 entries, so keep `pageSize` at 100 or below. Change the paths with `paths` of the config. Every route answers the books of the active tenant, which the `authInterceptor` of ngx-auth sends. `lastPosting` of the service changes with every entry the app posts, reverses, closes or reopens a fiscal year with; the journal and the closing load again after each. + +# Configuration +`provideBookkeepingConfig` sets the `baseUrl` and the defaults of the views, for the whole app, or for a part of it when you add it to the providers of a component or route. Values you leave out keep the ones of the parent, single paths, labels and dialog texts included: + +| Option | Default | +|---|---| +| `baseUrl` | required — the url of the bookkeeping routes of your api | +| `paths` | the paths of the table above, like `{ entries: 'entries', statementForms: 'statement-forms', journal: 'reports/journal' }` | +| `pageSize` | `20` — how many entries a page of the journal has, at most 100 | +| `dateFormat` | `{ year: 'numeric', month: '2-digit', day: '2-digit' }` — the days of the books, as the options of `Intl.DateTimeFormat` in the `LOCALE_ID`; replaced as a whole | +| `headingLevel` | `2` — the level of the headings inside the views; their sections are headed one level below | +| `sizeClasses` | `MICRO`, `SMALL`, `MEDIUM` and `LARGE`, the classes of § 267 and § 267a HGB — what a company can have been before its first fiscal year, by the value the api takes; replaced as a whole | +| `conformances` | `{}` — what the conformances of your api are called, by name, like `{ 'ug-legal-reserve': 'Legal reserve of a UG' }` | +| `canReopen` | `false` — the default of `canReopen` of the fiscal years | +| `labels` | the English texts of the views, by view: `common`, `journal`, `entryForm`, `ledger`, `trialBalance`, `statements` and `fiscalYears` | +| `postProposalConfirmDialogData`, `closeConfirmDialogData` | the title, text and buttons of the questions before posting a proposed entry and closing a fiscal year | + +## Translating +The default texts are `$localize` with an id of their own, like `@@ngx-bookkeeping.api.journal.reverse`, so `ng extract-i18n` puts them into the messages of your app, and you translate them like its own texts. The library needs `@angular/localize` for that, `ng add @angular/localize`, also in an app of one language. A build with `localize` fills the texts in, so no part of `@angular/localize` reaches the browser. The defaults are made once the config is injected, so translations an app loads at runtime with `loadTranslations` apply as well. A text of `provideBookkeepingConfig` replaces the default in every language. So translate a default in your messages, and change it in the config only to say something else. + +German ships with the library: `locale/messages.de.xlf` of the package is an XLIFF 1.2 file with a German target for each of its texts, and its `package.json` names it in `"translations": { "de": "./locale/messages.de.xlf" }`. A merge of the translations of an app's dependencies reads that field and fills these targets into the German messages of the app, so German needs no translation of your own. The labels of the positions of a statement, the names of its forms, and the names of the accounts are data of your api, in the language it answers in. + +# License +MIT. diff --git a/projects/ngx-bookkeeping/api/bookkeeping-amount.utilities.spec.ts b/projects/ngx-bookkeeping/api/bookkeeping-amount.utilities.spec.ts new file mode 100644 index 0000000..4dca227 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-amount.utilities.spec.ts @@ -0,0 +1,31 @@ +import { describe, expect, test } from 'vitest'; + +import { BookkeepingAmountUtilities } from './bookkeeping-amount.utilities'; + +describe('BookkeepingAmountUtilities', () => { + test('writes the decimal strings of the api in the language of the app with the currency of the books', () => { + const euro: Intl.NumberFormat = BookkeepingAmountUtilities.resolveFormat('EUR', 'en-US'); + + expect(BookkeepingAmountUtilities.format('1190', euro)).toBe('€1,190.00'); + expect(BookkeepingAmountUtilities.format('-350.5', euro)).toBe('-€350.50'); + expect(BookkeepingAmountUtilities.format('1190', BookkeepingAmountUtilities.resolveFormat('JPY', 'en-US'))).toBe('¥1,190'); + }); + + test('adds up amounts in minor units without the rounding errors of decimals', () => { + const fractionDigits: number = BookkeepingAmountUtilities.resolveFractionDigits(BookkeepingAmountUtilities.resolveFormat('EUR', 'de')); + const sum: number = [0.1, 0.2].reduce((total, amount) => total + BookkeepingAmountUtilities.resolveMinorUnits(amount, fractionDigits), 0); + + expect(fractionDigits).toBe(2); + expect(sum).toBe(30); + expect(BookkeepingAmountUtilities.resolveDecimal(sum, fractionDigits)).toBe('0.30'); + expect(BookkeepingAmountUtilities.resolveDecimal(119_000, 2)).toBe('1190.00'); + }); + + test('tells the sign of an amount of the api', () => { + expect(BookkeepingAmountUtilities.isNegative('-190')).toBe(true); + expect(BookkeepingAmountUtilities.isNegative('190')).toBe(false); + expect(BookkeepingAmountUtilities.isZero('0.00')).toBe(true); + expect(BookkeepingAmountUtilities.getAbsolute('-190')).toBe('190'); + expect(BookkeepingAmountUtilities.getAbsolute('190')).toBe('190'); + }); +}); diff --git a/projects/ngx-bookkeeping/api/bookkeeping-amount.utilities.ts b/projects/ngx-bookkeeping/api/bookkeeping-amount.utilities.ts new file mode 100644 index 0000000..5ba3b17 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-amount.utilities.ts @@ -0,0 +1,86 @@ +/** + * The amounts of the books: the api writes each as a decimal string in the currency of the books, like '1190' or + * '-350.5', and the views write them in the language of the app with that currency. Nothing here adds up balances, + * which the api answers; only an entry being typed adds up its lines, in minor units. + */ +export abstract class BookkeepingAmountUtilities { + /** + * Resolves how amounts of a currency are written in a language. + * @param currency - The currency of the books, as an ISO 4217 code like 'EUR'. + * @param locale - The language, like the LOCALE_ID of the app. + * @returns The format, with the minor units of the currency, like 2 decimals for EUR. + */ + static resolveFormat(currency: string, locale: string): Intl.NumberFormat { + return new Intl.NumberFormat(locale, { style: 'currency', currency }); + } + + /** + * Formats an amount of the api. + * @param amount - The decimal string, like '1190' or '-350.5'. + * @param format - The format of the currency, from resolveFormat. + * @returns The amount as it shows, like '€1,190.00'. + */ + static format(amount: string, format: Intl.NumberFormat): string { + // a number keeps 15 significant digits, which is every amount of a small company's books to the cent. format + // takes a decimal string as well in current browsers, but the types of the targeted lib don't declare it yet. + return format.format(Number(amount)); + } + + /** + * Resolves the decimals of the minor unit of the currency of a format. + * @param format - The format of the currency, from resolveFormat. + * @returns The decimals, like 2 for EUR and 0 for JPY. + */ + static resolveFractionDigits(format: Intl.NumberFormat): number { + // Intl knows the minor units from ISO 4217, so they aren't kept in a table of our own. + return format.resolvedOptions().maximumFractionDigits ?? 2; + } + + /** + * Resolves an amount typed into an input in minor units, which add up without the rounding errors of decimals. + * @param amount - The amount, like 12.3. + * @param fractionDigits - The decimals of the currency. + * @returns The amount in minor units, like 1230. + */ + static resolveMinorUnits(amount: number, fractionDigits: number): number { + return Math.round(amount * (10 ** fractionDigits)); + } + + /** + * Resolves the decimal string of an amount in minor units, as the api takes it. + * @param minorUnits - The amount in minor units, like 1230. + * @param fractionDigits - The decimals of the currency. + * @returns The decimal string, like '12.30'. + */ + static resolveDecimal(minorUnits: number, fractionDigits: number): string { + return (minorUnits / (10 ** fractionDigits)).toFixed(fractionDigits); + } + + /** + * Whether an amount of the api is below zero, like a balance on the credit side. + * @param amount - The decimal string. + * @returns True for a negative amount. + */ + static isNegative(amount: string): boolean { + return amount.trim().startsWith('-'); + } + + /** + * Whether an amount of the api is zero, like '0' or '0.00'. + * @param amount - The decimal string. + * @returns True for zero. + */ + static isZero(amount: string): boolean { + return Number(amount) === 0; + } + + /** + * Gets an amount of the api without its sign. + * @param amount - The decimal string, like '-350.5'. + * @returns The amount without a minus, like '350.5'. + */ + static getAbsolute(amount: string): string { + const trimmed: string = amount.trim(); + return trimmed.startsWith('-') ? trimmed.slice(1) : trimmed; + } +} diff --git a/projects/ngx-bookkeeping/api/bookkeeping-common-labels.model.ts b/projects/ngx-bookkeeping/api/bookkeeping-common-labels.model.ts new file mode 100644 index 0000000..90c2a4a --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-common-labels.model.ts @@ -0,0 +1,105 @@ +/** + * The texts several views of the books show, to translate them. + */ +export type BookkeepingCommonLabels = { + /** + * The select of the fiscal year. + */ + fiscalYear: string, + /** + * The input of the days a report covers. + */ + period: string, + /** + * The first day of the period. + */ + periodStart: string, + /** + * The last day of the period. + */ + periodEnd: string, + /** + * The hint below the period. + */ + periodHint: string, + /** + * An account of the books. + */ + account: string, + /** + * The debit side, like the header of its column. + */ + debit: string, + /** + * The credit side, like the header of its column. + */ + credit: string, + /** + * A balance. + */ + balance: string, + /** + * What a balance on the debit side shows after its amount, like 'Dr'. Screen readers read the debit label instead. + */ + debitSide: string, + /** + * What a balance on the credit side shows after its amount, like 'Cr'. Screen readers read the credit label instead. + */ + creditSide: string, + /** + * The row of the sums of a report. + */ + total: string, + /** + * The day an entry is booked on. + */ + postingDate: string, + /** + * The day of the document an entry is booked from. + */ + documentDate: string, + /** + * The number of the document an entry is booked from. + */ + documentReference: string, + /** + * What an entry booked. + */ + text: string, + /** + * The header of the entries of a report. + */ + entry: string, + /** + * An entry by its number in its fiscal year. + */ + entryNumber: (sequence: number) => string, + /** + * The button that saves a report as a pdf. + */ + downloadPdf: string, + /** + * What a view says when a file couldn't be downloaded. + */ + downloadFailed: string, + /** + * What screen readers read while a view loads. + */ + loading: string, + /** + * What a view says when the books couldn't be loaded. + */ + loadingFailed: string, + /** + * What a view says when the books have no fiscal year yet. + */ + noFiscalYears: string, + /** + * What a view says when a request was refused without a message of the server, like without a connection. + */ + requestFailed: string, + /** + * The button that cancels a dialog. + */ + cancel: string +}; diff --git a/projects/ngx-bookkeeping/api/bookkeeping-config-changes.model.ts b/projects/ngx-bookkeeping/api/bookkeeping-config-changes.model.ts new file mode 100644 index 0000000..25b2630 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-config-changes.model.ts @@ -0,0 +1,34 @@ +import { ConfirmDialogData } from '@service-soft/ui/dialog'; + +import { BookkeepingConfig } from './bookkeeping-config.model'; +import { BookkeepingLabelsChanges } from './bookkeeping-labels-changes.model'; + +/** + * The values to change in the config of the books. Everything is optional, including every single path, label and text + * of the confirm dialogs, but the requests need the baseUrl once. + */ +export type BookkeepingConfigChanges = Partial> & { + /** + * The url of the bookkeeping routes of your api, like 'https://api.example.com/bookkeeping'. + */ + baseUrl?: string, + /** + * The paths to change. + */ + paths?: Partial, + /** + * The labels to change, by the view that shows them. + */ + labels?: BookkeepingLabelsChanges, + /** + * The texts of the question before posting a proposed entry to change. + */ + postProposalConfirmDialogData?: Partial, + /** + * The texts of the question before closing a fiscal year to change. + */ + closeConfirmDialogData?: Partial +}; diff --git a/projects/ngx-bookkeeping/api/bookkeeping-config.model.ts b/projects/ngx-bookkeeping/api/bookkeeping-config.model.ts new file mode 100644 index 0000000..dae3e81 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-config.model.ts @@ -0,0 +1,62 @@ +import { ConfirmDialogData } from '@service-soft/ui/dialog'; +import { HeadingLevel } from '@service-soft/ui/heading'; + +import { BookkeepingLabels } from './bookkeeping-labels.model'; +import { BookkeepingPaths } from './bookkeeping-paths.model'; + +/** + * Where the books are, and the values their views use. + */ +export type BookkeepingConfig = { + /** + * The url of the bookkeeping routes of your api, like 'https://api.example.com/bookkeeping'. Undefined until + * provideBookkeepingConfig sets it, which every request needs. + */ + baseUrl: string | undefined, + /** + * The paths of the routes below the baseUrl. + */ + paths: BookkeepingPaths, + /** + * How many entries a page of the journal has. + */ + pageSize: number, + /** + * How the days of the books are shown, as the options of Intl.DateTimeFormat in the LOCALE_ID of the app. By + * default like the date inputs of ui write them: '12/31/2026' in 'en-US' or '31.12.2026' in 'de'. + */ + dateFormat: Intl.DateTimeFormatOptions, + /** + * The level of the headings inside the views, like the sections of a fiscal year. Their sections are headed one + * level below. + */ + headingLevel: HeadingLevel, + /** + * The size classes a company can have had before the first fiscal year of its books, by the value the api takes, + * with what the option of each is called. Replaced as a whole by provideBookkeepingConfig. + */ + sizeClasses: Record, + /** + * The conformances of the api, the rules of a law the books are held to, by their name, with what they are called, + * like `{ 'ug-legal-reserve': 'Legal reserve of a UG' }`. The closing shows who proposes an entry by it, or by + * the name the config doesn't call anything. + */ + conformances: Record, + /** + * Whether the user may reopen a closed fiscal year, like with `bookkeeping.reopen-fiscal-year`, which the fiscal + * years show the button by while their `canReopen` isn't set. False by default. + */ + canReopen: boolean, + /** + * The texts of the views. + */ + labels: BookkeepingLabels, + /** + * The question before posting an entry proposed before closing. + */ + postProposalConfirmDialogData: ConfirmDialogData, + /** + * The question before closing a fiscal year. + */ + closeConfirmDialogData: ConfirmDialogData +}; diff --git a/projects/ngx-bookkeeping/api/bookkeeping-config.provider.spec.ts b/projects/ngx-bookkeeping/api/bookkeeping-config.provider.spec.ts new file mode 100644 index 0000000..22b5ead --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-config.provider.spec.ts @@ -0,0 +1,89 @@ +import { Injector } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { describe, expect, test } from 'vitest'; + +import { BookkeepingConfig } from './bookkeeping-config.model'; +import { BOOKKEEPING_CONFIG, provideBookkeepingConfig } from './bookkeeping-config.provider'; + +describe('provideBookkeepingConfig', () => { + test('has defaults for everything but the baseUrl, and lets no one reopen a fiscal year', () => { + const config: BookkeepingConfig = TestBed.inject(BOOKKEEPING_CONFIG); + + expect(config.baseUrl).toBeUndefined(); + expect(config.canReopen).toBe(false); + expect([config.pageSize, config.headingLevel]).toEqual([20, 2]); + expect([config.paths.fiscalYears, config.paths.reopening, config.paths.balanceSheet]).toEqual(['fiscal-years', 'reopening', 'reports/balance-sheet']); + expect([config.labels.common.fiscalYear, config.labels.fiscalYears.reopen]).toEqual(['Fiscal year', 'Reopen fiscal year']); + expect(config.closeConfirmDialogData.confirmButtonLabel).toBe('Close fiscal year'); + }); + + test('changes only what it is given, and keeps the defaults of the rest', () => { + TestBed.configureTestingModule({ + providers: [ + provideBookkeepingConfig({ + baseUrl: '/api/bookkeeping', + canReopen: true, + paths: { entries: 'buchungen' }, + labels: { journal: { reverse: 'Stornieren' } }, + closeConfirmDialogData: { title: 'Abschließen?' } + }) + ] + }); + + const config: BookkeepingConfig = TestBed.inject(BOOKKEEPING_CONFIG); + + expect([config.baseUrl, config.canReopen, config.pageSize]).toEqual(['/api/bookkeeping', true, 20]); + expect([config.paths.entries, config.paths.accounts]).toEqual(['buchungen', 'accounts']); + expect([config.labels.journal.reverse, config.labels.journal.reversal]).toEqual(['Stornieren', 'Reversal']); + expect(config.labels.ledger.openingBalance).toBe('Opening balance'); + expect([config.closeConfirmDialogData.title, config.closeConfirmDialogData.confirmButtonLabel]).toEqual(['Abschließen?', 'Close fiscal year']); + expect(config.postProposalConfirmDialogData.title).toBe('Post this entry?'); + }); + + test('takes what it leaves out from the parent injector, and merges paths, labels and dialogs part by part', () => { + TestBed.configureTestingModule({ + providers: [ + provideBookkeepingConfig({ + baseUrl: '/api/bookkeeping', + canReopen: true, + paths: { entries: 'buchungen' }, + labels: { fiscalYears: { reopen: 'Wieder öffnen' } }, + postProposalConfirmDialogData: { title: 'Buchen?' } + }) + ] + }); + const child: Injector = Injector.create({ + providers: [ + provideBookkeepingConfig({ + pageSize: 50, + paths: { accounts: 'konten' }, + labels: { fiscalYears: { close: 'Abschließen' } }, + postProposalConfirmDialogData: { confirmButtonLabel: 'Buchen' } + }) + ], + parent: TestBed.inject(Injector) + }); + + const config: BookkeepingConfig = child.get(BOOKKEEPING_CONFIG); + + expect([config.baseUrl, config.canReopen, config.pageSize]).toEqual(['/api/bookkeeping', true, 50]); + expect([config.paths.entries, config.paths.accounts, config.paths.closing]).toEqual(['buchungen', 'konten', 'closing']); + expect([config.labels.fiscalYears.reopen, config.labels.fiscalYears.close, config.labels.fiscalYears.open]) + .toEqual(['Wieder öffnen', 'Abschließen', 'Open']); + expect([config.postProposalConfirmDialogData.title, config.postProposalConfirmDialogData.confirmButtonLabel]) + .toEqual(['Buchen?', 'Buchen']); + // the parent keeps its own + const parent: BookkeepingConfig = TestBed.inject(BOOKKEEPING_CONFIG); + expect([parent.pageSize, parent.paths.accounts, parent.labels.fiscalYears.close]).toEqual([20, 'accounts', 'Close fiscal year']); + }); + + test('keeps the baseUrl of the parent when a child changes something else', () => { + TestBed.configureTestingModule({ providers: [provideBookkeepingConfig({ baseUrl: '/api/bookkeeping' })] }); + const child: Injector = Injector.create({ + providers: [provideBookkeepingConfig({ baseUrl: undefined, canReopen: true })], + parent: TestBed.inject(Injector) + }); + + expect(child.get(BOOKKEEPING_CONFIG).baseUrl).toBe('/api/bookkeeping'); + }); +}); diff --git a/projects/ngx-bookkeeping/api/bookkeeping-config.provider.ts b/projects/ngx-bookkeeping/api/bookkeeping-config.provider.ts new file mode 100644 index 0000000..2576856 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-config.provider.ts @@ -0,0 +1,284 @@ +import { inject, InjectionToken, Provider } from '@angular/core'; + +import { BookkeepingConfigChanges } from './bookkeeping-config-changes.model'; +import { BookkeepingConfig } from './bookkeeping-config.model'; +import { BookkeepingLabels } from './bookkeeping-labels.model'; +import { BookkeepingLabelsChanges } from './bookkeeping-labels-changes.model'; + +/** + * The texts of the views when nothing changes them, as $localize, which an app translates like its own. + * @returns The default labels. + */ +function getDefaultBookkeepingLabels(): BookkeepingLabels { + return { + common: { + fiscalYear: $localize`:@@ngx-bookkeeping.api.common.fiscalYear:Fiscal year`, + period: $localize`:@@ngx-bookkeeping.api.common.period:Period`, + periodStart: $localize`:@@ngx-bookkeeping.api.common.periodStart:From`, + periodEnd: $localize`:@@ngx-bookkeeping.api.common.periodEnd:Until`, + periodHint: $localize`:@@ngx-bookkeeping.api.common.periodHint:The whole fiscal year when empty`, + account: $localize`:@@ngx-bookkeeping.api.common.account:Account`, + debit: $localize`:@@ngx-bookkeeping.api.common.debit:Debit`, + credit: $localize`:@@ngx-bookkeeping.api.common.credit:Credit`, + balance: $localize`:@@ngx-bookkeeping.api.common.balance:Balance`, + debitSide: $localize`:@@ngx-bookkeeping.api.common.debitSide:Dr`, + creditSide: $localize`:@@ngx-bookkeeping.api.common.creditSide:Cr`, + total: $localize`:@@ngx-bookkeeping.api.common.total:Total`, + postingDate: $localize`:@@ngx-bookkeeping.api.common.postingDate:Posting date`, + documentDate: $localize`:@@ngx-bookkeeping.api.common.documentDate:Document date`, + documentReference: $localize`:@@ngx-bookkeeping.api.common.documentReference:Document number`, + text: $localize`:@@ngx-bookkeeping.api.common.text:Text`, + entry: $localize`:@@ngx-bookkeeping.api.common.entry:Entry`, + entryNumber: sequence => $localize`:@@ngx-bookkeeping.api.common.entryNumber:Entry ${sequence}:sequence:`, + downloadPdf: $localize`:@@ngx-bookkeeping.api.common.downloadPdf:Download as PDF`, + downloadFailed: $localize`:@@ngx-bookkeeping.api.common.downloadFailed:The file couldn't be downloaded. Please try again.`, + loading: $localize`:@@ngx-bookkeeping.api.common.loading:Loading the books`, + loadingFailed: $localize`:@@ngx-bookkeeping.api.common.loadingFailed:The books couldn't be loaded.`, + noFiscalYears: $localize`:@@ngx-bookkeeping.api.common.noFiscalYears:The books have no fiscal year yet.`, + requestFailed: $localize`:@@ngx-bookkeeping.api.common.requestFailed:The request couldn't be sent. Please try again.`, + cancel: $localize`:@@ngx-bookkeeping.api.common.cancel:Cancel` + }, + journal: { + allAccounts: $localize`:@@ngx-bookkeeping.api.journal.allAccounts:All accounts`, + noEntries: $localize`:@@ngx-bookkeeping.api.journal.noEntries:No entry matches the filters.`, + pages: $localize`:@@ngx-bookkeeping.api.journal.pages:Pages of the journal`, + lines: sequence => $localize`:@@ngx-bookkeeping.api.journal.lines:Lines of entry ${sequence}:sequence:`, + totalDebit: $localize`:@@ngx-bookkeeping.api.journal.totalDebit:Debits of the period`, + totalCredit: $localize`:@@ngx-bookkeeping.api.journal.totalCredit:Credits of the period`, + reverse: $localize`:@@ngx-bookkeeping.api.journal.reverse:Reverse`, + reverseEntry: sequence => $localize`:@@ngx-bookkeeping.api.journal.reverseEntry:Reverse entry ${sequence}:sequence:`, + reversalOf: sequence => $localize`:@@ngx-bookkeeping.api.journal.reversalOf:Reverses entry ${sequence}:sequence:`, + reversal: $localize`:@@ngx-bookkeeping.api.journal.reversal:Reversal`, + reversedBy: sequence => $localize`:@@ngx-bookkeeping.api.journal.reversedBy:Reversed by entry ${sequence}:sequence:`, + reversedEntry: $localize`:@@ngx-bookkeeping.api.journal.reversedEntry:Reversed`, + reversed: (sequence, reversal) => { + return $localize`:@@ngx-bookkeeping.api.journal.reversed:Entry ${sequence}:sequence: was reversed by entry ${reversal}:reversal:.`; + }, + reversalTitle: sequence => $localize`:@@ngx-bookkeeping.api.journal.reversalTitle:Reverse entry ${sequence}:sequence:?`, + reversalText: $localize`:@@ngx-bookkeeping.api.journal.reversalText:The reversal posts the lines of the entry with debit and credit swapped. The entry itself stays in the journal as it is. This can't be undone.`, + reversalPostingDate: $localize`:@@ngx-bookkeeping.api.journal.reversalPostingDate:Posting date of the reversal`, + reversalPostingDateHint: $localize`:@@ngx-bookkeeping.api.journal.reversalPostingDateHint:A day of an open fiscal year`, + reversalReason: $localize`:@@ngx-bookkeeping.api.journal.reversalReason:Reason`, + reversalReasonHint: $localize`:@@ngx-bookkeeping.api.journal.reversalReasonHint:The text of the reversal, like "Booked on the wrong account"`, + confirmReversal: $localize`:@@ngx-bookkeeping.api.journal.confirmReversal:Reverse` + }, + entryForm: { + documentReferenceHint: $localize`:@@ngx-bookkeeping.api.entryForm.documentReferenceHint:Like the number of the invoice`, + textHint: $localize`:@@ngx-bookkeeping.api.entryForm.textHint:What was booked, like "Rent March"`, + lines: $localize`:@@ngx-bookkeeping.api.entryForm.lines:Lines`, + line: index => $localize`:@@ngx-bookkeeping.api.entryForm.line:Line ${index}:index:`, + addLine: $localize`:@@ngx-bookkeeping.api.entryForm.addLine:Add a line`, + removeLine: $localize`:@@ngx-bookkeeping.api.entryForm.removeLine:Remove`, + removeLineOf: index => $localize`:@@ngx-bookkeeping.api.entryForm.removeLineOf:Remove line ${index}:index:`, + totalDebit: $localize`:@@ngx-bookkeeping.api.entryForm.totalDebit:Debits`, + totalCredit: $localize`:@@ngx-bookkeeping.api.entryForm.totalCredit:Credits`, + difference: $localize`:@@ngx-bookkeeping.api.entryForm.difference:Difference`, + unbalanced: difference => { + return $localize`:@@ngx-bookkeeping.api.entryForm.unbalanced:The debits and the credits differ by ${difference}:difference:. An entry is posted once both are equal.`; + }, + amountMissing: $localize`:@@ngx-bookkeeping.api.entryForm.amountMissing:Enter a debit or a credit.`, + amountTwice: $localize`:@@ngx-bookkeeping.api.entryForm.amountTwice:Enter either a debit or a credit, not both.`, + post: $localize`:@@ngx-bookkeeping.api.entryForm.post:Post entry`, + posted: sequence => $localize`:@@ngx-bookkeeping.api.entryForm.posted:Entry ${sequence}:sequence: was posted.` + }, + ledger: { + chooseAccount: $localize`:@@ngx-bookkeeping.api.ledger.chooseAccount:Choose an account to see what was booked on it.`, + table: account => $localize`:@@ngx-bookkeeping.api.ledger.table:Ledger of ${account}:account:`, + openingBalance: $localize`:@@ngx-bookkeeping.api.ledger.openingBalance:Opening balance`, + closingBalance: $localize`:@@ngx-bookkeeping.api.ledger.closingBalance:Closing balance`, + noLines: $localize`:@@ngx-bookkeeping.api.ledger.noLines:Nothing was booked on the account in the period.` + }, + trialBalance: { + until: $localize`:@@ngx-bookkeeping.api.trialBalance.until:Until`, + untilHint: $localize`:@@ngx-bookkeeping.api.trialBalance.untilHint:The last day whose entries count, the end of the fiscal year when empty`, + table: (fiscalYear, until) => { + return $localize`:@@ngx-bookkeeping.api.trialBalance.table:Trial balance of ${fiscalYear}:fiscalYear: until ${until}:until:`; + }, + number: $localize`:@@ngx-bookkeeping.api.trialBalance.number:No.`, + debitBalance: $localize`:@@ngx-bookkeeping.api.trialBalance.debitBalance:Debit balance`, + creditBalance: $localize`:@@ngx-bookkeeping.api.trialBalance.creditBalance:Credit balance`, + noRows: $localize`:@@ngx-bookkeeping.api.trialBalance.noRows:Nothing was booked in the fiscal year until then.` + }, + statements: { + form: $localize`:@@ngx-bookkeeping.api.statements.form:Form`, + applyingForm: form => $localize`:@@ngx-bookkeeping.api.statements.applyingForm:${form}:form: (the form of the fiscal year)`, + position: $localize`:@@ngx-bookkeeping.api.statements.position:Position`, + result: $localize`:@@ngx-bookkeeping.api.statements.result:Result of the fiscal year`, + final: $localize`:@@ngx-bookkeeping.api.statements.final:Final`, + finalNote: $localize`:@@ngx-bookkeeping.api.statements.finalNote:The fiscal year is closed. This is the statement archived at its closing.`, + preliminary: $localize`:@@ngx-bookkeeping.api.statements.preliminary:Preliminary`, + preliminaryNote: $localize`:@@ngx-bookkeeping.api.statements.preliminaryNote:The fiscal year is open, so its figures can still change.`, + unmapped: $localize`:@@ngx-bookkeeping.api.statements.unmapped:Accounts without a position`, + unmappedText: $localize`:@@ngx-bookkeeping.api.statements.unmappedText:These accounts have a balance but no position in this statement, so none of its positions holds them. Map each of them to a position.` + }, + fiscalYears: { + fiscalYears: $localize`:@@ngx-bookkeeping.api.fiscalYears.fiscalYears:Fiscal years`, + start: $localize`:@@ngx-bookkeeping.api.fiscalYears.start:Start`, + end: $localize`:@@ngx-bookkeeping.api.fiscalYears.end:End`, + status: $localize`:@@ngx-bookkeeping.api.fiscalYears.status:Status`, + open: $localize`:@@ngx-bookkeeping.api.fiscalYears.open:Open`, + closedOn: day => $localize`:@@ngx-bookkeeping.api.fiscalYears.closedOn:Closed on ${day}:day:`, + fiscalYear: fiscalYear => $localize`:@@ngx-bookkeeping.api.fiscalYears.fiscalYear:Fiscal year ${fiscalYear}:fiscalYear:`, + add: $localize`:@@ngx-bookkeeping.api.fiscalYears.add:Add a fiscal year`, + firstStartHint: $localize`:@@ngx-bookkeeping.api.fiscalYears.firstStartHint:The first day of the books`, + nextStart: day => $localize`:@@ngx-bookkeeping.api.fiscalYears.nextStart:It starts on ${day}:day:, the day after the last fiscal year.`, + firstEndHint: $localize`:@@ngx-bookkeeping.api.fiscalYears.firstEndHint:The end of its calendar year when empty, or an earlier day for a short first year`, + nextEndHint: day => $localize`:@@ngx-bookkeeping.api.fiscalYears.nextEndHint:It ends on ${day}:day:, a year after its start, when empty`, + added: fiscalYear => $localize`:@@ngx-bookkeeping.api.fiscalYears.added:The fiscal year ${fiscalYear}:fiscalYear: was added.`, + details: $localize`:@@ngx-bookkeeping.api.fiscalYears.details:For the statements`, + averageEmployees: $localize`:@@ngx-bookkeeping.api.fiscalYears.averageEmployees:Average number of employees`, + averageEmployeesHint: $localize`:@@ngx-bookkeeping.api.fiscalYears.averageEmployeesHint:During the fiscal year, like 2.5, for the size class of a corporation`, + balanceSheetNote: $localize`:@@ngx-bookkeeping.api.fiscalYears.balanceSheetNote:Note below the balance sheet`, + balanceSheetNoteHint: $localize`:@@ngx-bookkeeping.api.fiscalYears.balanceSheetNoteHint:Stated below the balance sheet where the fiscal year states one, like that of a micro corporation`, + before: $localize`:@@ngx-bookkeeping.api.fiscalYears.before:Before this fiscal year`, + beforeHint: $localize`:@@ngx-bookkeeping.api.fiscalYears.beforeHint:What the company was on the balance sheet date before the first fiscal year of the books`, + founded: $localize`:@@ngx-bookkeeping.api.fiscalYears.founded:Founded in this fiscal year`, + save: $localize`:@@ngx-bookkeeping.api.fiscalYears.save:Save`, + saved: $localize`:@@ngx-bookkeeping.api.fiscalYears.saved:The fiscal year was saved.`, + closedNote: day => $localize`:@@ngx-bookkeeping.api.fiscalYears.closedNote:The fiscal year was closed on ${day}:day:. Nothing can be posted into it or changed unless it is reopened.`, + closing: $localize`:@@ngx-bookkeeping.api.fiscalYears.closing:Closing`, + proposalsText: $localize`:@@ngx-bookkeeping.api.fiscalYears.proposalsText:The rules of the law the books are held to propose these entries before the fiscal year is closed. Post each of them, then close the year.`, + noProposals: $localize`:@@ngx-bookkeeping.api.fiscalYears.noProposals:No entry is proposed before closing.`, + proposalsFailed: $localize`:@@ngx-bookkeeping.api.fiscalYears.proposalsFailed:The entries proposed before closing couldn't be loaded.`, + proposedBy: conformance => $localize`:@@ngx-bookkeeping.api.fiscalYears.proposedBy:Proposed by ${conformance}:conformance:`, + proposalLines: text => $localize`:@@ngx-bookkeeping.api.fiscalYears.proposalLines:Lines of "${text}:text:"`, + postProposal: $localize`:@@ngx-bookkeeping.api.fiscalYears.postProposal:Post`, + postProposalOf: text => $localize`:@@ngx-bookkeeping.api.fiscalYears.postProposalOf:Post "${text}:text:"`, + proposalPosted: sequence => $localize`:@@ngx-bookkeeping.api.fiscalYears.proposalPosted:The proposed entry was posted as entry ${sequence}:sequence:.`, + resultAccount: $localize`:@@ngx-bookkeeping.api.fiscalYears.resultAccount:Result account`, + resultAccountHint: $localize`:@@ngx-bookkeeping.api.fiscalYears.resultAccountHint:The equity account the result of the year is carried into`, + close: $localize`:@@ngx-bookkeeping.api.fiscalYears.close:Close fiscal year`, + closedResult: (fiscalYear, nextFiscalYear) => { + return $localize`:@@ngx-bookkeeping.api.fiscalYears.closedResult:The fiscal year ${fiscalYear}:fiscalYear: was closed, and the fiscal year ${nextFiscalYear}:nextFiscalYear: opened with its balances.`; + }, + reopen: $localize`:@@ngx-bookkeeping.api.fiscalYears.reopen:Reopen fiscal year`, + reopenTitle: fiscalYear => $localize`:@@ngx-bookkeeping.api.fiscalYears.reopenTitle:Reopen the fiscal year ${fiscalYear}:fiscalYear:?`, + reopenText: $localize`:@@ngx-bookkeeping.api.fiscalYears.reopenText:Reopening reverses its closing: the fiscal year is open again, you can post corrections into it, and then close it again. The opening balances of the next fiscal year are reversed as well, and posted again when you close it.`, + reopenKeptText: $localize`:@@ngx-bookkeeping.api.fiscalYears.reopenKeptText:Nothing is deleted: the entries of the closing stay in the journal next to their reversals, and the statements archived at the closing stay archived. You may be asked for your second factor.`, + reopenReason: $localize`:@@ngx-bookkeeping.api.fiscalYears.reopenReason:Reason`, + reopenReasonHint: $localize`:@@ngx-bookkeeping.api.fiscalYears.reopenReasonHint:Why the fiscal year is reopened, like the error to correct. It is the text of the reversing entries.`, + reopenFiledNote: $localize`:@@ngx-bookkeeping.api.fiscalYears.reopenFiledNote:The E-Bilanz of this fiscal year is filed with the tax administration. The year may only be reopened to correct it: once it is closed again, prepare a correction of the E-Bilanz and file it again.`, + forCorrection: $localize`:@@ngx-bookkeeping.api.fiscalYears.forCorrection:This reopening is to correct the filed E-Bilanz`, + forCorrectionUnknown: $localize`:@@ngx-bookkeeping.api.fiscalYears.forCorrectionUnknown:The accounts of this year are filed already, like an E-Bilanz, and this reopening is to correct them`, + reopened: fiscalYear => $localize`:@@ngx-bookkeeping.api.fiscalYears.reopened:The fiscal year ${fiscalYear}:fiscalYear: was reopened. Post the corrections, then close it again.`, + export: $localize`:@@ngx-bookkeeping.api.fiscalYears.export:Export for a tax audit`, + exportText: $localize`:@@ngx-bookkeeping.api.fiscalYears.exportText:A zip archive of the accounts and the entries of the fiscal year, in the format the software of a tax audit reads.`, + withDocuments: $localize`:@@ngx-bookkeeping.api.fiscalYears.withDocuments:With the documents`, + withDocumentsHint: $localize`:@@ngx-bookkeeping.api.fiscalYears.withDocumentsHint:The invoices, receipts, bank statements and archived statements behind the entries`, + exportOpenHint: $localize`:@@ngx-bookkeeping.api.fiscalYears.exportOpenHint:The fiscal year is open, so entries posted into it later are not in the export. Export it once it is closed.`, + downloadExport: $localize`:@@ngx-bookkeeping.api.fiscalYears.downloadExport:Download the export`, + exporting: $localize`:@@ngx-bookkeeping.api.fiscalYears.exporting:Downloading the export` + } + }; +} + +/** + * The values of the books when nothing changes them. Their texts are $localize, which an app translates like its own, + * and resolved once the config is injected, so translations an app loads at runtime apply as well. + * @returns The default config. + */ +function getDefaultBookkeepingConfig(): BookkeepingConfig { + return { + baseUrl: undefined, + paths: { + settings: 'settings', + accounts: 'accounts', + fiscalYears: 'fiscal-years', + entries: 'entries', + reversal: 'reversal', + closingProposals: 'closing-proposals', + closing: 'closing', + reopening: 'reopening', + export: 'export', + statementForms: 'statement-forms', + journal: 'reports/journal', + ledger: 'reports/ledger', + trialBalance: 'reports/trial-balance', + balanceSheet: 'reports/balance-sheet', + incomeStatement: 'reports/income-statement' + }, + pageSize: 20, + // the parts of the date inputs of ui, so a day reads the same in a list as in an input. + dateFormat: { year: 'numeric', month: '2-digit', day: '2-digit' }, + headingLevel: 2, + // the classes of § 267 and § 267a HGB, which the size of a corporation is told by. + sizeClasses: { + MICRO: $localize`:@@ngx-bookkeeping.api.sizeClasses.micro:Existed before as a micro corporation`, + SMALL: $localize`:@@ngx-bookkeeping.api.sizeClasses.small:Existed before as a small corporation`, + MEDIUM: $localize`:@@ngx-bookkeeping.api.sizeClasses.medium:Existed before as a medium-sized corporation`, + LARGE: $localize`:@@ngx-bookkeeping.api.sizeClasses.large:Existed before as a large corporation` + }, + conformances: {}, + canReopen: false, + labels: getDefaultBookkeepingLabels(), + postProposalConfirmDialogData: { + title: $localize`:@@ngx-bookkeeping.api.postProposalConfirmDialogData.title:Post this entry?`, + paragraphs: [$localize`:@@ngx-bookkeeping.api.postProposalConfirmDialogData.paragraphs:It is posted into the books as it is proposed. A posted entry is only corrected by reversing it.`], + confirmButtonLabel: $localize`:@@ngx-bookkeeping.api.postProposalConfirmDialogData.confirmButtonLabel:Post`, + cancelButtonLabel: $localize`:@@ngx-bookkeeping.api.postProposalConfirmDialogData.cancelButtonLabel:Cancel`, + confirmButtonColor: 'primary' + }, + closeConfirmDialogData: { + title: $localize`:@@ngx-bookkeeping.api.closeConfirmDialogData.title:Close this fiscal year?`, + paragraphs: [ + $localize`:@@ngx-bookkeeping.api.closeConfirmDialogData.paragraphs.postings:Nothing can be posted into it afterwards. Its balance sheet and income statement are archived as they are, and the next fiscal year opens with its balances.`, + $localize`:@@ngx-bookkeeping.api.closeConfirmDialogData.paragraphs.final:This can't be undone.` + ], + confirmButtonLabel: $localize`:@@ngx-bookkeeping.api.closeConfirmDialogData.confirmButtonLabel:Close fiscal year`, + cancelButtonLabel: $localize`:@@ngx-bookkeeping.api.closeConfirmDialogData.cancelButtonLabel:Cancel`, + confirmButtonColor: 'error' + } + }; +} + +/** + * Merges the labels to change into the ones of the parent, view by view. + * @param parent - The labels of the parent injector. + * @param changes - The labels to change. + * @returns The merged labels. + */ +function mergeLabels(parent: BookkeepingLabels, changes: BookkeepingLabelsChanges | undefined): BookkeepingLabels { + return { + common: { ...parent.common, ...changes?.common }, + journal: { ...parent.journal, ...changes?.journal }, + entryForm: { ...parent.entryForm, ...changes?.entryForm }, + ledger: { ...parent.ledger, ...changes?.ledger }, + trialBalance: { ...parent.trialBalance, ...changes?.trialBalance }, + statements: { ...parent.statements, ...changes?.statements }, + fiscalYears: { ...parent.fiscalYears, ...changes?.fiscalYears } + }; +} + +/** + * Where the books are, and the values their views use, below this injector. Change them with provideBookkeepingConfig. + */ +export const BOOKKEEPING_CONFIG: InjectionToken = new InjectionToken( + 'BOOKKEEPING_CONFIG', + { providedIn: 'root', factory: () => getDefaultBookkeepingConfig() } +); + +/** + * Sets where the books are, `{ baseUrl }`, and changes the values their views use, like the labels to translate them. + * Provide it in the application config for the whole app, or in a component or route for only that part of it. Values + * you leave out are taken from the parent injector, including single paths, labels and texts of the dialogs. + * @param config - The values to change. + * @returns The provider for BOOKKEEPING_CONFIG. + */ +export function provideBookkeepingConfig(config: BookkeepingConfigChanges): Provider { + return { + provide: BOOKKEEPING_CONFIG, + useFactory: (): BookkeepingConfig => { + const parent: BookkeepingConfig = inject(BOOKKEEPING_CONFIG, { skipSelf: true, optional: true }) + ?? getDefaultBookkeepingConfig(); + return { + ...parent, + ...config, + baseUrl: config.baseUrl ?? parent.baseUrl, + paths: { ...parent.paths, ...config.paths }, + labels: mergeLabels(parent.labels, config.labels), + postProposalConfirmDialogData: { ...parent.postProposalConfirmDialogData, ...config.postProposalConfirmDialogData }, + closeConfirmDialogData: { ...parent.closeConfirmDialogData, ...config.closeConfirmDialogData } + }; + } + }; +} diff --git a/projects/ngx-bookkeeping/api/bookkeeping-day.utilities.spec.ts b/projects/ngx-bookkeeping/api/bookkeeping-day.utilities.spec.ts new file mode 100644 index 0000000..23ef5eb --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-day.utilities.spec.ts @@ -0,0 +1,36 @@ +import { describe, expect, test } from 'vitest'; + +import { BookkeepingDayUtilities } from './bookkeeping-day.utilities'; + +const DAY_FORMAT: Intl.DateTimeFormatOptions = { year: 'numeric', month: '2-digit', day: '2-digit' }; + +describe('BookkeepingDayUtilities', () => { + test('keeps the day of a date input as the same day at midnight UTC, and back', () => { + const day: Date = BookkeepingDayUtilities.resolveDay(new Date(2026, 2, 31, 23, 30)); + + expect(day.toISOString()).toBe('2026-03-31T00:00:00.000Z'); + expect(BookkeepingDayUtilities.resolveLocalDate(day)).toEqual(new Date(2026, 2, 31)); + expect(BookkeepingDayUtilities.getQueryValue(day)).toBe('2026-03-31'); + expect(BookkeepingDayUtilities.resolveNextDay(day).toISOString()).toBe('2026-04-01T00:00:00.000Z'); + }); + + test('writes a day in the language of the app, the same day in every time zone', () => { + const day: Date = new Date('2026-03-31T00:00:00.000Z'); + + expect(BookkeepingDayUtilities.format(day, DAY_FORMAT, 'en-US')).toBe('03/31/2026'); + expect(BookkeepingDayUtilities.format(day, DAY_FORMAT, 'de')).toBe('31.03.2026'); + }); + + test('writes a moment with its time where the user is', () => { + // a moment of the local day, which a day in UTC would write as the day before or after in some time zones + const moment: Date = new Date(2026, 2, 31, 14, 30); + + expect(BookkeepingDayUtilities.formatMoment(moment, DAY_FORMAT, 'en-US')).toBe('03/31/2026, 02:30 PM'); + expect(BookkeepingDayUtilities.formatMoment(moment, DAY_FORMAT, 'de')).toBe('31.03.2026, 14:30'); + }); + + test('ends a year from a day the day before the same day a year later', () => { + expect(BookkeepingDayUtilities.resolveYearEnd(new Date('2027-01-01T00:00:00.000Z')).toISOString()).toBe('2027-12-31T00:00:00.000Z'); + expect(BookkeepingDayUtilities.resolveYearEnd(new Date('2026-07-01T00:00:00.000Z')).toISOString()).toBe('2027-06-30T00:00:00.000Z'); + }); +}); diff --git a/projects/ngx-bookkeeping/api/bookkeeping-day.utilities.ts b/projects/ngx-bookkeeping/api/bookkeeping-day.utilities.ts new file mode 100644 index 0000000..b0f8c9a --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-day.utilities.ts @@ -0,0 +1,84 @@ +/** + * The days of the books. The api holds a day as its midnight UTC, like the start of a fiscal year or the posting day of + * an entry, while the date inputs of ui hold the midnight of the day in the time zone of the browser. These convert + * between both, so a day stays the same day wherever the browser is. + */ +export abstract class BookkeepingDayUtilities { + /** + * Resolves the day of the books of a date of an input. + * @param date - The date, at any time of its day in the time zone of the browser. + * @returns The same day at midnight UTC, as the api takes it. + */ + static resolveDay(date: Date): Date { + return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())); + } + + /** + * Resolves the date of an input of a day of the books. + * @param day - The day, at midnight UTC. + * @returns The same day at midnight in the time zone of the browser, as the date inputs of ui hold it. + */ + static resolveLocalDate(day: Date): Date { + return new Date(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate()); + } + + /** + * Resolves the day after a day of the books. + * @param day - The day, at midnight UTC. + * @returns The next day, at midnight UTC. + */ + static resolveNextDay(day: Date): Date { + return new Date(Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate() + 1)); + } + + /** + * Resolves the last day of a year from a day: the day before the same day a year later, like the end of a fiscal + * year after another that names none. + * @param start - The first day, at midnight UTC. + * @returns The last day, at midnight UTC, like 2027-12-31 for 2027-01-01. + */ + static resolveYearEnd(start: Date): Date { + return new Date(Date.UTC(start.getUTCFullYear() + 1, start.getUTCMonth(), start.getUTCDate() - 1)); + } + + /** + * Resolves today as a day of the books. + * @returns Today in the time zone of the browser, at midnight UTC. + */ + static resolveToday(): Date { + return this.resolveDay(new Date()); + } + + /** + * Gets a day as the api takes it in a query, like `2026-03-31`. + * @param day - The day, at midnight UTC. + * @returns The day in ISO format. + */ + static getQueryValue(day: Date): string { + return day.toISOString().slice(0, 10); + } + + /** + * Formats a day of the books in a language, the same day in every time zone. + * @param day - The day, at midnight UTC. + * @param format - The options of Intl.DateTimeFormat, like `{ year: 'numeric', month: '2-digit', day: '2-digit' }`. + * @param locale - The locale, like the LOCALE_ID of the app. + * @returns The formatted day, like '03/31/2026' in 'en-US' or '31.03.2026' in 'de'. + */ + static format(day: Date, format: Intl.DateTimeFormatOptions, locale: string): string { + return new Intl.DateTimeFormat(locale, { ...format, timeZone: 'UTC' }).format(day); + } + + /** + * Formats a moment, like when a record was made, in a language: its day in the format of the days and its time, in + * the time zone of the browser. + * @param moment - The moment. + * @param format - The options of Intl.DateTimeFormat of the days, like `{ year: 'numeric', month: '2-digit', day: '2-digit' }`. + * @param locale - The locale, like the LOCALE_ID of the app. + * @returns The formatted moment, like '03/31/2026, 02:30 PM' in 'en-US' or '31.03.2026, 14:30' in 'de'. + */ + // a moment is no day of the books, so it shows where the user is, not in UTC. + static formatMoment(moment: Date, format: Intl.DateTimeFormatOptions, locale: string): string { + return new Intl.DateTimeFormat(locale, { ...format, hour: '2-digit', minute: '2-digit' }).format(moment); + } +} diff --git a/projects/ngx-bookkeeping/api/bookkeeping-entry-form-labels.model.ts b/projects/ngx-bookkeeping/api/bookkeeping-entry-form-labels.model.ts new file mode 100644 index 0000000..e0b36af --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-entry-form-labels.model.ts @@ -0,0 +1,65 @@ +/** + * The texts of the form that posts an entry, to translate them. + */ +export type BookkeepingEntryFormLabels = { + /** + * The hint below the number of the document. + */ + documentReferenceHint: string, + /** + * The hint below the text. + */ + textHint: string, + /** + * The heading of the lines. + */ + lines: string, + /** + * What screen readers call the group of the inputs of a line, counted from 1. + */ + line: (index: number) => string, + /** + * The button that adds a line. + */ + addLine: string, + /** + * The button that removes a line. + */ + removeLine: string, + /** + * What screen readers call the button that removes a line, counted from 1. + */ + removeLineOf: (index: number) => string, + /** + * The sum of the debits of the lines. + */ + totalDebit: string, + /** + * The sum of the credits of the lines. + */ + totalCredit: string, + /** + * The difference of both sums. + */ + difference: string, + /** + * The error of an entry whose debits and credits differ, with the difference formatted. + */ + unbalanced: (difference: string) => string, + /** + * The error of a line without an amount. + */ + amountMissing: string, + /** + * The error of a line with a debit and a credit. + */ + amountTwice: string, + /** + * The button that posts the entry. + */ + post: string, + /** + * What the form says once it posted an entry. + */ + posted: (sequence: number) => string +}; diff --git a/projects/ngx-bookkeeping/api/bookkeeping-file.model.ts b/projects/ngx-bookkeeping/api/bookkeeping-file.model.ts new file mode 100644 index 0000000..f6fa11d --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-file.model.ts @@ -0,0 +1,13 @@ +/** + * A file the api answered, like the pdf of a report or the export of a fiscal year, to save in the browser. + */ +export type BookkeepingFile = { + /** + * The name to save it under, the one the api gives it, like 'balance-sheet-2026.pdf'. + */ + name: string, + /** + * What the file holds. + */ + content: Blob +}; diff --git a/projects/ngx-bookkeeping/api/bookkeeping-file.utilities.spec.ts b/projects/ngx-bookkeeping/api/bookkeeping-file.utilities.spec.ts new file mode 100644 index 0000000..21908d1 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-file.utilities.spec.ts @@ -0,0 +1,12 @@ +import { describe, expect, test } from 'vitest'; + +import { BookkeepingFileUtilities } from './bookkeeping-file.utilities'; + +describe('BookkeepingFileUtilities', () => { + test('finds the name of a file in its content disposition, also one beyond ASCII', () => { + expect(BookkeepingFileUtilities.findFileName('attachment; filename="journal.pdf"')).toBe('journal.pdf'); + expect(BookkeepingFileUtilities.findFileName('attachment; filename="_-2026.zip"; filename*=UTF-8\'\'%C3%A4-2026.zip')).toBe('ä-2026.zip'); + // eslint-disable-next-line unicorn/no-null -- a response without the header answers null + expect(BookkeepingFileUtilities.findFileName(null)).toBeUndefined(); + }); +}); diff --git a/projects/ngx-bookkeeping/api/bookkeeping-file.utilities.ts b/projects/ngx-bookkeeping/api/bookkeeping-file.utilities.ts new file mode 100644 index 0000000..3ae0431 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-file.utilities.ts @@ -0,0 +1,39 @@ +import { BookkeepingFile } from './bookkeeping-file.model'; + +// `filename*=UTF-8''` of RFC 6266 first, which holds names beyond ASCII, then the plain `filename=""`. +const ENCODED_FILE_NAME: RegExp = /filename\*\s*=\s*UTF-8''([^;]+)/i; +const FILE_NAME: RegExp = /filename\s*=\s*"?([^";]+)"?/i; + +/** + * The files of the api, like the pdf of a report: their names, and saving them in the browser. + */ +export abstract class BookkeepingFileUtilities { + /** + * Saves a file in the browser, like a download. + * @param file - The file, with the name to save it under. + */ + static save(file: BookkeepingFile): void { + const url: string = URL.createObjectURL(file.content); + const link: HTMLAnchorElement = document.createElement('a'); + link.href = url; + link.download = file.name; + link.click(); + URL.revokeObjectURL(url); + } + + /** + * Finds the name of a file in the content disposition header the api answers it with. + * @param contentDisposition - The header, like `attachment; filename="balance-sheet-2026.pdf"`, or null without one. + * @returns The name, or undefined when the header names none. + */ + static findFileName(contentDisposition: string | null): string | undefined { + if (contentDisposition == undefined) { + return undefined; + } + const encoded: string | undefined = ENCODED_FILE_NAME.exec(contentDisposition)?.[1]; + if (encoded != undefined) { + return decodeURIComponent(encoded.trim()); + } + return FILE_NAME.exec(contentDisposition)?.[1]?.trim(); + } +} diff --git a/projects/ngx-bookkeeping/api/bookkeeping-fiscal-year.utilities.spec.ts b/projects/ngx-bookkeeping/api/bookkeeping-fiscal-year.utilities.spec.ts new file mode 100644 index 0000000..6acb7a1 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-fiscal-year.utilities.spec.ts @@ -0,0 +1,25 @@ +import { describe, expect, test } from 'vitest'; +import { FiscalYearModel } from 'zibri-contract'; + +import { FISCAL_YEAR_2025, FISCAL_YEAR_2026, FISCAL_YEARS } from '../fixtures/bookkeeping.fixtures'; +import { BookkeepingFiscalYearUtilities } from './bookkeeping-fiscal-year.utilities'; + +const DAY_FORMAT: Intl.DateTimeFormatOptions = { year: 'numeric', month: '2-digit', day: '2-digit' }; + +describe('BookkeepingFiscalYearUtilities', () => { + test('names a calendar year by its year, and any other by its days', () => { + const short: FiscalYearModel = { ...FISCAL_YEAR_2025, start: new Date('2025-03-15T00:00:00.000Z') }; + + expect(BookkeepingFiscalYearUtilities.resolveLabel(FISCAL_YEAR_2026, DAY_FORMAT, 'en-US')).toBe('2026'); + expect(BookkeepingFiscalYearUtilities.resolveLabel(short, DAY_FORMAT, 'en-US')).toBe('03/15/2025 – 12/31/2025'); + expect(BookkeepingFiscalYearUtilities.resolveLabel(short, DAY_FORMAT, 'de')).toBe('15.03.2025 – 31.12.2025'); + }); + + test('offers the latest fiscal year first, and shows the one of a day, or the latest when none holds it', () => { + expect(BookkeepingFiscalYearUtilities.resolveOptions(FISCAL_YEARS, DAY_FORMAT, 'en-US').map(option => option.label)) + .toEqual(['2026', '2025']); + expect(BookkeepingFiscalYearUtilities.findFiscalYearOf(FISCAL_YEARS, new Date('2025-06-30T00:00:00.000Z'))).toBe(FISCAL_YEAR_2025); + expect(BookkeepingFiscalYearUtilities.findFiscalYearOf(FISCAL_YEARS, new Date('2030-01-01T00:00:00.000Z'))).toBe(FISCAL_YEAR_2026); + expect(BookkeepingFiscalYearUtilities.findFiscalYearOf([], new Date())).toBeUndefined(); + }); +}); diff --git a/projects/ngx-bookkeeping/api/bookkeeping-fiscal-year.utilities.ts b/projects/ngx-bookkeeping/api/bookkeeping-fiscal-year.utilities.ts new file mode 100644 index 0000000..8873bed --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-fiscal-year.utilities.ts @@ -0,0 +1,57 @@ +import { InputOption } from '@service-soft/ui/input'; +import { FiscalYearModel } from 'zibri-contract'; + +import { BookkeepingDayUtilities } from './bookkeeping-day.utilities'; + +/** + * The fiscal years as the views offer them to choose from. + */ +export abstract class BookkeepingFiscalYearUtilities { + /** + * Resolves what a fiscal year is called: its calendar year, like '2026', or its first and last day, like + * '07/01/2025 – 06/30/2026' in 'en-US', for one that is no calendar year. + * @param fiscalYear - The fiscal year. + * @param dateFormat - The format of its days, the options of Intl.DateTimeFormat. + * @param locale - The locale, like the LOCALE_ID of the app. + * @returns The name. + */ + static resolveLabel(fiscalYear: FiscalYearModel, dateFormat: Intl.DateTimeFormatOptions, locale: string): string { + const { start, end } = fiscalYear; + const isCalendarYear: boolean = start.getUTCFullYear() === end.getUTCFullYear() + && start.getUTCMonth() === 0 && start.getUTCDate() === 1 + && end.getUTCMonth() === 11 && end.getUTCDate() === 31; + if (isCalendarYear) { + return String(start.getUTCFullYear()); + } + return `${BookkeepingDayUtilities.format(start, dateFormat, locale)} – ${BookkeepingDayUtilities.format(end, dateFormat, locale)}`; + } + + /** + * Resolves the fiscal years as the options of a select, the latest first. + * @param fiscalYears - The fiscal years, as the api answers them. + * @param dateFormat - The format of their days, the options of Intl.DateTimeFormat. + * @param locale - The locale, like the LOCALE_ID of the app. + * @returns An option per fiscal year, whose value is its id. + */ + static resolveOptions(fiscalYears: FiscalYearModel[], dateFormat: Intl.DateTimeFormatOptions, locale: string): InputOption[] { + return this.getLatestFirst(fiscalYears) + .map(fiscalYear => ({ label: this.resolveLabel(fiscalYear, dateFormat, locale), value: fiscalYear.id })); + } + + /** + * Finds the fiscal year a view shows first: the one of a day, or the latest when none holds it. + * @param fiscalYears - The fiscal years. + * @param day - The day, at midnight UTC, like today. + * @returns The fiscal year, or undefined when there is none. + */ + static findFiscalYearOf(fiscalYears: FiscalYearModel[], day: Date): FiscalYearModel | undefined { + const holding: FiscalYearModel | undefined = fiscalYears.find(fiscalYear => { + return fiscalYear.start.getTime() <= day.getTime() && day.getTime() <= fiscalYear.end.getTime(); + }); + return holding ?? this.getLatestFirst(fiscalYears)[0]; + } + + private static getLatestFirst(fiscalYears: FiscalYearModel[]): FiscalYearModel[] { + return [...fiscalYears].sort((a, b) => b.start.getTime() - a.start.getTime()); + } +} diff --git a/projects/ngx-bookkeeping/api/bookkeeping-fiscal-years-labels.model.ts b/projects/ngx-bookkeeping/api/bookkeeping-fiscal-years-labels.model.ts new file mode 100644 index 0000000..71a2187 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-fiscal-years-labels.model.ts @@ -0,0 +1,222 @@ +/** + * The texts of the fiscal years, to translate them. + */ +export type BookkeepingFiscalYearsLabels = { + /** + * The label of the table of the fiscal years. + */ + fiscalYears: string, + /** + * The header of the first day of a fiscal year. + */ + start: string, + /** + * The header of the last day of a fiscal year. + */ + end: string, + /** + * The header of whether a fiscal year is closed. + */ + status: string, + /** + * The status of an open fiscal year. + */ + open: string, + /** + * The status of a closed fiscal year, with the day it was closed on. + */ + closedOn: (day: string) => string, + /** + * The heading of a fiscal year, with what it is called. + */ + fiscalYear: (fiscalYear: string) => string, + /** + * The heading of adding a fiscal year, and its button. + */ + add: string, + /** + * The hint below the first day of the first fiscal year. + */ + firstStartHint: string, + /** + * What adding says about the first day of a fiscal year after another. + */ + nextStart: (day: string) => string, + /** + * The hint below the last day of the first fiscal year. + */ + firstEndHint: string, + /** + * The hint below the last day of a fiscal year after another, with the day it ends on when the input is empty, a + * year after its start. + */ + nextEndHint: (day: string) => string, + /** + * What the view says once it added a fiscal year. + */ + added: (fiscalYear: string) => string, + /** + * The heading of what the statements of a fiscal year need beside the books. + */ + details: string, + /** + * The input of the average number of employees. + */ + averageEmployees: string, + /** + * The hint below the average number of employees. + */ + averageEmployeesHint: string, + /** + * The input of the note below the balance sheet. + */ + balanceSheetNote: string, + /** + * The hint below the note. + */ + balanceSheetNoteHint: string, + /** + * The select of what the company was before the first fiscal year of the books. + */ + before: string, + /** + * The hint below that select. + */ + beforeHint: string, + /** + * The option of a company founded in the first fiscal year of the books. + */ + founded: string, + /** + * The button that saves the details. + */ + save: string, + /** + * What the view says once it saved the details. + */ + saved: string, + /** + * What the view says about a closed fiscal year, with the day it was closed on. + */ + closedNote: (day: string) => string, + /** + * The heading of closing a fiscal year. + */ + closing: string, + /** + * What the view says about the entries proposed before closing. + */ + proposalsText: string, + /** + * What the view says when nothing is proposed. + */ + noProposals: string, + /** + * What the view says when the proposals couldn't be loaded. + */ + proposalsFailed: string, + /** + * The name of who proposes an entry, with the name of its conformance as it shows. + */ + proposedBy: (conformance: string) => string, + /** + * What screen readers call the table of the lines of a proposed entry, with its text. + */ + proposalLines: (text: string) => string, + /** + * The button that posts a proposed entry. + */ + postProposal: string, + /** + * What screen readers call the button that posts a proposed entry, with its text. + */ + postProposalOf: (text: string) => string, + /** + * What the view says once it posted a proposed entry. + */ + proposalPosted: (sequence: number) => string, + /** + * The select of the account the result of the year is carried into. + */ + resultAccount: string, + /** + * The hint below the result account. + */ + resultAccountHint: string, + /** + * The button that closes the fiscal year. + */ + close: string, + /** + * What the view says once it closed a fiscal year, with it and the one after it. + */ + closedResult: (fiscalYear: string, nextFiscalYear: string) => string, + /** + * The button that reopens a closed fiscal year, and the one confirming it in its dialog. + */ + reopen: string, + /** + * The heading of the dialog that reopens a fiscal year, with what it is called. + */ + reopenTitle: (fiscalYear: string) => string, + /** + * What reopening does. + */ + reopenText: string, + /** + * What reopening keeps. + */ + reopenKeptText: string, + /** + * The input of why the fiscal year is reopened. + */ + reopenReason: string, + /** + * The hint below that input. + */ + reopenReasonHint: string, + /** + * What the dialog says about a fiscal year whose E-Bilanz is filed. + */ + reopenFiledNote: string, + /** + * The checkbox that the reopening corrects the filed E-Bilanz, required for a fiscal year whose E-Bilanz is filed. + */ + forCorrection: string, + /** + * The checkbox that the reopening corrects filed accounts, while the app doesn't know whether they are filed. + */ + forCorrectionUnknown: string, + /** + * What the view says once it reopened a fiscal year, with what it is called. + */ + reopened: (fiscalYear: string) => string, + /** + * The heading of the export for a tax audit. + */ + export: string, + /** + * What the view says about the export. + */ + exportText: string, + /** + * The input of whether the export holds the documents. + */ + withDocuments: string, + /** + * The hint below that input. + */ + withDocumentsHint: string, + /** + * What the view says about exporting an open fiscal year. + */ + exportOpenHint: string, + /** + * The button that downloads the export. + */ + downloadExport: string, + /** + * What screen readers read while the export downloads. + */ + exporting: string +}; diff --git a/projects/ngx-bookkeeping/api/bookkeeping-journal-labels.model.ts b/projects/ngx-bookkeeping/api/bookkeeping-journal-labels.model.ts new file mode 100644 index 0000000..9181a43 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-journal-labels.model.ts @@ -0,0 +1,85 @@ +/** + * The texts of the journal, to translate them. + */ +export type BookkeepingJournalLabels = { + /** + * The option of the account filter that shows the entries of every account. + */ + allAccounts: string, + /** + * What the journal says when no entry matches the filters. + */ + noEntries: string, + /** + * What screen readers call the pagination of the journal. + */ + pages: string, + /** + * What screen readers call the table of the lines of an entry. + */ + lines: (sequence: number) => string, + /** + * The sum of the debits of every entry that matches the filters, only of its lines on the account of the filter. + */ + totalDebit: string, + /** + * The sum of the credits of every entry that matches the filters, only of its lines on the account of the filter. + */ + totalCredit: string, + /** + * The button that reverses an entry. + */ + reverse: string, + /** + * What screen readers call the button that reverses an entry. + */ + reverseEntry: (sequence: number) => string, + /** + * The badge of a reversal whose entry is on the same page of the journal. + */ + reversalOf: (sequence: number) => string, + /** + * The badge of a reversal whose entry is not on the same page. + */ + reversal: string, + /** + * The badge of an entry that was reversed, whose reversal is on the same page. + */ + reversedBy: (sequence: number) => string, + /** + * The badge of an entry that was reversed, whose reversal is not on the same page. + */ + reversedEntry: string, + /** + * What the journal says once it reversed an entry. + */ + reversed: (sequence: number, reversal: number) => string, + /** + * The heading of the dialog that reverses an entry. + */ + reversalTitle: (sequence: number) => string, + /** + * What the dialog says about reversing. + */ + reversalText: string, + /** + * The input of the day the reversal is booked on. + */ + reversalPostingDate: string, + /** + * The hint below the day of the reversal. + */ + reversalPostingDateHint: string, + /** + * The input of why the entry is reversed, the text of the reversal. + */ + reversalReason: string, + /** + * The hint below the reason. + */ + reversalReasonHint: string, + /** + * The button of the dialog that reverses the entry. + */ + confirmReversal: string +}; diff --git a/projects/ngx-bookkeeping/api/bookkeeping-json.utilities.ts b/projects/ngx-bookkeeping/api/bookkeeping-json.utilities.ts new file mode 100644 index 0000000..2950f05 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-json.utilities.ts @@ -0,0 +1,158 @@ +import { BookkeepingAccountModel, BookkeepingClosingProposalModel, BookkeepingLedgerReportModel, BookkeepingSettingsModel, BookkeepingStatementModel, BookkeepingTrialBalanceModel, FiscalYearClosingResultModel, FiscalYearModel, FiscalYearReopeningResultModel, JournalEntryDetailsModel } from 'zibri-contract'; + +/** + * The models of the api as json answers them: its dates arrive as the strings of json, which the models of + * zibri-contract declare as Date. Each turns them into Date again. Only used by the BookkeepingService. + */ +export abstract class BookkeepingJsonUtilities { + /** + * Turns the dates of the settings into Date. + * @param settings - The settings, as json answers them. + * @returns The settings with Date. + */ + static toSettings(settings: BookkeepingSettingsModel): BookkeepingSettingsModel { + return { + ...settings, + legalForms: settings.legalForms.map(legalForm => ({ ...legalForm, validFrom: new Date(legalForm.validFrom) })) + }; + } + + /** + * Turns the dates of an account into Date. + * @param account - The account, as json answers it. + * @returns The account with Date. + */ + static toAccount(account: BookkeepingAccountModel): BookkeepingAccountModel { + return { ...account, closedAt: this.toOptionalDate(account.closedAt) }; + } + + /** + * Turns the dates of a fiscal year into Date. + * @param fiscalYear - The fiscal year, as json answers it. + * @returns The fiscal year with Date. + */ + static toFiscalYear(fiscalYear: FiscalYearModel): FiscalYearModel { + return { + ...fiscalYear, + start: new Date(fiscalYear.start), + end: new Date(fiscalYear.end), + closedAt: this.toOptionalDate(fiscalYear.closedAt) + }; + } + + /** + * Turns the dates of an entry and its lines into Date. + * @param details - The entry with its lines, as json answers it. + * @returns The entry with Date. + */ + static toEntryDetails(details: JournalEntryDetailsModel): JournalEntryDetailsModel { + const { entry, lines } = details; + return { + ...details, + entry: { + ...entry, + retainUntil: new Date(entry.retainUntil), + documentDate: new Date(entry.documentDate), + postingDate: new Date(entry.postingDate), + postedAt: new Date(entry.postedAt) + }, + lines: lines.map(line => ({ ...line, retainUntil: new Date(line.retainUntil) })) + }; + } + + /** + * Turns the dates of a ledger into Date. + * @param ledger - The ledger, as json answers it. + * @returns The ledger with Date. + */ + static toLedger(ledger: BookkeepingLedgerReportModel): BookkeepingLedgerReportModel { + return { + ...ledger, + account: this.toAccount(ledger.account), + from: new Date(ledger.from), + until: new Date(ledger.until), + lines: ledger.lines.map(line => ({ + ...line, + postingDate: new Date(line.postingDate), + documentDate: new Date(line.documentDate) + })) + }; + } + + /** + * Turns the dates of a trial balance into Date. + * @param trialBalance - The trial balance, as json answers it. + * @returns The trial balance with Date. + */ + static toTrialBalance(trialBalance: BookkeepingTrialBalanceModel): BookkeepingTrialBalanceModel { + return { + ...trialBalance, + start: new Date(trialBalance.start), + until: new Date(trialBalance.until), + rows: trialBalance.rows.map(row => ({ ...row, account: this.toAccount(row.account) })) + }; + } + + /** + * Turns the dates of a statement into Date. + * @param statement - The balance sheet or income statement, as json answers it. + * @returns The statement with Date. + */ + static toStatement(statement: BookkeepingStatementModel): BookkeepingStatementModel { + return { + ...statement, + start: new Date(statement.start), + end: new Date(statement.end), + previousEnd: statement.previousEnd == undefined ? statement.previousEnd : new Date(statement.previousEnd) + }; + } + + /** + * Turns the dates of a proposed entry into Date. + * @param proposal - The proposal, as json answers it. + * @returns The proposal with Date. + */ + static toClosingProposal(proposal: BookkeepingClosingProposalModel): BookkeepingClosingProposalModel { + return { + ...proposal, + entry: { + ...proposal.entry, + documentDate: new Date(proposal.entry.documentDate), + postingDate: new Date(proposal.entry.postingDate) + } + }; + } + + /** + * Turns the dates of what closing a fiscal year posted into Date. + * @param result - The result, as json answers it. + * @returns The result with Date. + */ + static toClosingResult(result: FiscalYearClosingResultModel): FiscalYearClosingResultModel { + return { + fiscalYear: this.toFiscalYear(result.fiscalYear), + nextFiscalYear: this.toFiscalYear(result.nextFiscalYear), + closingEntry: result.closingEntry == undefined ? result.closingEntry : this.toEntryDetails(result.closingEntry), + openingEntry: result.openingEntry == undefined ? result.openingEntry : this.toEntryDetails(result.openingEntry) + }; + } + + /** + * Turns the dates of what reopening a fiscal year posted into Date. + * @param result - The result, as json answers it. + * @returns The result with Date. + */ + static toReopeningResult(result: FiscalYearReopeningResultModel): FiscalYearReopeningResultModel { + return { + fiscalYear: this.toFiscalYear(result.fiscalYear), + nextFiscalYear: result.nextFiscalYear == undefined ? result.nextFiscalYear : this.toFiscalYear(result.nextFiscalYear), + closingReversal: result.closingReversal == undefined ? result.closingReversal : this.toEntryDetails(result.closingReversal), + openingReversal: result.openingReversal == undefined ? result.openingReversal : this.toEntryDetails(result.openingReversal) + }; + } + + // null and absent stay as they are, as the models tell them apart. + private static toOptionalDate(date: Date | null | undefined): Date | null | undefined { + return date == undefined ? date : new Date(date); + } +} diff --git a/projects/ngx-bookkeeping/api/bookkeeping-labels-changes.model.ts b/projects/ngx-bookkeeping/api/bookkeeping-labels-changes.model.ts new file mode 100644 index 0000000..5576105 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-labels-changes.model.ts @@ -0,0 +1,8 @@ +import { BookkeepingLabels } from './bookkeeping-labels.model'; + +/** + * The texts of the views to change, by the view that shows them. Each text left out keeps its default. + */ +export type BookkeepingLabelsChanges = { + [View in keyof BookkeepingLabels]?: Partial +}; diff --git a/projects/ngx-bookkeeping/api/bookkeeping-labels.model.ts b/projects/ngx-bookkeeping/api/bookkeeping-labels.model.ts new file mode 100644 index 0000000..dad1a79 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-labels.model.ts @@ -0,0 +1,41 @@ +import { BookkeepingCommonLabels } from './bookkeeping-common-labels.model'; +import { BookkeepingEntryFormLabels } from './bookkeeping-entry-form-labels.model'; +import { BookkeepingFiscalYearsLabels } from './bookkeeping-fiscal-years-labels.model'; +import { BookkeepingJournalLabels } from './bookkeeping-journal-labels.model'; +import { BookkeepingLedgerLabels } from './bookkeeping-ledger-labels.model'; +import { BookkeepingStatementLabels } from './bookkeeping-statement-labels.model'; +import { BookkeepingTrialBalanceLabels } from './bookkeeping-trial-balance-labels.model'; + +/** + * The texts of the views of the books, to translate them, by the view that shows them. + */ +export type BookkeepingLabels = { + /** + * The texts several views show. + */ + common: BookkeepingCommonLabels, + /** + * The texts of the journal. + */ + journal: BookkeepingJournalLabels, + /** + * The texts of the form that posts an entry. + */ + entryForm: BookkeepingEntryFormLabels, + /** + * The texts of the ledger. + */ + ledger: BookkeepingLedgerLabels, + /** + * The texts of the trial balance. + */ + trialBalance: BookkeepingTrialBalanceLabels, + /** + * The texts of the balance sheet and the income statement. + */ + statements: BookkeepingStatementLabels, + /** + * The texts of the fiscal years. + */ + fiscalYears: BookkeepingFiscalYearsLabels +}; diff --git a/projects/ngx-bookkeeping/api/bookkeeping-ledger-labels.model.ts b/projects/ngx-bookkeeping/api/bookkeeping-ledger-labels.model.ts new file mode 100644 index 0000000..3f5ddb2 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-ledger-labels.model.ts @@ -0,0 +1,25 @@ +/** + * The texts of the ledger of an account, to translate them. + */ +export type BookkeepingLedgerLabels = { + /** + * What the ledger says while no account is chosen. + */ + chooseAccount: string, + /** + * What screen readers call the table of the ledger, with the account as it shows. + */ + table: (account: string) => string, + /** + * The row of the balance before the period. + */ + openingBalance: string, + /** + * The balance after the period. + */ + closingBalance: string, + /** + * What the ledger says when nothing was booked on the account in the period. + */ + noLines: string +}; diff --git a/projects/ngx-bookkeeping/api/bookkeeping-paths.model.ts b/projects/ngx-bookkeeping/api/bookkeeping-paths.model.ts new file mode 100644 index 0000000..26db2cb --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-paths.model.ts @@ -0,0 +1,67 @@ +/** + * The paths of the routes below the baseUrl, `/`. A report is a pdf at its path with `.pdf` after it, like + * `reports/balance-sheet.pdf`. + */ +export type BookkeepingPaths = { + /** + * The settings of the books, whose currency the amounts are written in. 'settings' by default. + */ + settings: string, + /** + * The accounts. 'accounts' by default. + */ + accounts: string, + /** + * The fiscal years, which a POST adds to and a PATCH of `/` changes. 'fiscal-years' by default. + */ + fiscalYears: string, + /** + * The entries, a page of which a GET loads, and which a POST posts. 'entries' by default. + */ + entries: string, + /** + * Below an entry, `//`: reverses it with a POST. 'reversal' by default. + */ + reversal: string, + /** + * Below a fiscal year: the entries proposed before it is closed. 'closing-proposals' by default. + */ + closingProposals: string, + /** + * Below a fiscal year: closes it with a POST. 'closing' by default. + */ + closing: string, + /** + * Below a fiscal year: reopens it with a POST. 'reopening' by default. + */ + reopening: string, + /** + * Below a fiscal year: its export for a tax audit, as a file. 'export' by default. + */ + export: string, + /** + * Below a fiscal year: the forms its balance sheet and its income statement can be shown in. 'statement-forms' by + * default. + */ + statementForms: string, + /** + * The journal of a range, which downloads as a pdf. 'reports/journal' by default. + */ + journal: string, + /** + * The ledger of an account. 'reports/ledger' by default. + */ + ledger: string, + /** + * The trial balance of a fiscal year. 'reports/trial-balance' by default. + */ + trialBalance: string, + /** + * The balance sheet of a fiscal year. 'reports/balance-sheet' by default. + */ + balanceSheet: string, + /** + * The income statement of a fiscal year. 'reports/income-statement' by default. + */ + incomeStatement: string +}; diff --git a/projects/ngx-bookkeeping/api/bookkeeping-statement-labels.model.ts b/projects/ngx-bookkeeping/api/bookkeeping-statement-labels.model.ts new file mode 100644 index 0000000..d779c52 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-statement-labels.model.ts @@ -0,0 +1,45 @@ +/** + * The texts of the balance sheet and the income statement, to translate them. + */ +export type BookkeepingStatementLabels = { + /** + * The select of the form of the statement. + */ + form: string, + /** + * The option of the form that applies to the fiscal year, by its name, which shows first. + */ + applyingForm: (form: string) => string, + /** + * The header of the positions. + */ + position: string, + /** + * The result of the fiscal year. + */ + result: string, + /** + * The badge of a statement of a closed fiscal year. + */ + final: string, + /** + * What the statement of a closed fiscal year says about itself. + */ + finalNote: string, + /** + * The badge of a statement of an open fiscal year. + */ + preliminary: string, + /** + * What the statement of an open fiscal year says about itself. + */ + preliminaryNote: string, + /** + * The heading of the accounts with a balance in no position of the statement. + */ + unmapped: string, + /** + * What the statement says about those accounts. + */ + unmappedText: string +}; diff --git a/projects/ngx-bookkeeping/api/bookkeeping-trial-balance-labels.model.ts b/projects/ngx-bookkeeping/api/bookkeeping-trial-balance-labels.model.ts new file mode 100644 index 0000000..05ec11a --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-trial-balance-labels.model.ts @@ -0,0 +1,33 @@ +/** + * The texts of the trial balance, to translate them. + */ +export type BookkeepingTrialBalanceLabels = { + /** + * The input of the last day whose entries count. + */ + until: string, + /** + * The hint below the last day. + */ + untilHint: string, + /** + * What screen readers call the table, with the fiscal year and the last day as they show. + */ + table: (fiscalYear: string, until: string) => string, + /** + * The header of the number of an account. + */ + number: string, + /** + * The header of the balances on the debit side. + */ + debitBalance: string, + /** + * The header of the balances on the credit side. + */ + creditBalance: string, + /** + * What the trial balance says when nothing was booked in the fiscal year. + */ + noRows: string +}; diff --git a/projects/ngx-bookkeeping/api/bookkeeping-view.directive.ts b/projects/ngx-bookkeeping/api/bookkeeping-view.directive.ts new file mode 100644 index 0000000..c35ed15 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping-view.directive.ts @@ -0,0 +1,178 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { computed, Directive, inject, linkedSignal, LOCALE_ID, resource, ResourceRef, Signal, signal, WritableSignal } from '@angular/core'; +import { InputOption } from '@service-soft/ui/input'; +import { BookkeepingSettingsModel, FiscalYearModel } from 'zibri-contract'; + +import { BookkeepingAmountUtilities } from './bookkeeping-amount.utilities'; +import { BookkeepingCommonLabels } from './bookkeeping-common-labels.model'; +import { BookkeepingConfig } from './bookkeeping-config.model'; +import { BOOKKEEPING_CONFIG } from './bookkeeping-config.provider'; +import { BookkeepingDayUtilities } from './bookkeeping-day.utilities'; +import { BookkeepingFile } from './bookkeeping-file.model'; +import { BookkeepingFileUtilities } from './bookkeeping-file.utilities'; +import { BookkeepingFiscalYearUtilities } from './bookkeeping-fiscal-year.utilities'; +import { BookkeepingService } from './bookkeeping.service'; + +/** + * What the views of the books share: the settings, whose currency their amounts are written in, the fiscal year they + * show, the one of today at first, and downloading a file of the api, like the pdf of a report. The journal, the + * ledger, the trial balance, the statements and the fiscal years extend it. + */ +@Directive() +export abstract class BookkeepingViewDirective { + /** + * The config of the books. + */ + protected readonly config: BookkeepingConfig = inject(BOOKKEEPING_CONFIG); + + /** + * Sends the requests of the books. + */ + protected readonly bookkeepingService: BookkeepingService = inject(BookkeepingService); + + /** + * The language of the app, which amounts and days are written in. + */ + protected readonly locale: string = inject(LOCALE_ID); + + /** + * The texts several views show. + */ + protected readonly commonLabels: BookkeepingCommonLabels = this.config.labels.common; + + /** + * The settings of the books. + */ + protected readonly settings: ResourceRef = resource({ + loader: async () => await this.bookkeepingService.resolveSettings() + }); + + /** + * The fiscal years of the books, the earliest first. + */ + protected readonly fiscalYears: ResourceRef = resource({ + loader: async () => await this.bookkeepingService.resolveFiscalYears() + }); + + /** + * The fiscal years to choose from, the latest first. + */ + protected readonly fiscalYearOptions: Signal[]> = computed(() => { + return BookkeepingFiscalYearUtilities.resolveOptions(this.getFiscalYears(), this.config.dateFormat, this.locale); + }); + + /** + * Whether the books have no fiscal year yet. + */ + protected readonly hasNoFiscalYears: Signal = computed(() => this.fiscalYears.hasValue() && !this.getFiscalYears().length); + + /** + * The id of the fiscal year that shows: the one of today at first, or the latest. It stays while it is one of the + * fiscal years, also when they change, like after one was added. + */ + protected readonly fiscalYearId: WritableSignal = linkedSignal({ + source: () => this.getFiscalYears(), + computation: (fiscalYears, previous) => { + if (previous?.value != undefined && fiscalYears.some(fiscalYear => fiscalYear.id === previous.value)) { + return previous.value; + } + return BookkeepingFiscalYearUtilities.findFiscalYearOf(fiscalYears, BookkeepingDayUtilities.resolveToday())?.id; + } + }); + + /** + * The fiscal year that shows, undefined until the fiscal years are loaded. + */ + protected readonly fiscalYear: Signal = computed(() => { + return this.getFiscalYears().find(fiscalYear => fiscalYear.id === this.fiscalYearId()); + }); + + /** + * The first day of the fiscal year, in the time zone of the browser, as the date inputs take it. + */ + protected readonly fiscalYearStart: Signal = computed(() => this.resolveLocalDate(this.fiscalYear()?.start)); + + /** + * The last day of the fiscal year, in the time zone of the browser, as the date inputs take it. + */ + protected readonly fiscalYearEnd: Signal = computed(() => this.resolveLocalDate(this.fiscalYear()?.end)); + + /** + * How amounts are written: in the language of the app, with the currency of the books. Undefined until the + * settings are loaded. + */ + protected readonly format: Signal = computed(() => { + const settings: BookkeepingSettingsModel | undefined = this.settings.hasValue() ? this.settings.value() : undefined; + return settings == undefined ? undefined : BookkeepingAmountUtilities.resolveFormat(settings.currency, this.locale); + }); + + /** + * Whether the last file couldn't be downloaded. + */ + protected readonly downloadFailed: WritableSignal = signal(false); + + /** + * What the view says went wrong: that the books couldn't be loaded, or the last file downloaded. Undefined while + * nothing did. + */ + protected readonly alert: Signal = computed(() => { + if (this.loadingFailed()) { + return this.commonLabels.loadingFailed; + } + return this.downloadFailed() ? this.commonLabels.downloadFailed : undefined; + }); + + /** + * Whether what the view shows couldn't be loaded, the books or its report. + */ + protected abstract readonly loadingFailed: Signal; + + /** + * Downloads a file and saves it, or says that it couldn't be downloaded. + * @param resolveFile - Loads the file, like the pdf of a report. + */ + protected async download(resolveFile: () => Promise): Promise { + this.downloadFailed.set(false); + try { + BookkeepingFileUtilities.save(await resolveFile()); + } + catch (error) { + // a failed request is the answer to the download, anything else a mistake for the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.downloadFailed.set(true); + } + } + + /** + * Formats an amount of the api in the currency of the books. + * @param amount - The decimal string. + * @param format - The format, from format(). + * @returns The amount as it shows. + */ + protected formatAmount(amount: string, format: Intl.NumberFormat): string { + return BookkeepingAmountUtilities.format(amount, format); + } + + /** + * Formats a day of the books in the date format of the config. + * @param day - The day, at midnight UTC. + * @returns The day as it shows. + */ + protected formatDay(day: Date): string { + return BookkeepingDayUtilities.format(day, this.config.dateFormat, this.locale); + } + + /** + * Gets the fiscal years, or none while they load or couldn't be loaded, whose value can't be read. + * @returns The fiscal years, the earliest first. + */ + protected getFiscalYears(): FiscalYearModel[] { + return this.fiscalYears.hasValue() ? this.fiscalYears.value() ?? [] : []; + } + + private resolveLocalDate(day: Date | undefined): Date | undefined { + return day == undefined ? undefined : BookkeepingDayUtilities.resolveLocalDate(day); + } +} diff --git a/projects/ngx-bookkeeping/api/bookkeeping.service.spec.ts b/projects/ngx-bookkeeping/api/bookkeeping.service.spec.ts new file mode 100644 index 0000000..3fd6010 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping.service.spec.ts @@ -0,0 +1,116 @@ +import { HttpHeaders, provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { describe, expect, test } from 'vitest'; +import { BookkeepingStatementFormChoicesModel, BookkeepingStatementModel, BookkeepingStatementType, FiscalYearModel, JournalEntryDetailsModel, JournalEntryPageModel } from 'zibri-contract'; + +import { ACCOUNT_IDS, ACCOUNTS, BALANCE_SHEET_2026, BOOKKEEPING_BASE_URL, ENTRY_IDS, ENTRY_PAGE_2026, FISCAL_YEAR_IDS, FISCAL_YEARS, INVOICE_REVERSAL, STATEMENT_FORMS_2026, toJson } from '../fixtures/bookkeeping.fixtures'; +import { BookkeepingFile } from './bookkeeping-file.model'; +import { provideBookkeepingConfig } from './bookkeeping-config.provider'; +import { BookkeepingService } from './bookkeeping.service'; + +function setup(): [BookkeepingService, HttpTestingController] { + TestBed.configureTestingModule({ + providers: [provideHttpClient(), provideHttpClientTesting(), provideBookkeepingConfig({ baseUrl: BOOKKEEPING_BASE_URL })] + }); + return [TestBed.inject(BookkeepingService), TestBed.inject(HttpTestingController)]; +} + +describe('BookkeepingService', () => { + test('loads the fiscal years and the accounts, and answers their dates as Date', async () => { + const [service, http] = setup(); + + const fiscalYears: Promise = service.resolveFiscalYears(); + http.expectOne({ method: 'GET', url: `${BOOKKEEPING_BASE_URL}/fiscal-years` }).flush(toJson(FISCAL_YEARS)); + await expect(fiscalYears).resolves.toEqual(FISCAL_YEARS); + + const accounts: Promise = service.resolveAccounts(); + http.expectOne({ method: 'GET', url: `${BOOKKEEPING_BASE_URL}/accounts` }).flush(toJson(ACCOUNTS)); + await expect(accounts).resolves.toEqual(ACCOUNTS); + http.verify(); + }); + + test('loads a page of the entries, with the days of the query in ISO format and the filters left out sent not at all', async () => { + const [service, http] = setup(); + + const page: Promise = service.resolveEntries({ + page: 2, + limit: 20, + from: new Date('2026-03-01T00:00:00.000Z'), + until: new Date('2026-03-31T00:00:00.000Z'), + accountId: ACCOUNT_IDS.receivables + }); + const request: TestRequest = http.expectOne(({ url }) => url === `${BOOKKEEPING_BASE_URL}/entries`); + expect(request.request.params.toString()).toBe(`page=2&limit=20&from=2026-03-01&until=2026-03-31&accountId=${ACCOUNT_IDS.receivables}`); + request.flush(toJson(ENTRY_PAGE_2026)); + + await expect(page).resolves.toEqual(ENTRY_PAGE_2026); + }); + + test('loads the forms of the statements of a fiscal year below it', async () => { + const [service, http] = setup(); + + const forms: Promise = service.resolveStatementFormChoices(FISCAL_YEAR_IDS.year2026); + http.expectOne({ method: 'GET', url: `${BOOKKEEPING_BASE_URL}/fiscal-years/${FISCAL_YEAR_IDS.year2026}/statement-forms` }) + .flush(toJson(STATEMENT_FORMS_2026)); + + await expect(forms).resolves.toEqual(STATEMENT_FORMS_2026); + }); + + test('loads a statement in a form, and leaves the form out for the one of the fiscal year', async () => { + const [service, http] = setup(); + + const statement: Promise = service.resolveStatement( + BookkeepingStatementType.BALANCE_SHEET, + FISCAL_YEAR_IDS.year2026, + 'hgb.balance-sheet.micro' + ); + const request: TestRequest = http.expectOne(({ url }) => url === `${BOOKKEEPING_BASE_URL}/reports/balance-sheet`); + expect(request.request.params.toString()).toBe(`fiscalYearId=${FISCAL_YEAR_IDS.year2026}&form=hgb.balance-sheet.micro`); + request.flush(toJson(BALANCE_SHEET_2026)); + await expect(statement).resolves.toEqual(BALANCE_SHEET_2026); + + void service.resolveStatement(BookkeepingStatementType.INCOME_STATEMENT, FISCAL_YEAR_IDS.year2026, undefined); + const incomeStatement: TestRequest = http.expectOne(({ url }) => url === `${BOOKKEEPING_BASE_URL}/reports/income-statement`); + expect(incomeStatement.request.params.toString()).toBe(`fiscalYearId=${FISCAL_YEAR_IDS.year2026}`); + }); + + test('reverses an entry with a POST below it, and keeps it as the last posting', async () => { + const [service, http] = setup(); + expect(service.lastPosting()).toBeUndefined(); + + const reversal: Promise = service.reverseEntry(ENTRY_IDS.invoice, { + postingDate: new Date('2026-03-12T00:00:00.000Z'), + text: 'Wrong customer' + }); + const request: TestRequest = http.expectOne({ method: 'POST', url: `${BOOKKEEPING_BASE_URL}/entries/${ENTRY_IDS.invoice}/reversal` }); + // the api takes a day as its midnight UTC + expect(toJson(request.request.body)).toEqual({ postingDate: '2026-03-12T00:00:00.000Z', text: 'Wrong customer' }); + request.flush(toJson(INVOICE_REVERSAL)); + + await expect(reversal).resolves.toEqual(INVOICE_REVERSAL); + expect(service.lastPosting()).toEqual(INVOICE_REVERSAL); + }); + + test('loads a pdf as a file with the name the api gives it, or the name of the report without one', async () => { + const [service, http] = setup(); + + const named: Promise = service.resolveTrialBalancePdf(FISCAL_YEAR_IDS.year2026, undefined); + http.expectOne(({ url }) => url === `${BOOKKEEPING_BASE_URL}/reports/trial-balance.pdf`).flush(new Blob(['%PDF']), { + headers: new HttpHeaders({ 'content-disposition': 'attachment; filename="trial-balance-2026-01-01-2026-12-31.pdf"' }) + }); + expect((await named).name).toBe('trial-balance-2026-01-01-2026-12-31.pdf'); + + const unnamed: Promise = service.resolveExport(FISCAL_YEAR_IDS.year2026, { documents: false }); + const request: TestRequest = http.expectOne(({ url }) => url === `${BOOKKEEPING_BASE_URL}/fiscal-years/${FISCAL_YEAR_IDS.year2026}/export`); + expect(request.request.params.toString()).toBe('documents=false'); + request.flush(new Blob(['PK'])); + expect((await unnamed).name).toBe('export.zip'); + }); + + test('says what is missing without the baseUrl', async () => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + + await expect(TestBed.inject(BookkeepingService).resolveSettings()).rejects.toThrow('provideBookkeepingConfig({ baseUrl })'); + }); +}); diff --git a/projects/ngx-bookkeeping/api/bookkeeping.service.ts b/projects/ngx-bookkeeping/api/bookkeeping.service.ts new file mode 100644 index 0000000..1736a73 --- /dev/null +++ b/projects/ngx-bookkeeping/api/bookkeeping.service.ts @@ -0,0 +1,381 @@ +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { inject, Service, Signal, signal, WritableSignal } from '@angular/core'; +import { firstValueFrom } from 'rxjs'; +import { BookkeepingAccountModel, BookkeepingClosingProposalModel, BookkeepingExportOptionsModel, BookkeepingLedgerReportModel, BookkeepingSettingsModel, BookkeepingStatementFormChoicesModel, BookkeepingStatementModel, BookkeepingStatementType, BookkeepingTrialBalanceModel, FiscalYearChangeModel, FiscalYearClosingModel, FiscalYearClosingResultModel, FiscalYearModel, FiscalYearReopeningModel, FiscalYearReopeningResultModel, JournalEntryDetailsModel, JournalEntryPageModel, JournalEntryQueryModel, JournalEntryReversalModel, NewFiscalYearModel, NewJournalEntryModel } from 'zibri-contract'; + +import { BookkeepingConfig } from './bookkeeping-config.model'; +import { BOOKKEEPING_CONFIG } from './bookkeeping-config.provider'; +import { BookkeepingDayUtilities } from './bookkeeping-day.utilities'; +import { BookkeepingFile } from './bookkeeping-file.model'; +import { BookkeepingFileUtilities } from './bookkeeping-file.utilities'; +import { BookkeepingJsonUtilities } from './bookkeeping-json.utilities'; + +/** + * The query of a request. + */ +type BookkeepingParams = Record; + +/** + * Sends the requests of the bookkeeping routes at the baseUrl of provideBookkeepingConfig, like `GET /entries` for a + * page of the journal, `POST /entries` to post an entry and `POST /fiscal-years/:id/closing` to close a fiscal year. It + * answers the models of zibri-contract, with their dates as Date, and the pdfs and the export as files to save. It + * needs HttpClient, from provideHttpClient. + */ +@Service() +export class BookkeepingService { + /** + * Sends the requests. + */ + protected readonly http: HttpClient = inject(HttpClient); + + private readonly config: BookkeepingConfig = inject(BOOKKEEPING_CONFIG); + + private readonly lastPostingSignal: WritableSignal = signal(undefined); + + /** + * The last entry this service posted, reversed or closed a fiscal year with, or undefined before the first. Read it + * in the params of a resource of the books, which then loads again after every posting of the app, like the + * journal does. + */ + readonly lastPosting: Signal = this.lastPostingSignal.asReadonly(); + + /** + * Loads the settings of the books, whose currency the amounts are in. + * @returns The settings. Rejects with a 404 for a tenant without books. + */ + async resolveSettings(): Promise { + const settings: BookkeepingSettingsModel = await firstValueFrom( + this.http.get(this.resolveUrl(this.config.paths.settings)) + ); + return BookkeepingJsonUtilities.toSettings(settings); + } + + /** + * Loads the accounts of the books. + * @returns Every account, by number. + */ + async resolveAccounts(): Promise { + const accounts: BookkeepingAccountModel[] = await firstValueFrom( + this.http.get(this.resolveUrl(this.config.paths.accounts)) + ); + return accounts.map(account => BookkeepingJsonUtilities.toAccount(account)); + } + + /** + * Loads the fiscal years of the books. + * @returns Every fiscal year, the earliest first. + */ + async resolveFiscalYears(): Promise { + const fiscalYears: FiscalYearModel[] = await firstValueFrom( + this.http.get(this.resolveUrl(this.config.paths.fiscalYears)) + ); + return fiscalYears.map(fiscalYear => BookkeepingJsonUtilities.toFiscalYear(fiscalYear)); + } + + /** + * Adds a fiscal year. Rejects with the error of the request when the api refuses it, like for one that doesn't start + * the day after the last. + * @param fiscalYear - The fiscal year, with its days at midnight UTC. + * @returns The fiscal year added. + */ + async createFiscalYear(fiscalYear: NewFiscalYearModel): Promise { + const created: FiscalYearModel = await firstValueFrom( + this.http.post(this.resolveUrl(this.config.paths.fiscalYears), fiscalYear) + ); + return BookkeepingJsonUtilities.toFiscalYear(created); + } + + /** + * Changes what an open fiscal year holds for its statements, like its average number of employees. + * @param id - The id of the fiscal year. + * @param change - What to change. A property left out stays as it is. + * @returns The fiscal year changed. + */ + async updateFiscalYear(id: string, change: FiscalYearChangeModel): Promise { + const updated: FiscalYearModel = await firstValueFrom( + this.http.patch(this.resolveUrl(this.config.paths.fiscalYears, id), change) + ); + return BookkeepingJsonUtilities.toFiscalYear(updated); + } + + /** + * Loads the entries the conformances of a fiscal year propose to post before it is closed, like a legal reserve. + * @param id - The id of the fiscal year. + * @returns The proposals, each with the entry as postEntry takes it. + */ + async resolveClosingProposals(id: string): Promise { + const url: string = this.resolveUrl(this.config.paths.fiscalYears, id, this.config.paths.closingProposals); + const proposals: BookkeepingClosingProposalModel[] = await firstValueFrom(this.http.get(url)); + return proposals.map(proposal => BookkeepingJsonUtilities.toClosingProposal(proposal)); + } + + /** + * Closes a fiscal year: nothing is posted into it afterwards, and the next one opens with its balances. Rejects with + * the error of the request when the api refuses it, like while a proposed entry isn't posted. + * @param id - The id of the fiscal year. + * @param closing - The equity account its result is carried into. + * @returns Both fiscal years, and the entries closing it and opening the next. + */ + async closeFiscalYear(id: string, closing: FiscalYearClosingModel): Promise { + const url: string = this.resolveUrl(this.config.paths.fiscalYears, id, this.config.paths.closing); + const result: FiscalYearClosingResultModel = BookkeepingJsonUtilities.toClosingResult( + await firstValueFrom(this.http.post(url, closing)) + ); + const posted: JournalEntryDetailsModel | null = result.openingEntry ?? result.closingEntry; + if (posted != undefined) { + this.lastPostingSignal.set(posted); + } + return result; + } + + /** + * Reopens a closed fiscal year to correct its books: reverses the entry that closed it and the opening balances of + * the next one, so it can be posted into and closed again. Nothing of the closing is deleted. The api asks for a + * second factor, which the interceptor of the app's auth, like the one of @service-soft/ngx-auth, asks the user for. + * Rejects with the error of the request when the api refuses it, like while the next fiscal year is closed. + * @param id - The id of the fiscal year. + * @param reopening - Why it is reopened, and whether to correct accounts already filed. + * @returns Both fiscal years, and both reversals. + */ + async reopenFiscalYear(id: string, reopening: FiscalYearReopeningModel): Promise { + const url: string = this.resolveUrl(this.config.paths.fiscalYears, id, this.config.paths.reopening); + const result: FiscalYearReopeningResultModel = BookkeepingJsonUtilities.toReopeningResult( + await firstValueFrom(this.http.post(url, reopening)) + ); + const posted: JournalEntryDetailsModel | null = result.openingReversal ?? result.closingReversal; + if (posted != undefined) { + this.lastPostingSignal.set(posted); + } + return result; + } + + /** + * Loads the forms the balance sheet and the income statement of a fiscal year can be shown in, each with the one + * that applies to the fiscal year. + * @param id - The id of the fiscal year. + * @returns The forms of both statements, with their names in the language of the request. + */ + async resolveStatementFormChoices(id: string): Promise { + const url: string = this.resolveUrl(this.config.paths.fiscalYears, id, this.config.paths.statementForms); + return await firstValueFrom(this.http.get(url)); + } + + /** + * Loads the export of a fiscal year for a tax audit, a zip archive of its accounts, entries and documents. + * @param id - The id of the fiscal year. + * @param options - Whether it holds the documents, which it does by default. + * @returns The archive, with the name the api gives it. + */ + async resolveExport(id: string, options: BookkeepingExportOptionsModel): Promise { + const params: BookkeepingParams = options.documents == undefined ? {} : { documents: String(options.documents) }; + return await this.resolveFile(this.resolveUrl(this.config.paths.fiscalYears, id, this.config.paths.export), params, 'export.zip'); + } + + /** + * Posts an entry. Rejects with the error of the request when the api refuses it, like for an entry into a closed + * fiscal year. + * @param entry - The entry, with its days at midnight UTC and its amounts as decimal strings. + * @returns The entry posted, with its lines and its number in its fiscal year. + */ + async postEntry(entry: NewJournalEntryModel): Promise { + const posted: JournalEntryDetailsModel = BookkeepingJsonUtilities.toEntryDetails( + await firstValueFrom(this.http.post(this.resolveUrl(this.config.paths.entries), entry)) + ); + this.lastPostingSignal.set(posted); + return posted; + } + + /** + * Reverses an entry: posts its lines with debit and credit swapped. Rejects with the error of the request when the + * api refuses it, like for an entry reversed already. + * @param id - The id of the entry. + * @param reversal - The day the reversal is booked on, at midnight UTC, and why. + * @returns The reversal posted. + */ + async reverseEntry(id: string, reversal: JournalEntryReversalModel): Promise { + const url: string = this.resolveUrl(this.config.paths.entries, id, this.config.paths.reversal); + const posted: JournalEntryDetailsModel = BookkeepingJsonUtilities.toEntryDetails( + await firstValueFrom(this.http.post(url, reversal)) + ); + this.lastPostingSignal.set(posted); + return posted; + } + + /** + * Loads a page of the journal: the entries with their lines. Rejects with the error of the request when the api + * refuses the query, like for an account the books don't have. + * @param query - The page, and the fiscal year, the days and the account to filter by, the days at midnight UTC. + * @returns The entries of the page, by posting day and number, how many there are on all pages together, and the + * debits and the credits of all of them, only of their lines on the account of the query when it names one. + */ + async resolveEntries(query: JournalEntryQueryModel): Promise { + const { page, limit, fiscalYearId, from, until, accountId } = query; + const params: BookkeepingParams = { + page: String(page), + limit: String(limit), + ...fiscalYearId == undefined ? {} : { fiscalYearId }, + ...from == undefined ? {} : { from: BookkeepingDayUtilities.getQueryValue(from) }, + ...until == undefined ? {} : { until: BookkeepingDayUtilities.getQueryValue(until) }, + ...accountId == undefined ? {} : { accountId } + }; + const entries: JournalEntryPageModel = await firstValueFrom( + this.http.get(this.resolveUrl(this.config.paths.entries), { params }) + ); + return { ...entries, items: entries.items.map(entry => BookkeepingJsonUtilities.toEntryDetails(entry)) }; + } + + /** + * Loads the journal of a range as a pdf. + * @param from - The first day, at midnight UTC. + * @param until - The last day, at midnight UTC. + * @returns The pdf, with the name the api gives it. + */ + async resolveJournalPdf(from: Date, until: Date): Promise { + return await this.resolveFile(this.resolvePdfUrl(this.config.paths.journal), this.getRangeParams(from, until), 'journal.pdf'); + } + + /** + * Loads the ledger of an account: what was booked on it on the days of a range. + * @param accountId - The id of the account. + * @param from - The first day, at midnight UTC. + * @param until - The last day, at midnight UTC. + * @returns The lines with the balance after each, and the balances before and after them. + */ + async resolveLedger(accountId: string, from: Date, until: Date): Promise { + const ledger: BookkeepingLedgerReportModel = await firstValueFrom(this.http.get( + this.resolveUrl(this.config.paths.ledger), + { params: { accountId, ...this.getRangeParams(from, until) } } + )); + return BookkeepingJsonUtilities.toLedger(ledger); + } + + /** + * Loads the ledger of an account as a pdf. + * @param accountId - The id of the account. + * @param from - The first day, at midnight UTC. + * @param until - The last day, at midnight UTC. + * @returns The pdf, with the name the api gives it. + */ + async resolveLedgerPdf(accountId: string, from: Date, until: Date): Promise { + return await this.resolveFile( + this.resolvePdfUrl(this.config.paths.ledger), + { accountId, ...this.getRangeParams(from, until) }, + 'ledger.pdf' + ); + } + + /** + * Loads the trial balance of a fiscal year: the sums and the balance of every account booked on. + * @param fiscalYearId - The id of the fiscal year. + * @param until - The last day whose entries count, at midnight UTC, or undefined for the end of the fiscal year. + * @returns A row per account, and the sums of every column. + */ + async resolveTrialBalance(fiscalYearId: string, until: Date | undefined): Promise { + const trialBalance: BookkeepingTrialBalanceModel = await firstValueFrom(this.http.get( + this.resolveUrl(this.config.paths.trialBalance), + { params: this.getTrialBalanceParams(fiscalYearId, until) } + )); + return BookkeepingJsonUtilities.toTrialBalance(trialBalance); + } + + /** + * Loads the trial balance of a fiscal year as a pdf. + * @param fiscalYearId - The id of the fiscal year. + * @param until - The last day whose entries count, at midnight UTC, or undefined for the end of the fiscal year. + * @returns The pdf, with the name the api gives it. + */ + async resolveTrialBalancePdf(fiscalYearId: string, until: Date | undefined): Promise { + return await this.resolveFile( + this.resolvePdfUrl(this.config.paths.trialBalance), + this.getTrialBalanceParams(fiscalYearId, until), + 'trial-balance.pdf' + ); + } + + /** + * Loads the balance sheet or the income statement of a fiscal year. + * @param type - Which of both. + * @param fiscalYearId - The id of the fiscal year. + * @param form - The id of the form, or undefined for the one the api resolves for the fiscal year. + * @returns The statement, its positions in their order with the figures of the year before. + */ + async resolveStatement( + type: BookkeepingStatementType, + fiscalYearId: string, + form: string | undefined + ): Promise { + const statement: BookkeepingStatementModel = await firstValueFrom(this.http.get( + this.resolveUrl(this.getStatementPath(type)), + { params: this.getStatementParams(fiscalYearId, form) } + )); + return BookkeepingJsonUtilities.toStatement(statement); + } + + /** + * Loads the balance sheet or the income statement of a fiscal year as a pdf. + * @param type - Which of both. + * @param fiscalYearId - The id of the fiscal year. + * @param form - The id of the form, or undefined for the one the api resolves for the fiscal year. + * @returns The pdf, with the name the api gives it. + */ + async resolveStatementPdf(type: BookkeepingStatementType, fiscalYearId: string, form: string | undefined): Promise { + const fallbackName: string = type === BookkeepingStatementType.BALANCE_SHEET ? 'balance-sheet.pdf' : 'income-statement.pdf'; + return await this.resolveFile( + this.resolvePdfUrl(this.getStatementPath(type)), + this.getStatementParams(fiscalYearId, form), + fallbackName + ); + } + + private getStatementPath(type: BookkeepingStatementType): string { + switch (type) { + case BookkeepingStatementType.BALANCE_SHEET: { + return this.config.paths.balanceSheet; + } + case BookkeepingStatementType.INCOME_STATEMENT: { + return this.config.paths.incomeStatement; + } + } + } + + private getRangeParams(from: Date, until: Date): BookkeepingParams { + return { from: BookkeepingDayUtilities.getQueryValue(from), until: BookkeepingDayUtilities.getQueryValue(until) }; + } + + private getTrialBalanceParams(fiscalYearId: string, until: Date | undefined): BookkeepingParams { + return { fiscalYearId, ...until == undefined ? {} : { until: BookkeepingDayUtilities.getQueryValue(until) } }; + } + + private getStatementParams(fiscalYearId: string, form: string | undefined): BookkeepingParams { + return { fiscalYearId, ...form == undefined ? {} : { form } }; + } + + private async resolveFile(url: string, params: BookkeepingParams, fallbackName: string): Promise { + const response: HttpResponse = await firstValueFrom( + this.http.get(url, { params, responseType: 'blob', observe: 'response' }) + ); + // the api names the file, like after the fiscal year. A browser hides the header of another origin that didn't + // expose it, and the file keeps the name of what it is then. + const name: string = BookkeepingFileUtilities.findFileName(response.headers.get('content-disposition')) ?? fallbackName; + return { name, content: response.body ?? new Blob() }; + } + + // a report is a pdf at its own path with .pdf after it. + private resolvePdfUrl(path: string): string { + return `${this.resolveUrl(path)}.pdf`; + } + + // the paths are the config's as they are, as some hold a slash, like 'reports/journal'. Only ids are encoded. + private resolveUrl(path: string, id?: string, subPath?: string): string { + if (this.config.baseUrl == undefined) { + throw new Error('The BookkeepingService needs the url of the bookkeeping routes of your api. ' + + 'Add provideBookkeepingConfig({ baseUrl }) to the providers of your app.'); + } + return [ + this.config.baseUrl, + path, + ...id == undefined ? [] : [encodeURIComponent(id)], + ...subPath == undefined ? [] : [subPath] + ].join('/'); + } +} diff --git a/projects/ngx-bookkeeping/api/e-bilanz-account-mappings-labels.model.ts b/projects/ngx-bookkeeping/api/e-bilanz-account-mappings-labels.model.ts new file mode 100644 index 0000000..6a904e2 --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz-account-mappings-labels.model.ts @@ -0,0 +1,85 @@ +/** + * The texts of the account mappings of the E-Bilanz. + */ +export type EBilanzAccountMappingsLabels = { + /** + * The tab and the heading of the account mappings. + */ + accountMappings: string, + /** + * The text of the account mappings. + */ + accountMappingsText: string, + /** + * What the view says when the account mappings couldn't be loaded. + */ + loadingFailed: string, + /** + * The heading of the accounts the findings say need a position. + */ + unmappedAccounts: string, + /** + * The label of the table of the accounts mapped to a position of their own. + */ + mappedAccounts: string, + /** + * What the view says while no account is mapped. + */ + noMappings: string, + /** + * The heading of the form that maps an account. + */ + mapAccountTitle: string, + /** + * The header and the input of the position of a mapping. + */ + position: string, + /** + * The hint below the position of a mapping. + */ + positionHint: string, + /** + * The input of the position of a credit balance. + */ + creditPosition: string, + /** + * The hint below that input. + */ + creditPositionHint: string, + /** + * The button that maps an account the findings name. + */ + map: string, + /** + * The name of that button, with the account. + */ + mapOf: (account: string) => string, + /** + * The button that edits a mapping. + */ + edit: string, + /** + * The name of that button, with the account. + */ + editOf: (account: string) => string, + /** + * The button that removes a mapping. + */ + remove: string, + /** + * The name of that button, with the account. + */ + removeOf: (account: string) => string, + /** + * The button that saves a mapping. + */ + save: string, + /** + * What the view says once an account was mapped, with the account. + */ + mapped: (account: string) => string, + /** + * What the view says once a mapping was removed, with the account. + */ + removed: (account: string) => string +}; diff --git a/projects/ngx-bookkeeping/api/e-bilanz-certificate-labels.model.ts b/projects/ngx-bookkeeping/api/e-bilanz-certificate-labels.model.ts new file mode 100644 index 0000000..bf74d62 --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz-certificate-labels.model.ts @@ -0,0 +1,49 @@ +/** + * The texts of the ELSTER certificate the E-Bilanz is sent with. + */ +export type EBilanzCertificateLabels = { + /** + * The tab and the heading of the certificate. + */ + certificate: string, + /** + * The text of the certificate. + */ + certificateText: string, + /** + * What the view says when it couldn't load whether a certificate is uploaded. + */ + loadingFailed: string, + /** + * Since when the certificate is uploaded. + */ + uploadedAt: (moment: string) => string, + /** + * What the view says while no certificate is uploaded. + */ + noCertificate: string, + /** + * The input of the certificate file. + */ + file: string, + /** + * The hint below that input. + */ + fileHint: string, + /** + * The input of its PIN. + */ + pin: string, + /** + * The hint below that input. + */ + pinHint: string, + /** + * The button that uploads the certificate. + */ + upload: string, + /** + * What the view says once the certificate was uploaded. + */ + uploaded: string +}; diff --git a/projects/ngx-bookkeeping/api/e-bilanz-common-labels.model.ts b/projects/ngx-bookkeeping/api/e-bilanz-common-labels.model.ts new file mode 100644 index 0000000..be55d7a --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz-common-labels.model.ts @@ -0,0 +1,105 @@ +import { EBilanzAccountingStandard } from 'zibri-contract'; + +/** + * The texts of the E-Bilanz around its parts: its heading, its status, its tabs, the steps of filing it and what they + * say about how far it is filed. + */ +export type EBilanzCommonLabels = { + /** + * The heading of the E-Bilanz of a fiscal year, with what the fiscal year is called. + */ + eBilanz: (fiscalYear: string) => string, + /** + * What the view says while no fiscal year is closed, which the E-Bilanz states. + */ + noClosedFiscalYears: string, + /** + * What the view says when the E-Bilanz of the fiscal year couldn't be loaded. + */ + loadingFailed: string, + /** + * The status of an E-Bilanz that isn't prepared. + */ + notPrepared: string, + /** + * The status of an E-Bilanz prepared as the books state it. + */ + prepared: string, + /** + * The status of an E-Bilanz prepared before the books changed. + */ + outdated: string, + /** + * The status of an E-Bilanz that is filed, transmitted or by hand. + */ + filed: string, + /** + * The status of an E-Bilanz that is filed, while a correction of it is prepared or needs to be. + */ + correcting: string, + /** + * The label of the last day the E-Bilanz can be filed on. + */ + deadline: string, + /** + * What each balance sheet the E-Bilanz can state is called. + */ + accountingStandards: Record, + /** + * The tab of filing the E-Bilanz, with its steps. + */ + filing: string, + /** + * What screen readers call the list of the steps of filing it. + */ + steps: string, + /** + * The step that prepares the E-Bilanz. + */ + prepareStep: string, + /** + * The step that shows what was prepared. + */ + reviewStep: string, + /** + * The step that sends the E-Bilanz as a test. + */ + testStep: string, + /** + * The step that sends the E-Bilanz for real, or downloads it and marks it as filed by hand. + */ + fileStep: string, + /** + * The button of the last step, which shows the records. + */ + showRecords: string, + /** + * Why the steps after preparing it wait while it isn't prepared. + */ + notPreparedReason: string, + /** + * Why the steps after preparing it wait, and filing is disabled, while the books changed since it was prepared. + */ + outdatedReason: string, + /** + * What the filing says once the books, or what the E-Bilanz states beside them, changed since it was filed: that a + * correction is prepared. + */ + correctionReason: string, + /** + * How a filed E-Bilanz is corrected, below how it was filed. + */ + correctionHint: string, + /** + * How a filed E-Bilanz was filed: sent and accepted, with when and the ticket of the transmission. + */ + transmittedSummary: (moment: string, ticket: string) => string, + /** + * How a filed E-Bilanz was filed: marked as filed by hand, with when. + */ + manuallyFiledSummary: (moment: string) => string, + /** + * What a step of filing says to a user who may neither send nor download it. + */ + noPermission: string +}; diff --git a/projects/ngx-bookkeeping/api/e-bilanz-config-changes.model.ts b/projects/ngx-bookkeeping/api/e-bilanz-config-changes.model.ts new file mode 100644 index 0000000..cfd9902 --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz-config-changes.model.ts @@ -0,0 +1,21 @@ +import { EBilanzConfig } from './e-bilanz-config.model'; +import { EBilanzLabelsChanges } from './e-bilanz-labels-changes.model'; + +/** + * The values to change in the config of the E-Bilanz. Everything is optional, including every single path and label, + * but the requests need the baseUrl once. + */ +export type EBilanzConfigChanges = Partial> & { + /** + * The url of the E-Bilanz routes of your api, like 'https://api.example.com/e-bilanz'. + */ + baseUrl?: string, + /** + * The paths to change. + */ + paths?: Partial, + /** + * The labels to change, by the part of the view that shows them. + */ + labels?: EBilanzLabelsChanges +}; diff --git a/projects/ngx-bookkeeping/api/e-bilanz-config.model.ts b/projects/ngx-bookkeeping/api/e-bilanz-config.model.ts new file mode 100644 index 0000000..f7ff9ae --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz-config.model.ts @@ -0,0 +1,37 @@ +import { EBilanzLabels } from './e-bilanz-labels.model'; +import { EBilanzPaths } from './e-bilanz-paths.model'; + +/** + * Where the E-Bilanz is, and the values its view uses. The days, the amounts and the heading level are those of the + * books, of provideBookkeepingConfig. + */ +export type EBilanzConfig = { + /** + * The url of the E-Bilanz routes of your api, like 'https://api.example.com/e-bilanz'. Undefined until + * provideEBilanzConfig sets it, which every request of the E-Bilanz needs. + */ + baseUrl: string | undefined, + /** + * The paths of the routes below the baseUrl. + */ + paths: EBilanzPaths, + /** + * Whether the user may prepare and download the E-Bilanz, like with `bookkeeping.e-bilanz.prepare`, which the view + * shows its buttons by while its `canPrepare` isn't set. False by default. + */ + canPrepare: boolean, + /** + * Whether the user may send the E-Bilanz and mark it as filed by hand, like with `bookkeeping.e-bilanz.transmit`, + * which the view shows its buttons by while its `canTransmit` isn't set. False by default. + */ + canTransmit: boolean, + /** + * Whether the user may map accounts and upload the certificate, like with `bookkeeping.e-bilanz.manage`, which the + * view shows their tabs by while its `canManage` isn't set. False by default. + */ + canManage: boolean, + /** + * The texts of the view. + */ + labels: EBilanzLabels +}; diff --git a/projects/ngx-bookkeeping/api/e-bilanz-config.provider.spec.ts b/projects/ngx-bookkeeping/api/e-bilanz-config.provider.spec.ts new file mode 100644 index 0000000..ea0cdaf --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz-config.provider.spec.ts @@ -0,0 +1,42 @@ +import { Injector } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { describe, expect, test } from 'vitest'; + +import { BookkeepingConfig } from './bookkeeping-config.model'; +import { BOOKKEEPING_CONFIG, provideBookkeepingConfig } from './bookkeeping-config.provider'; +import { EBilanzConfig } from './e-bilanz-config.model'; +import { E_BILANZ_CONFIG, provideEBilanzConfig } from './e-bilanz-config.provider'; + +describe('provideEBilanzConfig', () => { + test('is a config of its own: the one of the books has no E-Bilanz in it', () => { + TestBed.configureTestingModule({ providers: [provideBookkeepingConfig({ baseUrl: '/api/bookkeeping' })] }); + + const books: BookkeepingConfig = TestBed.inject(BOOKKEEPING_CONFIG); + + expect(Object.keys(books).filter(key => key.toLowerCase().includes('bilanz'))).toEqual([]); + expect(Object.keys(books.labels)).toEqual(['common', 'journal', 'entryForm', 'ledger', 'trialBalance', 'statements', 'fiscalYears']); + expect(TestBed.inject(E_BILANZ_CONFIG).baseUrl).toBeUndefined(); + }); + + test('takes what it leaves out from the parent injector, and merges the labels part by part', () => { + TestBed.configureTestingModule({ + providers: [provideEBilanzConfig({ baseUrl: '/api/e-bilanz', labels: { filing: { testTransmission: 'Probe senden' } } })] + }); + const child: Injector = Injector.create({ + providers: [ + provideEBilanzConfig({ canTransmit: true, paths: { preview: 'vorschau' }, labels: { records: { records: 'Belege' } } }) + ], + parent: TestBed.inject(Injector) + }); + + const config: EBilanzConfig = child.get(E_BILANZ_CONFIG); + + expect([config.baseUrl, config.canTransmit, config.canPrepare, config.canManage]).toEqual(['/api/e-bilanz', true, false, false]); + expect([config.paths.preview, config.paths.preparation]).toEqual(['vorschau', 'preparation']); + expect([config.labels.filing.testTransmission, config.labels.filing.transmission]).toEqual(['Probe senden', 'Send to the tax administration']); + expect([config.labels.records.records, config.labels.records.noRecords]).toEqual(['Belege', 'Nothing was prepared or filed yet.']); + expect(config.labels.common.prepareStep).toBe('Prepare'); + // the parent keeps its own + expect(TestBed.inject(E_BILANZ_CONFIG).labels.records.records).toBe('Records'); + }); +}); diff --git a/projects/ngx-bookkeeping/api/e-bilanz-config.provider.ts b/projects/ngx-bookkeeping/api/e-bilanz-config.provider.ts new file mode 100644 index 0000000..eb961c4 --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz-config.provider.ts @@ -0,0 +1,299 @@ +import { inject, InjectionToken, Provider } from '@angular/core'; +import { EBilanzAccountingStandard, EBilanzFilingKind, EBilanzRevisionStatus, EBilanzTransmissionStatus } from 'zibri-contract'; + +import { EBilanzConfigChanges } from './e-bilanz-config-changes.model'; +import { EBilanzConfig } from './e-bilanz-config.model'; +import { EBilanzLabelsChanges } from './e-bilanz-labels-changes.model'; +import { EBilanzLabels } from './e-bilanz-labels.model'; + +/** + * The texts of the E-Bilanz when nothing changes them, as $localize, which an app translates like its own. + * @returns The default labels. + */ +function getDefaultEBilanzLabels(): EBilanzLabels { + return { + common: { + eBilanz: fiscalYear => $localize`:@@ngx-bookkeeping.api.eBilanz.common.eBilanz:E-Bilanz ${fiscalYear}:fiscalYear:`, + noClosedFiscalYears: $localize`:@@ngx-bookkeeping.api.eBilanz.common.noClosedFiscalYears:No fiscal year is closed yet. The E-Bilanz states a fiscal year once it is closed.`, + loadingFailed: $localize`:@@ngx-bookkeeping.api.eBilanz.common.loadingFailed:The E-Bilanz couldn't be loaded.`, + notPrepared: $localize`:@@ngx-bookkeeping.api.eBilanz.common.notPrepared:Not prepared`, + prepared: $localize`:@@ngx-bookkeeping.api.eBilanz.common.prepared:Prepared`, + outdated: $localize`:@@ngx-bookkeeping.api.eBilanz.common.outdated:Prepared before the books changed`, + filed: $localize`:@@ngx-bookkeeping.api.eBilanz.common.filed:Filed`, + correcting: $localize`:@@ngx-bookkeeping.api.eBilanz.common.correcting:Filed, being corrected`, + deadline: $localize`:@@ngx-bookkeeping.api.eBilanz.common.deadline:To be filed by`, + accountingStandards: { + [EBilanzAccountingStandard.UNIFIED]: $localize`:@@ngx-bookkeeping.api.eBilanz.common.accountingStandards.unified:The commercial balance sheet, which is the tax balance sheet as well (Einheitsbilanz)`, + [EBilanzAccountingStandard.TAX]: $localize`:@@ngx-bookkeeping.api.eBilanz.common.accountingStandards.tax:A tax balance sheet of its own (Steuerbilanz)` + }, + filing: $localize`:@@ngx-bookkeeping.api.eBilanz.common.filing:Filing`, + steps: $localize`:@@ngx-bookkeeping.api.eBilanz.common.steps:Steps of filing the E-Bilanz`, + prepareStep: $localize`:@@ngx-bookkeeping.api.eBilanz.common.prepareStep:Prepare`, + reviewStep: $localize`:@@ngx-bookkeeping.api.eBilanz.common.reviewStep:Review`, + testStep: $localize`:@@ngx-bookkeeping.api.eBilanz.common.testStep:Test`, + fileStep: $localize`:@@ngx-bookkeeping.api.eBilanz.common.fileStep:Send or file by hand`, + showRecords: $localize`:@@ngx-bookkeeping.api.eBilanz.common.showRecords:Show the records`, + notPreparedReason: $localize`:@@ngx-bookkeeping.api.eBilanz.common.notPreparedReason:Prepare the E-Bilanz first.`, + outdatedReason: $localize`:@@ngx-bookkeeping.api.eBilanz.common.outdatedReason:The books changed since the E-Bilanz was prepared. Prepare it again.`, + correctionReason: $localize`:@@ngx-bookkeeping.api.eBilanz.common.correctionReason:The books, or what the E-Bilanz states beside them, changed since it was filed. Prepare a correction: choose what it corrects, preview and prepare it, send it as a test, and file it again.`, + correctionHint: $localize`:@@ngx-bookkeeping.api.eBilanz.common.correctionHint:To correct it, reopen the fiscal year, post the corrections and close it again. The E-Bilanz then asks for a correction here.`, + transmittedSummary: (moment, ticket) => { + return $localize`:@@ngx-bookkeeping.api.eBilanz.common.transmittedSummary:The E-Bilanz was sent to the tax administration on ${moment}:moment: and accepted, with the ticket ${ticket}:ticket:.`; + }, + manuallyFiledSummary: moment => { + return $localize`:@@ngx-bookkeeping.api.eBilanz.common.manuallyFiledSummary:The E-Bilanz was marked as filed by hand on ${moment}:moment:. Its transmission protocol is in the records.`; + }, + noPermission: $localize`:@@ngx-bookkeeping.api.eBilanz.common.noPermission:You may read the E-Bilanz, but not send it, download it or mark it as filed.` + }, + preparation: { + preparationText: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.preparationText:The preview shows the E-Bilanz as the books state it, with what it needs, and keeps nothing. Prepare it once it needs nothing more: the preparation is archived, and it is what an export and a transmission send.`, + accountingStandard: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.accountingStandard:Balance sheet`, + accountingStandardHint: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.accountingStandardHint:Which balance sheet the E-Bilanz states. Both are legitimate, so choose the one your books are kept for.`, + revisionStatus: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.revisionStatus:What the correction corrects`, + revisionStatusHint: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.revisionStatusHint:The E-Bilanz of this fiscal year is filed, so this one corrects it. Tell the tax administration what changed.`, + revisionStatuses: { + [EBilanzRevisionStatus.CORRECTED]: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.revisionStatuses.corrected:Errors corrected`, + [EBilanzRevisionStatus.CHANGED]: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.revisionStatuses.changed:A choice changed`, + [EBilanzRevisionStatus.CORRECTED_AND_CHANGED]: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.revisionStatuses.correctedAndChanged:Both`, + [EBilanzRevisionStatus.MORE_DETAIL]: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.revisionStatuses.moreDetail:Only more detail`, + [EBilanzRevisionStatus.OTHER_CORRECTION]: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.revisionStatuses.otherCorrection:Another correction` + }, + revisionStatusDescriptions: { + [EBilanzRevisionStatus.CORRECTED]: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.revisionStatusDescriptions.corrected:The balance sheet or the income statement had an error, which is fixed now (berichtigt, § 4 (2) sentence 1 EStG).`, + [EBilanzRevisionStatus.CHANGED]: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.revisionStatusDescriptions.changed:Nothing was wrong, but a choice the law allows is made differently now, like how an asset is valued (geändert, § 4 (2) sentence 2 EStG).`, + [EBilanzRevisionStatus.CORRECTED_AND_CHANGED]: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.revisionStatusDescriptions.correctedAndChanged:An error is fixed, and a choice is made differently as well (berichtigt und geändert).`, + [EBilanzRevisionStatus.MORE_DETAIL]: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.revisionStatusDescriptions.moreDetail:The same figures as filed, only with more detail, like the accounts of each position.`, + [EBilanzRevisionStatus.OTHER_CORRECTION]: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.revisionStatusDescriptions.otherCorrection:Only something outside the balance sheet and the income statement changed, like the details of the company (sonstige Korrektur).` + }, + revisionStatusMissing: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.revisionStatusMissing:Choose what the correction corrects first.`, + fixedAssetFigures: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.fixedAssetFigures:Figures of the statement of changes in fixed assets`, + fixedAssetFiguresText: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.fixedAssetFiguresText:The books don't hold these figures of the positions the findings name. Enter the ones that apply, then preview again.`, + figuresOf: position => $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.figuresOf:Figures of ${position}:position:`, + preview: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.preview:Preview`, + accountingStandardMissing: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.accountingStandardMissing:Choose the balance sheet first.`, + prepare: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.prepare:Prepare`, + previewed: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.previewed:The preview shows the E-Bilanz as the books state it now.`, + previewHasFindings: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.previewHasFindings:It can be prepared once it needs nothing more.`, + previewMissing: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.previewMissing:Preview it first, with the balance sheet and the figures above.`, + preparedAnnouncement: $localize`:@@ngx-bookkeeping.api.eBilanz.preparation.preparedAnnouncement:The E-Bilanz was prepared. Review it, then send it as a test or file it by hand.` + }, + review: { + findings: $localize`:@@ngx-bookkeeping.api.eBilanz.review.findings:What the E-Bilanz needs`, + findingsText: $localize`:@@ngx-bookkeeping.api.eBilanz.review.findingsText:Each of these needs to change before the E-Bilanz can be prepared.`, + wholeFinding: $localize`:@@ngx-bookkeeping.api.eBilanz.review.wholeFinding:The whole E-Bilanz`, + taxonomyVersion: $localize`:@@ngx-bookkeeping.api.eBilanz.review.taxonomyVersion:Version of the taxonomy`, + accountingStandard: $localize`:@@ngx-bookkeeping.api.eBilanz.review.accountingStandard:Balance sheet`, + company: $localize`:@@ngx-bookkeeping.api.eBilanz.review.company:Company`, + taxNumber: $localize`:@@ngx-bookkeeping.api.eBilanz.review.taxNumber:Tax number`, + previewNote: $localize`:@@ngx-bookkeeping.api.eBilanz.review.previewNote:A preview, as the books state it now. It isn't prepared.`, + preparationNote: moment => $localize`:@@ngx-bookkeeping.api.eBilanz.review.preparationNote:As prepared on ${moment}:moment:.`, + noContent: $localize`:@@ngx-bookkeeping.api.eBilanz.review.noContent:The E-Bilanz isn't prepared yet. Choose its balance sheet and preview it.`, + statements: { + balanceSheet: $localize`:@@ngx-bookkeeping.api.eBilanz.review.statements.balanceSheet:Balance sheet`, + incomeStatement: $localize`:@@ngx-bookkeeping.api.eBilanz.review.statements.incomeStatement:Income statement`, + microIncomeStatement: $localize`:@@ngx-bookkeeping.api.eBilanz.review.statements.microIncomeStatement:Income statement of a micro corporation`, + appropriationOfProfits: $localize`:@@ngx-bookkeeping.api.eBilanz.review.statements.appropriationOfProfits:Appropriation of profits` + }, + position: $localize`:@@ngx-bookkeeping.api.eBilanz.review.position:Position`, + amount: $localize`:@@ngx-bookkeeping.api.eBilanz.review.amount:Amount`, + nil: $localize`:@@ngx-bookkeeping.api.eBilanz.review.nil:NIL`, + nilText: $localize`:@@ngx-bookkeeping.api.eBilanz.review.nilText:NIL marks a position the tax administration asks for that the books don't state, which isn't 0.`, + fixedAssets: $localize`:@@ngx-bookkeeping.api.eBilanz.review.fixedAssets:Statement of changes in fixed assets`, + noFixedAssets: $localize`:@@ngx-bookkeeping.api.eBilanz.review.noFixedAssets:The E-Bilanz states no fixed assets.` + }, + filing: { + testText: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.testText:A test goes to the tax administration like the real transmission, which checks it and keeps nothing. The E-Bilanz can be sent for real once a test of the same content was accepted.`, + skipTestText: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.skipTestText:Filing it by hand with another program? Go on without a test.`, + testTransmission: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.testTransmission:Send as a test`, + filingText: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.filingText:Nothing is ever sent by itself: each of these happens once you press its button. Send the E-Bilanz from here, or download it, file it with another program and mark it as filed.`, + sendHeading: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.sendHeading:Send it from here`, + manualHeading: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.manualHeading:File it by hand`, + exportAs: (name, extension) => $localize`:@@ngx-bookkeeping.api.eBilanz.filing.exportAs:Download ${name}:name: (.${extension}:extension:)`, + download: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.download:Download the E-Bilanz`, + noExporters: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.noExporters:It can't be downloaded: this app can't write the E-Bilanz as a file. To download it, ask your administrator to set up the download.`, + transmission: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.transmission:Send to the tax administration`, + manualFiling: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.manualFiling:Mark as filed by hand`, + noTransmitter: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.noTransmitter:Sending isn't set up in this app. Download the file, file it with another program and mark it as filed here. To send from here, ask your administrator to set up sending.`, + certificateMissing: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.certificateMissing:Sending also needs the ELSTER certificate of the company, which isn't uploaded yet: upload it under ELSTER certificate.`, + filedReason: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.filedReason:The E-Bilanz is filed as it was prepared.`, + untestedReason: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.untestedReason:Send it as a test first: it can be sent for real once a test of the same content was accepted.`, + testAccepted: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.testAccepted:The test was accepted. The E-Bilanz can be sent for real now.`, + testRefused: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.testRefused:The test was refused. The tax administration answered:`, + transmitted: ticket => $localize`:@@ngx-bookkeeping.api.eBilanz.filing.transmitted:The E-Bilanz was sent and accepted, with the ticket ${ticket}:ticket:.`, + transmissionRefused: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.transmissionRefused:The transmission was refused. The tax administration answered:`, + failedNotSent: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.failedNotSent:Sending failed, and nothing reached the tax administration, so it can be sent again. What failed:`, + sendingStarted: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.sendingStarted:Sending to ELSTER started.`, + sendingTitle: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.sendingTitle:Sending to ELSTER…`, + sendingText: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.sendingText:This can take several minutes. You can leave this page; the result is recorded.`, + runningReason: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.runningReason:It is being sent to ELSTER right now. Wait for the result, which shows above.`, + unsettledTitle: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.unsettledTitle:The result isn't known`, + unsettledText: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.unsettledText:It may have been sent. Check in ELSTER whether it arrived before you do anything else.`, + unsettledTest: moment => $localize`:@@ngx-bookkeeping.api.eBilanz.filing.unsettledTest:The test started on ${moment}:moment: may have reached ELSTER.`, + unsettledTransmission: moment => $localize`:@@ngx-bookkeeping.api.eBilanz.filing.unsettledTransmission:The transmission started on ${moment}:moment: may have reached ELSTER.`, + unsettledActionsText: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.unsettledActionsText:If it arrived, mark it as filed by hand with the transmission protocol of ELSTER. If it didn't arrive, say so here, and it can be sent again.`, + unsettledReason: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.unsettledReason:It may have been sent already. Check in ELSTER whether it arrived, then mark it as filed by hand or say that ELSTER didn't receive it.`, + notReceived: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.notReceived:ELSTER did not receive it`, + notReceivedTitle: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.notReceivedTitle:ELSTER did not receive it?`, + notReceivedText: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.notReceivedText:Only confirm this once you checked in ELSTER that it did not arrive. Each transmission whose result isn't known is then recorded as not received, and the E-Bilanz can be sent again.`, + notReceivedConsequence: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.notReceivedConsequence:If it did arrive, sending it again files it twice. You may be asked for your second factor.`, + confirmNotReceived: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.confirmNotReceived:It did not arrive`, + notReceivedRecorded: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.notReceivedRecorded:Recorded that ELSTER did not receive it. It can be sent again.`, + manuallyFiled: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.manuallyFiled:The E-Bilanz was marked as filed by hand.`, + transmissionTitle: fiscalYear => $localize`:@@ngx-bookkeeping.api.eBilanz.filing.transmissionTitle:Send the E-Bilanz ${fiscalYear}:fiscalYear: to the tax administration?`, + transmissionContent: (company, taxNumber, period, preparedAt) => { + return $localize`:@@ngx-bookkeeping.api.eBilanz.filing.transmissionContent:This sends the E-Bilanz of ${company}:company:, tax number ${taxNumber}:taxNumber:, for the fiscal year ${period}:period:, as it was prepared on ${preparedAt}:preparedAt:.`; + }, + transmissionStatement: (positions, taxonomyVersion, accountingStandard) => { + return $localize`:@@ngx-bookkeeping.api.eBilanz.filing.transmissionStatement:It states ${positions}:positions: positions in the version ${taxonomyVersion}:taxonomyVersion: of the taxonomy, with the accounts of each position and the statement of changes in fixed assets. Its balance sheet: ${accountingStandard}:accountingStandard:.`; + }, + transmissionTest: (moment, ticket) => $localize`:@@ngx-bookkeeping.api.eBilanz.filing.transmissionTest:Its test was accepted on ${moment}:moment:, with the ticket ${ticket}:ticket:.`, + transmissionFinal: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.transmissionFinal:This is final: the tax administration keeps what it receives, and it can't be taken back. You may be asked for your second factor before it is sent.`, + confirmTransmission: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.confirmTransmission:Send for real`, + manualFilingTitle: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.manualFilingTitle:Mark the E-Bilanz as filed by hand?`, + manualFilingText: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.manualFilingText:Upload the transmission protocol of the program you filed it with. It is archived with the record, and the E-Bilanz as it was prepared counts as filed.`, + protocol: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.protocol:Transmission protocol`, + protocolHint: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.protocolHint:Like the pdf the program wrote`, + confirmManualFiling: $localize`:@@ngx-bookkeeping.api.eBilanz.filing.confirmManualFiling:Mark as filed` + }, + records: { + records: $localize`:@@ngx-bookkeeping.api.eBilanz.records.records:Records`, + noRecords: $localize`:@@ngx-bookkeeping.api.eBilanz.records.noRecords:Nothing was prepared or filed yet.`, + kinds: { + [EBilanzFilingKind.PREPARED]: $localize`:@@ngx-bookkeeping.api.eBilanz.records.kinds.prepared:Prepared`, + [EBilanzFilingKind.TEST_TRANSMISSION]: $localize`:@@ngx-bookkeeping.api.eBilanz.records.kinds.testTransmission:Test transmission`, + [EBilanzFilingKind.TRANSMISSION]: $localize`:@@ngx-bookkeeping.api.eBilanz.records.kinds.transmission:Transmission`, + [EBilanzFilingKind.MANUAL_FILING]: $localize`:@@ngx-bookkeeping.api.eBilanz.records.kinds.manualFiling:Filed by hand` + }, + kind: $localize`:@@ngx-bookkeeping.api.eBilanz.records.kind:Record`, + recordedAt: $localize`:@@ngx-bookkeeping.api.eBilanz.records.recordedAt:Recorded`, + ticket: $localize`:@@ngx-bookkeeping.api.eBilanz.records.ticket:Ticket`, + result: $localize`:@@ngx-bookkeeping.api.eBilanz.records.result:Result`, + statuses: { + [EBilanzTransmissionStatus.TRANSMITTING]: $localize`:@@ngx-bookkeeping.api.eBilanz.records.statuses.transmitting:Started`, + [EBilanzTransmissionStatus.ACCEPTED]: $localize`:@@ngx-bookkeeping.api.eBilanz.records.statuses.accepted:Accepted`, + [EBilanzTransmissionStatus.REFUSED]: $localize`:@@ngx-bookkeeping.api.eBilanz.records.statuses.refused:Refused`, + [EBilanzTransmissionStatus.FAILED]: $localize`:@@ngx-bookkeeping.api.eBilanz.records.statuses.failed:Failed`, + [EBilanzTransmissionStatus.UNKNOWN]: $localize`:@@ngx-bookkeeping.api.eBilanz.records.statuses.unknown:Result not known`, + [EBilanzTransmissionStatus.NOT_RECEIVED]: $localize`:@@ngx-bookkeeping.api.eBilanz.records.statuses.notReceived:Not received, as confirmed` + }, + corrects: (record, moment, revisionStatus) => { + return $localize`:@@ngx-bookkeeping.api.eBilanz.records.corrects:Corrects the record "${record}:record:" of ${moment}:moment:: ${revisionStatus}:revisionStatus:`; + }, + messages: $localize`:@@ngx-bookkeeping.api.eBilanz.records.messages:Messages`, + protocol: $localize`:@@ngx-bookkeeping.api.eBilanz.records.protocol:Protocol`, + downloadProtocol: name => $localize`:@@ngx-bookkeeping.api.eBilanz.records.downloadProtocol:Download ${name}:name:` + }, + accountMappings: { + accountMappings: $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.accountMappings:Account mappings`, + accountMappingsText: $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.accountMappingsText:An account reports as the position of the taxonomy its statement position stands for, or as a position of its own it is mapped to here. A mapping counts for every fiscal year not prepared yet.`, + loadingFailed: $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.loadingFailed:The account mappings couldn't be loaded.`, + unmappedAccounts: $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.unmappedAccounts:Accounts that need a position`, + mappedAccounts: $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.mappedAccounts:Accounts mapped to a position of their own`, + noMappings: $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.noMappings:No account is mapped to a position of its own.`, + mapAccountTitle: $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.mapAccountTitle:Map an account`, + position: $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.position:Position`, + positionHint: $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.positionHint:The element name of the position in the taxonomy, like bs.ass.currAss.cashEquiv.bank`, + creditPosition: $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.creditPosition:Position of a credit balance`, + creditPositionHint: $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.creditPositionHint:The position while its balance is a credit, the one above when empty`, + map: $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.map:Map`, + mapOf: account => $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.mapOf:Map ${account}:account:`, + edit: $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.edit:Edit`, + editOf: account => $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.editOf:Edit the mapping of ${account}:account:`, + remove: $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.remove:Remove`, + removeOf: account => $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.removeOf:Remove the mapping of ${account}:account:`, + save: $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.save:Save the mapping`, + mapped: account => $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.mapped:${account}:account: was mapped. Preview the E-Bilanz again to see what it states now.`, + removed: account => $localize`:@@ngx-bookkeeping.api.eBilanz.accountMappings.removed:The mapping of ${account}:account: was removed.` + }, + certificate: { + certificate: $localize`:@@ngx-bookkeeping.api.eBilanz.certificate.certificate:ELSTER certificate`, + certificateText: $localize`:@@ngx-bookkeeping.api.eBilanz.certificate.certificateText:The transmitter signs the E-Bilanz with the certificate of the company. Whoever has it and its PIN signs for the company, so upload a certificate of its own for the app, and a new one after each renewal in Mein ELSTER.`, + loadingFailed: $localize`:@@ngx-bookkeeping.api.eBilanz.certificate.loadingFailed:Whether a certificate is uploaded couldn't be loaded.`, + uploadedAt: moment => $localize`:@@ngx-bookkeeping.api.eBilanz.certificate.uploadedAt:A certificate was uploaded on ${moment}:moment:.`, + noCertificate: $localize`:@@ngx-bookkeeping.api.eBilanz.certificate.noCertificate:No certificate is uploaded.`, + file: $localize`:@@ngx-bookkeeping.api.eBilanz.certificate.file:Certificate`, + fileHint: $localize`:@@ngx-bookkeeping.api.eBilanz.certificate.fileHint:The .pfx file of Mein ELSTER`, + pin: $localize`:@@ngx-bookkeeping.api.eBilanz.certificate.pin:PIN`, + pinHint: $localize`:@@ngx-bookkeeping.api.eBilanz.certificate.pinHint:It is stored encrypted and never shown again.`, + upload: $localize`:@@ngx-bookkeeping.api.eBilanz.certificate.upload:Upload the certificate`, + uploaded: $localize`:@@ngx-bookkeeping.api.eBilanz.certificate.uploaded:The certificate was uploaded.` + } + }; +} + +/** + * The values of the E-Bilanz when nothing changes them. Its texts are $localize, which an app translates like its own, + * and resolved once the config is injected, so translations an app loads at runtime apply as well. + * @returns The default config. + */ +function getDefaultEBilanzConfig(): EBilanzConfig { + return { + baseUrl: undefined, + paths: { + fiscalYears: 'fiscal-years', + preview: 'preview', + preparation: 'preparation', + export: 'export', + testTransmission: 'test-transmission', + transmission: 'transmission', + transmissionNotReceived: 'transmission-not-received', + manualFiling: 'manual-filing', + settings: 'settings', + certificate: 'settings/certificate', + accountMappings: 'account-mappings' + }, + canPrepare: false, + canTransmit: false, + canManage: false, + labels: getDefaultEBilanzLabels() + }; +} + +/** + * Merges the labels to change into the ones of the parent, part by part. + * @param parent - The labels of the parent injector. + * @param changes - The labels to change. + * @returns The merged labels. + */ +function mergeLabels(parent: EBilanzLabels, changes: EBilanzLabelsChanges | undefined): EBilanzLabels { + return { + common: { ...parent.common, ...changes?.common }, + preparation: { ...parent.preparation, ...changes?.preparation }, + review: { ...parent.review, ...changes?.review }, + filing: { ...parent.filing, ...changes?.filing }, + records: { ...parent.records, ...changes?.records }, + accountMappings: { ...parent.accountMappings, ...changes?.accountMappings }, + certificate: { ...parent.certificate, ...changes?.certificate } + }; +} + +/** + * Where the E-Bilanz is, and the values its view uses, below this injector. Change them with provideEBilanzConfig. + */ +export const E_BILANZ_CONFIG: InjectionToken = new InjectionToken( + 'E_BILANZ_CONFIG', + { providedIn: 'root', factory: () => getDefaultEBilanzConfig() } +); + +/** + * Sets where the E-Bilanz is, `{ baseUrl }`, and changes the values its view uses, like what the user may do or the + * labels to translate it. Provide it in the application config for the whole app, or in a component or route for only + * that part of it. Values you leave out are taken from the parent injector, including single paths and labels. + * @param config - The values to change. + * @returns The provider for E_BILANZ_CONFIG. + */ +export function provideEBilanzConfig(config: EBilanzConfigChanges): Provider { + return { + provide: E_BILANZ_CONFIG, + useFactory: (): EBilanzConfig => { + const parent: EBilanzConfig = inject(E_BILANZ_CONFIG, { skipSelf: true, optional: true }) ?? getDefaultEBilanzConfig(); + return { + ...parent, + ...config, + baseUrl: config.baseUrl ?? parent.baseUrl, + paths: { ...parent.paths, ...config.paths }, + labels: mergeLabels(parent.labels, config.labels) + }; + } + }; +} diff --git a/projects/ngx-bookkeeping/api/e-bilanz-correction-status.type.ts b/projects/ngx-bookkeeping/api/e-bilanz-correction-status.type.ts new file mode 100644 index 0000000..7e1ef27 --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz-correction-status.type.ts @@ -0,0 +1,7 @@ +import { EBilanzRevisionStatus } from 'zibri-contract'; + +/** + * How an E-Bilanz corrects the one filed before it: each revision status but `original`, which only the first + * E-Bilanz of a fiscal year states. + */ +export type EBilanzCorrectionStatus = Exclude; diff --git a/projects/ngx-bookkeeping/api/e-bilanz-filing-labels.model.ts b/projects/ngx-bookkeeping/api/e-bilanz-filing-labels.model.ts new file mode 100644 index 0000000..e398855 --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz-filing-labels.model.ts @@ -0,0 +1,197 @@ +/** + * The texts of the steps that send the E-Bilanz as a test, and for real or file it by hand, with their dialogs. + */ +export type EBilanzFilingLabels = { + /** + * The text of the step that sends it as a test. + */ + testText: string, + /** + * That the test can be left out by whoever files the E-Bilanz by hand. + */ + skipTestText: string, + /** + * The button that sends the E-Bilanz as a test. + */ + testTransmission: string, + /** + * The text of the step that sends it for real or files it by hand. + */ + filingText: string, + /** + * The heading of sending it from the app. + */ + sendHeading: string, + /** + * The heading of filing it by hand: downloading it and marking it as filed. + */ + manualHeading: string, + /** + * The button that downloads the E-Bilanz with an exporter, with its name and the extension of its file. + */ + exportAs: (name: string, extension: string) => string, + /** + * The disabled button that would download the E-Bilanz while the app can't write it as a file. + */ + download: string, + /** + * Why it can't be downloaded: the app can't write it as a file, and who enables it. + */ + noExporters: string, + /** + * The button that sends the E-Bilanz for real. + */ + transmission: string, + /** + * The button that records the E-Bilanz as filed by hand. + */ + manualFiling: string, + /** + * Why sending is disabled while the app can't send it, what to do instead, and who enables it. + */ + noTransmitter: string, + /** + * What sending needs beside, said to a user who uploads the certificate while none is uploaded. + */ + certificateMissing: string, + /** + * Why sending and recording is disabled once the E-Bilanz is filed. + */ + filedReason: string, + /** + * Why sending for real is disabled while no test of the same content was accepted. + */ + untestedReason: string, + /** + * What the view says once a test was accepted. + */ + testAccepted: string, + /** + * What the view says once a test was refused, above the messages of the tax administration. + */ + testRefused: string, + /** + * What the view says once the E-Bilanz was sent and accepted, with the ticket of the transmission. + */ + transmitted: (ticket: string) => string, + /** + * What the view says once a transmission was refused, above the messages of the tax administration. + */ + transmissionRefused: string, + /** + * What the view says once a transmission failed and the api knows it sent nothing, above what failed. + */ + failedNotSent: string, + /** + * What the view says once the api started a transmission, which runs in the background. + */ + sendingStarted: string, + /** + * The heading of what the view shows while a transmission runs. + */ + sendingTitle: string, + /** + * What the view says while a transmission runs. + */ + sendingText: string, + /** + * Why sending and marking it as filed by hand are disabled while a transmission runs. + */ + runningReason: string, + /** + * The heading of the warning about a transmission whose result is not known. + */ + unsettledTitle: string, + /** + * The warning about a transmission whose result is not known: check ELSTER first. + */ + unsettledText: string, + /** + * Which test the warning is about, with when it started. + */ + unsettledTest: (moment: string) => string, + /** + * Which transmission for real the warning is about, with when it started. + */ + unsettledTransmission: (moment: string) => string, + /** + * What the user does once they checked ELSTER. + */ + unsettledActionsText: string, + /** + * Why sending of the same kind is disabled while a transmission of it has a result that is not known. + */ + unsettledReason: string, + /** + * The button that confirms that ELSTER didn't receive it. + */ + notReceived: string, + /** + * The question before confirming that ELSTER didn't receive it. + */ + notReceivedTitle: string, + /** + * What confirming it does. + */ + notReceivedText: string, + /** + * What confirming it risks. + */ + notReceivedConsequence: string, + /** + * The button of that question that confirms it. + */ + confirmNotReceived: string, + /** + * What the view says once it was recorded that ELSTER didn't receive it. + */ + notReceivedRecorded: string, + /** + * What the view says once the E-Bilanz was recorded as filed by hand. + */ + manuallyFiled: string, + /** + * The question before sending the E-Bilanz for real, with what the fiscal year is called. + */ + transmissionTitle: (fiscalYear: string) => string, + /** + * What is sent: the company, its tax number, the fiscal year with its days and when it was prepared. + */ + transmissionContent: (company: string, taxNumber: string, period: string, preparedAt: string) => string, + /** + * What it states: how many positions, in which version of the taxonomy, and which balance sheet. + */ + transmissionStatement: (positions: number, taxonomyVersion: string, accountingStandard: string) => string, + /** + * When the test of the same content was accepted, with the ticket of the test. + */ + transmissionTest: (moment: string, ticket: string) => string, + /** + * That sending is final. + */ + transmissionFinal: string, + /** + * The button that confirms sending for real. + */ + confirmTransmission: string, + /** + * The heading of the dialog that records the E-Bilanz as filed by hand. + */ + manualFilingTitle: string, + /** + * The text of that dialog. + */ + manualFilingText: string, + /** + * The input of the transmission protocol. + */ + protocol: string, + /** + * The hint below that input. + */ + protocolHint: string, + /** + * The button that confirms the filing by hand. + */ + confirmManualFiling: string +}; diff --git a/projects/ngx-bookkeeping/api/e-bilanz-labels-changes.model.ts b/projects/ngx-bookkeeping/api/e-bilanz-labels-changes.model.ts new file mode 100644 index 0000000..1d18b0b --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz-labels-changes.model.ts @@ -0,0 +1,8 @@ +import { EBilanzLabels } from './e-bilanz-labels.model'; + +/** + * The texts of the E-Bilanz to change, by the part of it that shows them. Each text left out keeps its default. + */ +export type EBilanzLabelsChanges = { + [Part in keyof EBilanzLabels]?: Partial +}; diff --git a/projects/ngx-bookkeeping/api/e-bilanz-labels.model.ts b/projects/ngx-bookkeeping/api/e-bilanz-labels.model.ts new file mode 100644 index 0000000..45ce38c --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz-labels.model.ts @@ -0,0 +1,41 @@ +import { EBilanzAccountMappingsLabels } from './e-bilanz-account-mappings-labels.model'; +import { EBilanzCertificateLabels } from './e-bilanz-certificate-labels.model'; +import { EBilanzCommonLabels } from './e-bilanz-common-labels.model'; +import { EBilanzFilingLabels } from './e-bilanz-filing-labels.model'; +import { EBilanzPreparationLabels } from './e-bilanz-preparation-labels.model'; +import { EBilanzRecordsLabels } from './e-bilanz-records-labels.model'; +import { EBilanzReviewLabels } from './e-bilanz-review-labels.model'; + +/** + * The texts of the E-Bilanz, to translate them, by the part of it that shows them. + */ +export type EBilanzLabels = { + /** + * The texts around its parts: its heading, its status, its tabs and the steps of filing it. + */ + common: EBilanzCommonLabels, + /** + * The texts of the step that prepares it. + */ + preparation: EBilanzPreparationLabels, + /** + * The texts of what it needs and of its content. + */ + review: EBilanzReviewLabels, + /** + * The texts of the steps that send it, download it and mark it as filed by hand. + */ + filing: EBilanzFilingLabels, + /** + * The texts of its records. + */ + records: EBilanzRecordsLabels, + /** + * The texts of the account mappings. + */ + accountMappings: EBilanzAccountMappingsLabels, + /** + * The texts of the ELSTER certificate. + */ + certificate: EBilanzCertificateLabels +}; diff --git a/projects/ngx-bookkeeping/api/e-bilanz-paths.model.ts b/projects/ngx-bookkeeping/api/e-bilanz-paths.model.ts new file mode 100644 index 0000000..e0abbf6 --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz-paths.model.ts @@ -0,0 +1,52 @@ +/** + * The paths of the routes of the E-Bilanz below its baseUrl, `/`. + */ +export type EBilanzPaths = { + /** + * The E-Bilanz of a fiscal year, `/`, which the paths below a fiscal year follow. 'fiscal-years' by + * default. + */ + fiscalYears: string, + /** + * Below a fiscal year: the E-Bilanz as the books state it, with a POST, keeping nothing. 'preview' by default. + */ + preview: string, + /** + * Below a fiscal year: prepares the E-Bilanz with a POST. 'preparation' by default. + */ + preparation: string, + /** + * Below a fiscal year: the latest preparation as the file of an exporter. 'export' by default. + */ + export: string, + /** + * Below a fiscal year: sends the latest preparation as a test with a POST. 'test-transmission' by default. + */ + testTransmission: string, + /** + * Below a fiscal year: sends the latest preparation for real with a POST. 'transmission' by default. + */ + transmission: string, + /** + * Below a fiscal year: confirms with a POST that each transmission whose result is not known didn't reach the tax + * administration. 'transmission-not-received' by default. + */ + transmissionNotReceived: string, + /** + * Below a fiscal year: records it as filed by hand with a POST of its protocol. 'manual-filing' by default. + */ + manualFiling: string, + /** + * Whether the certificate is uploaded. 'settings' by default. + */ + settings: string, + /** + * Replaces the certificate and its PIN with a PUT. 'settings/certificate' by default. + */ + certificate: string, + /** + * The accounts mapped to a position of their own, `/` with a PUT or a DELETE for one of them. + * 'account-mappings' by default. + */ + accountMappings: string +}; diff --git a/projects/ngx-bookkeeping/api/e-bilanz-preparation-labels.model.ts b/projects/ngx-bookkeeping/api/e-bilanz-preparation-labels.model.ts new file mode 100644 index 0000000..50676c4 --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz-preparation-labels.model.ts @@ -0,0 +1,79 @@ +import { EBilanzCorrectionStatus } from './e-bilanz-correction-status.type'; + +/** + * The texts of the step that prepares the E-Bilanz. + */ +export type EBilanzPreparationLabels = { + /** + * The text of the step. + */ + preparationText: string, + /** + * The select of which balance sheet the E-Bilanz states. + */ + accountingStandard: string, + /** + * The hint below that select. + */ + accountingStandardHint: string, + /** + * The choice of what a correction of a filed E-Bilanz corrects. + */ + revisionStatus: string, + /** + * The hint below that choice. + */ + revisionStatusHint: string, + /** + * What each option of that choice is called. + */ + revisionStatuses: Record, + /** + * When each option of that choice applies, in plain words. + */ + revisionStatusDescriptions: Record, + /** + * Why a correction can't be previewed: what it corrects isn't chosen. + */ + revisionStatusMissing: string, + /** + * The heading of the figures of the statement of changes in fixed assets the books don't hold. + */ + fixedAssetFigures: string, + /** + * The text above those figures. + */ + fixedAssetFiguresText: string, + /** + * The name of the figures of one position, with what it is called. + */ + figuresOf: (position: string) => string, + /** + * The button that previews the E-Bilanz. + */ + preview: string, + /** + * Why it can't be previewed: no balance sheet is chosen. + */ + accountingStandardMissing: string, + /** + * The button that prepares the E-Bilanz. + */ + prepare: string, + /** + * What the view says once the preview shows. + */ + previewed: string, + /** + * Why the E-Bilanz can't be prepared from the preview: it still needs something. + */ + previewHasFindings: string, + /** + * Why the E-Bilanz can't be prepared: there is no preview of what the step holds now. + */ + previewMissing: string, + /** + * What the view says once the E-Bilanz was prepared. + */ + preparedAnnouncement: string +}; diff --git a/projects/ngx-bookkeeping/api/e-bilanz-records-labels.model.ts b/projects/ngx-bookkeeping/api/e-bilanz-records-labels.model.ts new file mode 100644 index 0000000..034a88a --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz-records-labels.model.ts @@ -0,0 +1,57 @@ +import { EBilanzFilingKind, EBilanzTransmissionStatus } from 'zibri-contract'; + +/** + * The texts of the records of the E-Bilanz. + */ +export type EBilanzRecordsLabels = { + /** + * The tab and the heading of the records. + */ + records: string, + /** + * What the view says while there is no record. + */ + noRecords: string, + /** + * What each kind of record is called. + */ + kinds: Record, + /** + * The header of what a record records. + */ + kind: string, + /** + * The header of when a record was made. + */ + recordedAt: string, + /** + * The header of the ticket of a transmission. + */ + ticket: string, + /** + * The header of where a transmission stands. + */ + result: string, + /** + * Where a transmission stands, as a record of it states it: started, accepted, refused, failed, not known, or not + * received. + */ + statuses: Record, + /** + * What a preparation that corrects a filed E-Bilanz says: what the record it corrects is, when it was made, and + * what the correction corrects. + */ + corrects: (record: string, moment: string, revisionStatus: string) => string, + /** + * The header of the messages of the tax administration. + */ + messages: string, + /** + * The header of the protocol of a record. + */ + protocol: string, + /** + * The button that downloads a protocol, with its name. + */ + downloadProtocol: (name: string) => string +}; diff --git a/projects/ngx-bookkeeping/api/e-bilanz-review-labels.model.ts b/projects/ngx-bookkeeping/api/e-bilanz-review-labels.model.ts new file mode 100644 index 0000000..b9a153c --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz-review-labels.model.ts @@ -0,0 +1,74 @@ +/** + * The texts of the step that shows the E-Bilanz: what it needs, and its content. + */ +export type EBilanzReviewLabels = { + /** + * The heading of what the E-Bilanz needs before it can be prepared. + */ + findings: string, + /** + * The text above those findings. + */ + findingsText: string, + /** + * What a finding about the whole E-Bilanz names in place of a position. + */ + wholeFinding: string, + /** + * The label of the version of the taxonomy the E-Bilanz is stated in. + */ + taxonomyVersion: string, + /** + * The label of which balance sheet it states. + */ + accountingStandard: string, + /** + * The label of the company the E-Bilanz states. + */ + company: string, + /** + * The label of the tax number of the company. + */ + taxNumber: string, + /** + * The note above the content of a preview. + */ + previewNote: string, + /** + * The note above the content of the latest preparation, with when it was prepared. + */ + preparationNote: (moment: string) => string, + /** + * What the view says while there is neither a preparation nor a preview to show. + */ + noContent: string, + /** + * What each statement of the positions is called, by its name in the api, like `balanceSheet`. A statement the + * labels don't name shows by its name. Those of `balanceSheet` and `incomeStatement` are the tabs of the content. + */ + statements: Record, + /** + * The header of the positions and their accounts. + */ + position: string, + /** + * The header of their amounts. + */ + amount: string, + /** + * What a position the books don't state shows in place of its amount. + */ + nil: string, + /** + * What NIL means, above the positions. + */ + nilText: string, + /** + * The tab and the table of the statement of changes in fixed assets. + */ + fixedAssets: string, + /** + * What the view says when the E-Bilanz has no row of the fixed assets. + */ + noFixedAssets: string +}; diff --git a/projects/ngx-bookkeeping/api/e-bilanz.service.spec.ts b/projects/ngx-bookkeeping/api/e-bilanz.service.spec.ts new file mode 100644 index 0000000..a4a6dbe --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz.service.spec.ts @@ -0,0 +1,334 @@ +import { HttpErrorResponse, HttpRequest, provideHttpClient } from '@angular/common/http'; +import { TestBed } from '@angular/core/testing'; +import { HttpTestingUtilities } from 'testing/http'; +import { afterEach, describe, expect, test, vi } from 'vitest'; +import { + EBilanzAccountingStandard, + EBilanzAccountMappingModel, + EBilanzCertificateSettingsModel, + EBilanzFilingKind, + EBilanzFilingModel, + EBilanzFixedAssetInputModel, + EBilanzPreparationInputModel, + EBilanzPreviewModel, + EBilanzStateModel, + EBilanzTransmissionStatus +} from 'zibri-contract'; + +import { BookkeepingTestingUtilities } from '../fixtures/bookkeeping-testing.utilities'; +import { ACCOUNT_IDS, FISCAL_YEAR_IDS } from '../fixtures/bookkeeping.fixtures'; +import { DEPRECIATION_COLUMN, E_BILANZ_BASE_URL, OFFICE_EQUIPMENT_POSITION, TRANSIT_POSITION, XBRL_EXPORTER } from '../fixtures/e-bilanz.fixtures'; +import { FakeEBilanzBackendOptions } from '../fixtures/fake-e-bilanz-backend-options.model'; +import { FakeEBilanzBackend } from '../fixtures/fake-e-bilanz-backend.model'; +import { BookkeepingFile } from './bookkeeping-file.model'; +import { provideEBilanzConfig } from './e-bilanz-config.provider'; +import { EBilanzService } from './e-bilanz.service'; +import { FiscalYearFilingResolver } from './fiscal-year-filing-resolver.model'; +import { FISCAL_YEAR_FILING_RESOLVER, provideFiscalYearFilingResolver } from './fiscal-year-filing-resolver.provider'; + +const FISCAL_YEAR_URL: string = `${E_BILANZ_BASE_URL}/fiscal-years/${FISCAL_YEAR_IDS.year2025}`; +const FIGURES: EBilanzFixedAssetInputModel[] = [{ position: OFFICE_EQUIPMENT_POSITION, values: [{ column: DEPRECIATION_COLUMN, amount: '200.00' }] }]; +const INPUT: EBilanzPreparationInputModel = { accountingStandard: EBilanzAccountingStandard.UNIFIED, fixedAssets: FIGURES }; +// the default duration of a transmission of the fake +const TRANSMISSION_DURATION_IN_MS: number = 3000; + +let backend: FakeEBilanzBackend; + +function setup(options: FakeEBilanzBackendOptions = {}): EBilanzService { + backend = new FakeEBilanzBackend(options); + TestBed.configureTestingModule({ providers: BookkeepingTestingUtilities.getEBilanzProviders(backend) }); + return TestBed.inject(EBilanzService); +} + +// the method and the url of the last request the fake answered, with its query. +function getLastRoute(): string { + const request: HttpRequest | undefined = backend.requests.at(-1); + return request == undefined ? '' : `${request.method} ${request.urlWithParams}`; +} + +// the part of the multipart body of the last request the fake answered. +function findPart(name: string): FormDataEntryValue | null | undefined { + const body: unknown = backend.requests.at(-1)?.body; + return body instanceof FormData ? body.get(name) : undefined; +} + +// the api sends in the background, and the fake records the result after a few seconds. +function useFakeTimers(): void { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); +} + +describe('EBilanzService', () => { + afterEach(() => { + vi.useRealTimers(); + }); + + test('loads the E-Bilanz of a fiscal year from its url below the fiscal years', async () => { + const service: EBilanzService = setup(); + + const state: EBilanzStateModel = await service.resolveState(FISCAL_YEAR_IDS.year2025); + + expect(getLastRoute()).toBe(`GET ${FISCAL_YEAR_URL}`); + expect(state).toMatchObject({ fiscalYearId: FISCAL_YEAR_IDS.year2025, preparationId: null, filed: false, exporters: [XBRL_EXPORTER] }); + }); + + test('previews the E-Bilanz with the input it is given, and answers what it still needs', async () => { + const service: EBilanzService = setup(); + + const preview: EBilanzPreviewModel = await service.resolvePreview(FISCAL_YEAR_IDS.year2025, { accountingStandard: EBilanzAccountingStandard.UNIFIED }); + + expect(getLastRoute()).toBe(`POST ${FISCAL_YEAR_URL}/preview`); + expect(backend.requests.at(-1)?.body).toEqual({ accountingStandard: EBilanzAccountingStandard.UNIFIED }); + expect(preview.content).not.toBeNull(); + // money in transit isn't mapped and the figures of the fixed assets are missing + expect(preview.findings.length).toBeGreaterThan(0); + }); + + test('rejects a preview of an open fiscal year with the error of the api', async () => { + const service: EBilanzService = setup(); + + await expect(service.resolvePreview(FISCAL_YEAR_IDS.year2026, INPUT)).rejects.toMatchObject({ + status: 409, + error: { message: 'The E-Bilanz states a closed fiscal year: close the fiscal year first.' } + }); + }); + + test('maps money in transit to a position of its own, then prepares the E-Bilanz with the figures', async () => { + const service: EBilanzService = setup(); + await expect(service.prepare(FISCAL_YEAR_IDS.year2025, INPUT)).rejects.toBeInstanceOf(HttpErrorResponse); + + const mapping: EBilanzAccountMappingModel = await service.updateAccountMapping(ACCOUNT_IDS.transit, { position: TRANSIT_POSITION }); + expect(getLastRoute()).toBe(`PUT ${E_BILANZ_BASE_URL}/account-mappings/${ACCOUNT_IDS.transit}`); + expect(mapping).toMatchObject({ accountId: ACCOUNT_IDS.transit, position: TRANSIT_POSITION, creditPosition: null }); + + const preparation: EBilanzFilingModel = await service.prepare(FISCAL_YEAR_IDS.year2025, INPUT); + expect(getLastRoute()).toBe(`POST ${FISCAL_YEAR_URL}/preparation`); + expect(backend.requests.at(-1)?.body).toEqual(INPUT); + expect(preparation).toMatchObject({ fiscalYearId: FISCAL_YEAR_IDS.year2025, kind: EBilanzFilingKind.PREPARED }); + expect((await service.resolveState(FISCAL_YEAR_IDS.year2025)).preparationId).toBe(preparation.id); + }); + + test('loads, changes and removes the mappings of the accounts', async () => { + const service: EBilanzService = setup(); + expect(await service.resolveAccountMappings()).toEqual([]); + expect(getLastRoute()).toBe(`GET ${E_BILANZ_BASE_URL}/account-mappings`); + + const mapping: EBilanzAccountMappingModel = await service.updateAccountMapping(ACCOUNT_IDS.transit, { position: TRANSIT_POSITION }); + expect(await service.resolveAccountMappings()).toEqual([mapping]); + + await service.deleteAccountMapping(ACCOUNT_IDS.transit); + expect(getLastRoute()).toBe(`DELETE ${E_BILANZ_BASE_URL}/account-mappings/${ACCOUNT_IDS.transit}`); + expect(await service.resolveAccountMappings()).toEqual([]); + }); + + test('rejects a mapping without a position with the error of the api', async () => { + const service: EBilanzService = setup(); + + await expect(service.updateAccountMapping(ACCOUNT_IDS.transit, { position: '' })) + .rejects.toMatchObject({ status: 400, error: { message: 'position is required' } }); + }); + + test('loads the export of an exporter as a file, with the name the api gives it', async () => { + const service: EBilanzService = setup({ stage: 'prepared' }); + + const file: BookkeepingFile = await service.resolveExport(FISCAL_YEAR_IDS.year2025, XBRL_EXPORTER); + + expect(getLastRoute()).toBe(`GET ${FISCAL_YEAR_URL}/export?exporter=xbrl`); + expect(file.name).toBe('e-bilanz-2025-01-01-2025-12-31.xbrl'); + expect([file.content.type, await file.content.text()]).toEqual(['application/xml', '']); + }); + + test('names an export without a name of the api after the file extension of its exporter', async () => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + HttpTestingUtilities.provideAnswers({ [`GET ${FISCAL_YEAR_URL}/export`]: { status: 200, body: new Blob(['']) } }), + provideEBilanzConfig({ baseUrl: E_BILANZ_BASE_URL }) + ] + }); + + const file: BookkeepingFile = await TestBed.inject(EBilanzService).resolveExport(FISCAL_YEAR_IDS.year2025, XBRL_EXPORTER); + + expect(file.name).toBe('e-bilanz.xbrl'); + }); + + test('rejects an export of an E-Bilanz not prepared with the error of the api', async () => { + const service: EBilanzService = setup(); + + await expect(service.resolveExport(FISCAL_YEAR_IDS.year2025, XBRL_EXPORTER)).rejects.toMatchObject({ + status: 409, + error: { message: 'The E-Bilanz of the fiscal year needs to be prepared first.' } + }); + }); + + test('starts a test, answers the record it started with, and the state has its result once it was sent', async () => { + useFakeTimers(); + const service: EBilanzService = setup({ stage: 'prepared', transmitter: 'configured' }); + + const started: EBilanzFilingModel = await service.transmitTest(FISCAL_YEAR_IDS.year2025); + + expect(getLastRoute()).toBe(`POST ${FISCAL_YEAR_URL}/test-transmission`); + expect(backend.requests.at(-1)?.body).toEqual({}); + expect(started).toMatchObject({ kind: EBilanzFilingKind.TEST_TRANSMISSION, status: EBilanzTransmissionStatus.TRANSMITTING }); + expect((await service.resolveState(FISCAL_YEAR_IDS.year2025)).transmissions) + .toMatchObject([{ id: started.id, test: true, status: EBilanzTransmissionStatus.TRANSMITTING }]); + + await vi.advanceTimersByTimeAsync(TRANSMISSION_DURATION_IN_MS); + + expect((await service.resolveState(FISCAL_YEAR_IDS.year2025)).transmissions) + .toMatchObject([{ id: started.id, test: true, status: EBilanzTransmissionStatus.ACCEPTED }]); + }); + + test('rejects a test without a transmitter with the error of the api', async () => { + const service: EBilanzService = setup({ stage: 'prepared' }); + + await expect(service.transmitTest(FISCAL_YEAR_IDS.year2025)).rejects.toMatchObject({ + status: 409, + error: { message: expect.stringContaining('No transmitter is registered') } + }); + }); + + test('sends an E-Bilanz tested for real, which is filed once it was accepted', async () => { + useFakeTimers(); + const service: EBilanzService = setup({ stage: 'tested', transmitter: 'configured' }); + + const started: EBilanzFilingModel = await service.transmit(FISCAL_YEAR_IDS.year2025); + + expect(getLastRoute()).toBe(`POST ${FISCAL_YEAR_URL}/transmission`); + expect(backend.requests.at(-1)?.body).toEqual({}); + expect(started).toMatchObject({ kind: EBilanzFilingKind.TRANSMISSION, status: EBilanzTransmissionStatus.TRANSMITTING }); + expect(await service.resolveFiled(FISCAL_YEAR_IDS.year2025)).toBe(false); + + await vi.advanceTimersByTimeAsync(TRANSMISSION_DURATION_IN_MS); + + expect(await service.resolveFiled(FISCAL_YEAR_IDS.year2025)).toBe(true); + }); + + test('rejects sending for real before a test was accepted with the error of the api', async () => { + const service: EBilanzService = setup({ stage: 'prepared', transmitter: 'configured' }); + + await expect(service.transmit(FISCAL_YEAR_IDS.year2025)).rejects.toMatchObject({ + status: 409, + error: { message: 'The E-Bilanz needs to be sent as a test and accepted before it is sent for real.' } + }); + }); + + test('records a transmission whose result is not known as not received, so it can be sent again', async () => { + const service: EBilanzService = setup({ stage: 'unknown', transmitter: 'configured' }); + const unknown: string | undefined = (await service.resolveState(FISCAL_YEAR_IDS.year2025)).transmissions + .find(transmission => transmission.status === EBilanzTransmissionStatus.UNKNOWN)?.id; + + const records: EBilanzFilingModel[] = await service.recordNotReceived(FISCAL_YEAR_IDS.year2025); + + expect(getLastRoute()).toBe(`POST ${FISCAL_YEAR_URL}/transmission-not-received`); + expect(backend.requests.at(-1)?.body).toEqual({}); + expect(records).toMatchObject([{ transmissionId: unknown, status: EBilanzTransmissionStatus.NOT_RECEIVED, mayHaveBeenSent: false }]); + expect((await service.resolveState(FISCAL_YEAR_IDS.year2025)).transmissions.find(transmission => transmission.id === unknown)?.status) + .toBe(EBilanzTransmissionStatus.NOT_RECEIVED); + }); + + test('rejects recording a transmission as not received without such a transmission with the error of the api', async () => { + const service: EBilanzService = setup({ stage: 'tested', transmitter: 'configured' }); + + await expect(service.recordNotReceived(FISCAL_YEAR_IDS.year2025)).rejects.toMatchObject({ + status: 409, + error: { message: 'The fiscal year has no transmission of the E-Bilanz whose result is not known.' } + }); + }); + + test('resolves whether the E-Bilanz is filed from its state, as the FiscalYearFilingResolver provided with it', async () => { + backend = new FakeEBilanzBackend({ stage: 'transmitted' }); + TestBed.configureTestingModule({ + providers: [...BookkeepingTestingUtilities.getEBilanzProviders(backend), provideFiscalYearFilingResolver(EBilanzService)] + }); + const resolver: FiscalYearFilingResolver | undefined = TestBed.inject(FISCAL_YEAR_FILING_RESOLVER); + + expect(resolver).toBe(TestBed.inject(EBilanzService)); + expect(await resolver?.resolveFiled(FISCAL_YEAR_IDS.year2025)).toBe(true); + expect(getLastRoute()).toBe(`GET ${FISCAL_YEAR_URL}`); + }); + + test('resolves an E-Bilanz only prepared as not filed, and rejects for a fiscal year the api doesn\'t have', async () => { + const service: EBilanzService = setup({ stage: 'prepared' }); + + expect(await service.resolveFiled(FISCAL_YEAR_IDS.year2025)).toBe(false); + await expect(service.resolveFiled('unknown')).rejects.toMatchObject({ status: 404 }); + }); + + test('records the E-Bilanz as filed by hand with its protocol, and loads the protocol from the url of the record', async () => { + const service: EBilanzService = setup({ stage: 'prepared' }); + const protocol: File = new File(['%PDF-1.7'], 'elster-protocol.pdf', { type: 'application/pdf' }); + + const filing: EBilanzFilingModel = await service.recordManualFiling(FISCAL_YEAR_IDS.year2025, protocol); + + expect(getLastRoute()).toBe(`POST ${FISCAL_YEAR_URL}/manual-filing`); + const part: FormDataEntryValue | null | undefined = findPart('protocol'); + expect(part instanceof File ? part.name : part).toBe('elster-protocol.pdf'); + expect(filing).toMatchObject({ kind: EBilanzFilingKind.MANUAL_FILING, protocol: { name: 'elster-protocol.pdf' } }); + expect(await service.resolveFiled(FISCAL_YEAR_IDS.year2025)).toBe(true); + + if (filing.protocol == undefined) { + throw new Error('The filing has no protocol.'); + } + const file: BookkeepingFile = await service.resolveProtocol(filing.protocol); + expect(getLastRoute()).toBe(`GET ${E_BILANZ_BASE_URL}/${filing.id}/files/protocol`); + expect([file.name, await file.content.text()]).toEqual(['elster-protocol.pdf', '%PDF-1.7']); + }); + + test('rejects a filing by hand of an E-Bilanz not prepared with the error of the api', async () => { + const service: EBilanzService = setup(); + + await expect(service.recordManualFiling(FISCAL_YEAR_IDS.year2025, new File(['%PDF-1.7'], 'protocol.pdf'))) + .rejects.toMatchObject({ status: 409, error: { message: 'The E-Bilanz of the fiscal year needs to be prepared first.' } }); + }); + + test('says that a protocol without a url can\'t be loaded, and sends nothing', async () => { + const service: EBilanzService = setup(); + + await expect(service.resolveProtocol({ name: 'protocol.pdf', mimeType: 'application/pdf', size: 8 })) + .rejects.toThrow('The protocol protocol.pdf has no url it downloads from.'); + expect(backend.requests).toEqual([]); + }); + + test('loads the settings of the certificate, and uploads the certificate with its PIN as a multipart body', async () => { + const service: EBilanzService = setup({ transmitter: 'no-certificate' }); + expect(await service.resolveCertificateSettings()).toEqual({ certificateUploadedAt: null, certificateUploadedBy: null }); + expect(getLastRoute()).toBe(`GET ${E_BILANZ_BASE_URL}/settings`); + + const settings: EBilanzCertificateSettingsModel = await service.updateCertificate(new File(['pfx'], 'company.pfx'), '123456'); + + expect(getLastRoute()).toBe(`PUT ${E_BILANZ_BASE_URL}/settings/certificate`); + const certificate: FormDataEntryValue | null | undefined = findPart('certificate'); + expect([certificate instanceof File ? certificate.name : certificate, findPart('pin')]).toEqual(['company.pfx', '123456']); + expect(settings.certificateUploadedAt).not.toBeNull(); + expect(await service.resolveCertificateSettings()).toEqual(settings); + }); + + test('rejects a certificate with a PIN too short with the error of the api', async () => { + const service: EBilanzService = setup({ transmitter: 'no-certificate' }); + + await expect(service.updateCertificate(new File(['pfx'], 'company.pfx'), '123')).rejects.toMatchObject({ status: 400 }); + }); + + test('sends to the paths of the config, and encodes the ids in them', async () => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + HttpTestingUtilities.provideAnswers({ + 'POST /api/elster/jahre/2025%2F1/vorschau': { status: 200, body: { findings: [] } }, + 'DELETE /api/elster/zuordnungen/1200%2F1': { status: 204 } + }), + provideEBilanzConfig({ baseUrl: '/api/elster', paths: { fiscalYears: 'jahre', preview: 'vorschau', accountMappings: 'zuordnungen' } }) + ] + }); + const service: EBilanzService = TestBed.inject(EBilanzService); + + await expect(service.resolvePreview('2025/1', INPUT)).resolves.toEqual({ findings: [] }); + await expect(service.deleteAccountMapping('1200/1')).resolves.toBeUndefined(); + }); + + test('says what is missing without the baseUrl', async () => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), HttpTestingUtilities.provideAnswers({})] }); + + await expect(TestBed.inject(EBilanzService).resolveState(FISCAL_YEAR_IDS.year2025)).rejects.toThrow('provideEBilanzConfig({ baseUrl })'); + }); +}); diff --git a/projects/ngx-bookkeeping/api/e-bilanz.service.ts b/projects/ngx-bookkeeping/api/e-bilanz.service.ts new file mode 100644 index 0000000..6aa2b6c --- /dev/null +++ b/projects/ngx-bookkeeping/api/e-bilanz.service.ts @@ -0,0 +1,232 @@ +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { inject, Service } from '@angular/core'; +import { firstValueFrom } from 'rxjs'; +import { + EBilanzAccountMappingChangeModel, + EBilanzAccountMappingModel, + EBilanzCertificateSettingsModel, + EBilanzExporterModel, + EBilanzFilingModel, + EBilanzPreparationInputModel, + EBilanzPreviewModel, + EBilanzStateModel, + FileReference +} from 'zibri-contract'; + +import { BookkeepingFile } from './bookkeeping-file.model'; +import { BookkeepingFileUtilities } from './bookkeeping-file.utilities'; +import { EBilanzConfig } from './e-bilanz-config.model'; +import { E_BILANZ_CONFIG } from './e-bilanz-config.provider'; +import { FiscalYearFilingResolver } from './fiscal-year-filing-resolver.model'; + +/** + * Sends the requests of the E-Bilanz routes at the baseUrl of provideEBilanzConfig, like + * `GET /fiscal-years/:id` for the E-Bilanz of a fiscal year, `POST /fiscal-years/:id/preparation` to prepare it and + * `POST /fiscal-years/:id/transmission` to send it. Each request is one the user asked for: nothing here sends by + * itself. It answers the models of zibri-contract, with their dates as the strings of json the models declare, and the + * exports and protocols as files to save. It needs HttpClient, from provideHttpClient. + * + * It is a FiscalYearFilingResolver as well: `provideFiscalYearFilingResolver(EBilanzService)` lets the dialog that + * reopens a fiscal year know whether its E-Bilanz is filed. + */ +@Service() +export class EBilanzService implements FiscalYearFilingResolver { + /** + * Sends the requests. + */ + protected readonly http: HttpClient = inject(HttpClient); + + private readonly config: EBilanzConfig = inject(E_BILANZ_CONFIG); + + /** + * Loads the E-Bilanz of a fiscal year. + * @param fiscalYearId - The id of the fiscal year. + * @returns Its latest preparation, what it needs now, its records, its deadline, and how it can be filed. + */ + async resolveState(fiscalYearId: string): Promise { + return await firstValueFrom(this.http.get(this.resolveFiscalYearUrl(fiscalYearId))); + } + + /** + * Loads the E-Bilanz of a closed fiscal year as the books state it, keeping nothing. Rejects with the error of the + * request when the api refuses it, like for an open fiscal year. + * @param fiscalYearId - The id of the fiscal year. + * @param input - Which balance sheet it states, and the figures of the statement of changes in fixed assets the books + * don't hold. + * @returns The content, and what it needs before it can be prepared. + */ + async resolvePreview(fiscalYearId: string, input: EBilanzPreparationInputModel): Promise { + return await firstValueFrom(this.http.post(this.resolveFiscalYearUrl(fiscalYearId, this.config.paths.preview), input)); + } + + /** + * Prepares the E-Bilanz of a closed fiscal year: archives it as a record, which an export and a transmission send. + * Rejects with the error of the request when the api refuses it, like while it needs something. + * @param fiscalYearId - The id of the fiscal year. + * @param input - What the preview took. + * @returns The record of the preparation. + */ + async prepare(fiscalYearId: string, input: EBilanzPreparationInputModel): Promise { + const url: string = this.resolveFiscalYearUrl(fiscalYearId, this.config.paths.preparation); + return await firstValueFrom(this.http.post(url, input)); + } + + /** + * Loads the latest preparation as the file of an exporter, to file it by hand. Rejects with the error of the request + * when the api refuses it, like while the books state it otherwise than it was prepared. + * @param fiscalYearId - The id of the fiscal year. + * @param exporter - The exporter, one of the state. + * @returns The file, with the name the api gives it. + */ + async resolveExport(fiscalYearId: string, exporter: EBilanzExporterModel): Promise { + const url: string = this.resolveFiscalYearUrl(fiscalYearId, this.config.paths.export); + return await this.resolveFile(url, { exporter: exporter.name }, `e-bilanz.${exporter.fileExtension}`); + } + + /** + * Starts sending the latest preparation as a test, which the tax administration doesn't keep. The api answers once + * it started, with `202`, and sends it in the background: its result is in the `transmissions` of the state, which + * resolveState loads. Rejects with the error of the request when the api refuses it, like without a transmitter. + * @param fiscalYearId - The id of the fiscal year. + * @returns The record the test was started with, whose `status` is `transmitting`. + */ + async transmitTest(fiscalYearId: string): Promise { + const url: string = this.resolveFiscalYearUrl(fiscalYearId, this.config.paths.testTransmission); + return await firstValueFrom(this.http.post(url, {})); + } + + /** + * Starts sending the latest preparation to the tax administration for real. The api asks for a second factor, which + * the interceptor of the app's auth, like the one of @service-soft/ngx-auth, asks the user for. It answers once it + * started, with `202`, and sends it in the background, like transmitTest. Rejects with the error of the request when + * the api refuses it, like until a test of the same content was accepted. + * @param fiscalYearId - The id of the fiscal year. + * @returns The record the transmission was started with, whose `status` is `transmitting`. + */ + async transmit(fiscalYearId: string): Promise { + const url: string = this.resolveFiscalYearUrl(fiscalYearId, this.config.paths.transmission); + return await firstValueFrom(this.http.post(url, {})); + } + + /** + * Confirms that each transmission whose result is not known didn't reach the tax administration, after the user + * checked that in ELSTER: each one is recorded as `not-received`, and one of its kind can be sent again. The api + * asks for a second factor like for transmit. Rejects with the error of the request when the api refuses it, like + * without such a transmission. + * @param fiscalYearId - The id of the fiscal year. + * @returns The records written, one for each such transmission. + */ + async recordNotReceived(fiscalYearId: string): Promise { + const url: string = this.resolveFiscalYearUrl(fiscalYearId, this.config.paths.transmissionNotReceived); + return await firstValueFrom(this.http.post(url, {})); + } + + /** + * Resolves whether the E-Bilanz of a fiscal year is filed: transmitted and accepted, or filed by hand. It makes the + * service a FiscalYearFilingResolver, which the dialog that reopens a fiscal year asks. + * @param fiscalYearId - The id of the fiscal year. + * @returns Whether it is filed. + */ + async resolveFiled(fiscalYearId: string): Promise { + return (await this.resolveState(fiscalYearId)).filed; + } + + /** + * Records the latest preparation as filed by hand, sent as the part `protocol` of a multipart body. Rejects with the + * error of the request when the api refuses it, like once it is filed. + * @param fiscalYearId - The id of the fiscal year. + * @param protocol - The transmission protocol of the program it was filed with. + * @returns The record of the filing. + */ + async recordManualFiling(fiscalYearId: string, protocol: File): Promise { + const body: FormData = new FormData(); + body.append('protocol', protocol, protocol.name); + const url: string = this.resolveFiscalYearUrl(fiscalYearId, this.config.paths.manualFiling); + return await firstValueFrom(this.http.post(url, body)); + } + + /** + * Loads the protocol of a record. + * @param protocol - The protocol, as the record names it, with the url it downloads from. + * @returns The protocol, with its name. + */ + async resolveProtocol(protocol: FileReference): Promise { + if (protocol.url == undefined) { + throw new Error(`The protocol ${protocol.name} has no url it downloads from.`); + } + return await this.resolveFile(protocol.url, {}, protocol.name); + } + + /** + * Loads whether the ELSTER certificate is uploaded. + * @returns When it was uploaded, never the certificate or its PIN. + */ + async resolveCertificateSettings(): Promise { + return await firstValueFrom(this.http.get(this.resolveUrl(this.config.paths.settings))); + } + + /** + * Replaces the ELSTER certificate and its PIN, sent as the parts `certificate` and `pin` of a multipart body. + * @param certificate - The .pfx file of Mein ELSTER. + * @param pin - Its PIN, which the api stores encrypted and never answers. + * @returns When it was uploaded. + */ + async updateCertificate(certificate: File, pin: string): Promise { + const body: FormData = new FormData(); + body.append('certificate', certificate, certificate.name); + body.append('pin', pin); + return await firstValueFrom(this.http.put(this.resolveUrl(this.config.paths.certificate), body)); + } + + /** + * Loads the accounts mapped to a position of their own. + * @returns Every mapping. + */ + async resolveAccountMappings(): Promise { + return await firstValueFrom(this.http.get(this.resolveUrl(this.config.paths.accountMappings))); + } + + /** + * Maps an account to a position of its own. Rejects with the error of the request when the api refuses it. + * @param accountId - The id of the account. + * @param change - The position, and the one of a credit balance. + * @returns The mapping. + */ + async updateAccountMapping(accountId: string, change: EBilanzAccountMappingChangeModel): Promise { + const url: string = this.resolveUrl(this.config.paths.accountMappings, accountId); + return await firstValueFrom(this.http.put(url, change)); + } + + /** + * Removes the mapping of an account, which then reports by its statement position again. + * @param accountId - The id of the account. + */ + async deleteAccountMapping(accountId: string): Promise { + await firstValueFrom(this.http.delete(this.resolveUrl(this.config.paths.accountMappings, accountId))); + } + + private async resolveFile(url: string, params: Record, fallbackName: string): Promise { + const response: HttpResponse = await firstValueFrom( + this.http.get(url, { params, responseType: 'blob', observe: 'response' }) + ); + // like the files of the books: a browser hides the header of another origin that didn't expose it. + const name: string = BookkeepingFileUtilities.findFileName(response.headers.get('content-disposition')) ?? fallbackName; + return { name, content: response.body ?? new Blob() }; + } + + private resolveFiscalYearUrl(fiscalYearId: string, subPath?: string): string { + return [ + this.resolveUrl(this.config.paths.fiscalYears, fiscalYearId), + ...subPath == undefined ? [] : [subPath] + ].join('/'); + } + + // the paths are the config's as they are, as one holds a slash, 'settings/certificate'. Only ids are encoded. + private resolveUrl(path: string, id?: string): string { + if (this.config.baseUrl == undefined) { + throw new Error('The EBilanzService needs the url of the E-Bilanz routes of your api. ' + + 'Add provideEBilanzConfig({ baseUrl }) to the providers of your app.'); + } + return [this.config.baseUrl, path, ...id == undefined ? [] : [encodeURIComponent(id)]].join('/'); + } +} diff --git a/projects/ngx-bookkeeping/api/fiscal-year-filing-resolver.model.ts b/projects/ngx-bookkeeping/api/fiscal-year-filing-resolver.model.ts new file mode 100644 index 0000000..9cad172 --- /dev/null +++ b/projects/ngx-bookkeeping/api/fiscal-year-filing-resolver.model.ts @@ -0,0 +1,13 @@ +/** + * Knows whether the accounts of a fiscal year are filed with the tax administration, like by an accepted E-Bilanz. A + * fiscal year whose accounts are filed is reopened only to correct them, which the dialog that reopens it asks for + * then. EBilanzService is one, for the E-Bilanz of this library. + */ +export type FiscalYearFilingResolver = { + /** + * Resolves whether the accounts of a fiscal year are filed. + * @param fiscalYearId - The id of the fiscal year. + * @returns Whether they are filed. + */ + resolveFiled: (fiscalYearId: string) => Promise +}; diff --git a/projects/ngx-bookkeeping/api/fiscal-year-filing-resolver.provider.ts b/projects/ngx-bookkeeping/api/fiscal-year-filing-resolver.provider.ts new file mode 100644 index 0000000..a1b8bc1 --- /dev/null +++ b/projects/ngx-bookkeeping/api/fiscal-year-filing-resolver.provider.ts @@ -0,0 +1,22 @@ +import { inject, InjectionToken, Provider, Type } from '@angular/core'; + +import { FiscalYearFilingResolver } from './fiscal-year-filing-resolver.model'; + +/** + * What the dialog that reopens a fiscal year asks whether its accounts are filed, undefined while none is provided. It + * then doesn't know, and lets the user say whether the reopening corrects filed accounts. + */ +export const FISCAL_YEAR_FILING_RESOLVER: InjectionToken = new InjectionToken< + FiscalYearFilingResolver | undefined +>('FISCAL_YEAR_FILING_RESOLVER', { providedIn: 'root', factory: () => undefined }); + +/** + * Tells the dialog that reopens a fiscal year whether its accounts are filed, like with the E-Bilanz of this library: + * `provideFiscalYearFilingResolver(EBilanzService)`. Provided where the fiscal years show, it keeps the fiscal years + * independent of the E-Bilanz, whose code only loads where it is provided. + * @param resolver - The injectable that knows, like EBilanzService. + * @returns The provider for FISCAL_YEAR_FILING_RESOLVER. + */ +export function provideFiscalYearFilingResolver(resolver: Type): Provider { + return { provide: FISCAL_YEAR_FILING_RESOLVER, useFactory: () => inject(resolver) }; +} diff --git a/projects/ngx-bookkeeping/api/ng-package.json b/projects/ngx-bookkeeping/api/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-bookkeeping/api/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-bookkeeping/api/public-api.ts b/projects/ngx-bookkeeping/api/public-api.ts new file mode 100644 index 0000000..492081b --- /dev/null +++ b/projects/ngx-bookkeeping/api/public-api.ts @@ -0,0 +1,37 @@ +export * from './bookkeeping-amount.utilities'; +export * from './bookkeeping-common-labels.model'; +export * from './bookkeeping-config-changes.model'; +export * from './bookkeeping-config.model'; +export * from './bookkeeping-config.provider'; +export * from './bookkeeping-day.utilities'; +export * from './bookkeeping-entry-form-labels.model'; +export * from './bookkeeping-file.model'; +export * from './bookkeeping-file.utilities'; +export * from './bookkeeping-fiscal-year.utilities'; +export * from './bookkeeping-fiscal-years-labels.model'; +export * from './bookkeeping-journal-labels.model'; +export * from './bookkeeping-labels-changes.model'; +export * from './bookkeeping-labels.model'; +export * from './bookkeeping-ledger-labels.model'; +export * from './bookkeeping-paths.model'; +export * from './bookkeeping-statement-labels.model'; +export * from './bookkeeping-trial-balance-labels.model'; +export * from './bookkeeping-view.directive'; +export * from './bookkeeping.service'; +export * from './e-bilanz-account-mappings-labels.model'; +export * from './e-bilanz-certificate-labels.model'; +export * from './e-bilanz-common-labels.model'; +export * from './e-bilanz-config-changes.model'; +export * from './e-bilanz-config.model'; +export * from './e-bilanz-config.provider'; +export * from './e-bilanz-correction-status.type'; +export * from './e-bilanz-filing-labels.model'; +export * from './e-bilanz-labels-changes.model'; +export * from './e-bilanz-labels.model'; +export * from './e-bilanz-paths.model'; +export * from './e-bilanz-preparation-labels.model'; +export * from './e-bilanz-records-labels.model'; +export * from './e-bilanz-review-labels.model'; +export * from './e-bilanz.service'; +export * from './fiscal-year-filing-resolver.model'; +export * from './fiscal-year-filing-resolver.provider'; diff --git a/projects/ngx-bookkeeping/balance-sheet/balance-sheet.component.html b/projects/ngx-bookkeeping/balance-sheet/balance-sheet.component.html new file mode 100644 index 0000000..f0a925c --- /dev/null +++ b/projects/ngx-bookkeeping/balance-sheet/balance-sheet.component.html @@ -0,0 +1 @@ + diff --git a/projects/ngx-bookkeeping/balance-sheet/balance-sheet.component.spec.ts b/projects/ngx-bookkeeping/balance-sheet/balance-sheet.component.spec.ts new file mode 100644 index 0000000..d53faf1 --- /dev/null +++ b/projects/ngx-bookkeeping/balance-sheet/balance-sheet.component.spec.ts @@ -0,0 +1,96 @@ +import { provideHttpClient } from '@angular/common/http'; +import { provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideBookkeepingConfig } from '@service-soft/ngx-bookkeeping/api'; +import { FakeAnswer } from 'testing/http'; +import { describe, expect, test } from 'vitest'; +import { BookkeepingStatementFormChoicesModel, BookkeepingStatementModel } from 'zibri-contract'; + +import { BookkeepingTestingUtilities } from '../fixtures/bookkeeping-testing.utilities'; +import { BALANCE_SHEET_2026, BALANCE_SHEET_WITH_UNMAPPED, BOOKKEEPING_BASE_URL, FISCAL_YEAR_IDS, STATEMENT_FORMS_2026, toJson } from '../fixtures/bookkeeping.fixtures'; +import { BalanceSheetComponent } from './balance-sheet.component'; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [BalanceSheetComponent] +}) +class HostComponent {} + +const FORMS_PATH: string = `fiscal-years/${FISCAL_YEAR_IDS.year2026}/statement-forms`; + +function getAnswers(statement: BookkeepingStatementModel, forms: BookkeepingStatementFormChoicesModel): Record { + return { + ...BookkeepingTestingUtilities.getBookAnswers(), + [`GET ${BOOKKEEPING_BASE_URL}/${FORMS_PATH}`]: { status: 200, body: toJson(forms) }, + [`GET ${BOOKKEEPING_BASE_URL}/reports/balance-sheet`]: { status: 200, body: toJson(statement) } + }; +} + +async function render( + statement: BookkeepingStatementModel, + forms: BookkeepingStatementFormChoicesModel = STATEMENT_FORMS_2026 +): Promise<[ComponentFixture, HTMLElement, TestRequest[]]> { + TestBed.configureTestingModule({ + providers: [provideHttpClient(), provideHttpClientTesting(), provideBookkeepingConfig({ baseUrl: BOOKKEEPING_BASE_URL })] + }); + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + const requests: TestRequest[] = await BookkeepingTestingUtilities.settle(fixture, getAnswers(statement, forms)); + return [fixture, fixture.nativeElement as HTMLElement, requests]; +} + +describe('BalanceSheetComponent', () => { + test('shows the positions by depth with the figures of the year before, the result, and that it is preliminary', async () => { + const [, root, requests] = await render(BALANCE_SHEET_2026); + + // in the form that applies to the fiscal year + expect(BookkeepingTestingUtilities.findRequest(requests, FORMS_PATH)).toBeDefined(); + expect(BookkeepingTestingUtilities.findRequest(requests, 'reports/balance-sheet')?.request.params.toString()) + .toBe(`fiscalYearId=${FISCAL_YEAR_IDS.year2026}&form=hgb.balance-sheet.micro`); + expect(root.querySelector('caption')?.textContent.trim()).toBe('Balance sheet'); + expect([...root.querySelectorAll('thead th')].map(header => header.textContent.trim())).toEqual(['Position', '12/31/2026', '12/31/2025']); + const rows: HTMLTableRowElement[] = [...root.querySelectorAll('tbody tr')]; + expect(rows.slice(0, 3).map(row => BookkeepingTestingUtilities.getText(row))).toEqual([ + 'Assets €14,640.00 €13,450.00', + 'Fixed assets €0.00 €0.00', + 'Current assets €14,640.00 €13,450.00' + ]); + // a position below another is indented, and one with positions below it set apart + expect(rows[0]?.querySelector('th')?.className).toContain('font-semibold'); + expect(rows[1]?.querySelector('th')?.className).toContain('ps-7'); + expect(BookkeepingTestingUtilities.getText(root.querySelector('ui-badge'))).toBe('Preliminary'); + expect(BookkeepingTestingUtilities.getText(root.querySelector('ui-data-list'))).toBe('Result of the fiscal year €1,000.00'); + expect(root.querySelector('ui-callout')).toBeNull(); + }); + + test('shows the accounts with a balance in none of its positions', async () => { + const [, root] = await render(BALANCE_SHEET_WITH_UNMAPPED); + + expect(BookkeepingTestingUtilities.getText(root.querySelector('ui-callout'))).toContain('Accounts without a position'); + expect(BookkeepingTestingUtilities.getText(root.querySelector('ui-callout ui-data-list'))).toBe('1360 Money in transit €120.00'); + }); + + test('offers the forms of the api, the one that applies to the fiscal year chosen and marked', async () => { + const [fixture, root] = await render(BALANCE_SHEET_2026); + + const combobox: HTMLElement | undefined = [...root.querySelectorAll('[role="combobox"]')].at(-1); + expect(combobox?.textContent.trim()) + .toBe('Shortened balance sheet of a micro corporation (§ 266 (1) sentence 4 HGB) (the form of the fiscal year)'); + await BookkeepingTestingUtilities.select(fixture, root, 'Form', 'Balance sheet (§ 266 HGB)'); + const requests: TestRequest[] = await BookkeepingTestingUtilities.settle(fixture, getAnswers(BALANCE_SHEET_2026, STATEMENT_FORMS_2026)); + + expect(BookkeepingTestingUtilities.findRequest(requests, 'reports/balance-sheet')?.request.params.toString()) + .toBe(`fiscalYearId=${FISCAL_YEAR_IDS.year2026}&form=hgb.balance-sheet`); + }); + + test('offers no choice for a statement with a single form', async () => { + const [, root] = await render(BALANCE_SHEET_2026, { + ...STATEMENT_FORMS_2026, + balanceSheet: { applies: 'hgb.balance-sheet', forms: [{ id: 'hgb.balance-sheet', name: 'Balance sheet (§ 266 HGB)' }] } + }); + + // the select of the fiscal year alone + expect(root.querySelectorAll('[role="combobox"]')).toHaveLength(1); + }); +}); diff --git a/projects/ngx-bookkeeping/balance-sheet/balance-sheet.component.ts b/projects/ngx-bookkeeping/balance-sheet/balance-sheet.component.ts new file mode 100644 index 0000000..68054a7 --- /dev/null +++ b/projects/ngx-bookkeeping/balance-sheet/balance-sheet.component.ts @@ -0,0 +1,22 @@ +import { Component } from '@angular/core'; +import { StatementComponent } from '@service-soft/ngx-bookkeeping/statement'; +import { BookkeepingStatementType } from 'zibri-contract'; + +/** + * The balance sheet of the books of provideBookkeepingConfig: ``. It shows the assets, equity and + * liabilities of a fiscal year, the one of today at first, by position, with the figures of the year before and the + * result of the year, and every account with a balance in none of its positions, in the form that applies to the + * fiscal year or another form of the api the user chooses. It downloads as a pdf. + */ +@Component({ + selector: 'ngx-balance-sheet', + templateUrl: './balance-sheet.component.html', + imports: [StatementComponent], + host: { class: 'block' } +}) +export class BalanceSheetComponent { + /** + * The statement it shows. + */ + protected readonly type: BookkeepingStatementType = BookkeepingStatementType.BALANCE_SHEET; +} diff --git a/projects/ngx-bookkeeping/balance-sheet/balance-sheet.stories.ts b/projects/ngx-bookkeeping/balance-sheet/balance-sheet.stories.ts new file mode 100644 index 0000000..dae287d --- /dev/null +++ b/projects/ngx-bookkeeping/balance-sheet/balance-sheet.stories.ts @@ -0,0 +1,75 @@ +import { Meta, StoryObj } from '@storybook/angular'; + +import { BookkeepingStoryUtilities } from '../fixtures/bookkeeping-story.utilities'; +import { BALANCE_SHEET_2026, BALANCE_SHEET_WITH_UNMAPPED, FISCAL_YEAR_IDS, STATEMENT_FORMS_2026 } from '../fixtures/bookkeeping.fixtures'; +import { BalanceSheetComponent } from './balance-sheet.component'; + +const BALANCE_SHEET: string = 'GET reports/balance-sheet'; + +// the forms of the api, offered with the one that applies to the fiscal year chosen. +const FORMS: string = `GET fiscal-years/${FISCAL_YEAR_IDS.year2026}/statement-forms`; + +const meta: Meta = { + title: 'Bookkeeping/Balance sheet', + component: BalanceSheetComponent, + render: () => ({ template: '' }) +}; +export default meta; + +type Story = StoryObj; + +export const Default: Story = { + decorators: [ + BookkeepingStoryUtilities.provideBackend({ + [FORMS]: BookkeepingStoryUtilities.getAnswer(STATEMENT_FORMS_2026), + [BALANCE_SHEET]: BookkeepingStoryUtilities.getAnswer(BALANCE_SHEET_2026) + }) + ] +}; + +export const Final: Story = { + decorators: [ + BookkeepingStoryUtilities.provideBackend({ + [FORMS]: BookkeepingStoryUtilities.getAnswer(STATEMENT_FORMS_2026), + [BALANCE_SHEET]: BookkeepingStoryUtilities.getAnswer({ ...BALANCE_SHEET_2026, closed: true }) + }) + ] +}; + +export const UnmappedAccounts: Story = { + decorators: [ + BookkeepingStoryUtilities.provideBackend({ + [FORMS]: BookkeepingStoryUtilities.getAnswer(STATEMENT_FORMS_2026), + [BALANCE_SHEET]: BookkeepingStoryUtilities.getAnswer(BALANCE_SHEET_WITH_UNMAPPED) + }) + ] +}; + +// a fiscal year whose balance sheet has a single form, so there is nothing to choose. +export const SingleForm: Story = { + decorators: [ + BookkeepingStoryUtilities.provideBackend({ + [FORMS]: BookkeepingStoryUtilities.getAnswer({ + ...STATEMENT_FORMS_2026, + balanceSheet: { applies: 'hgb.balance-sheet', forms: [{ id: 'hgb.balance-sheet', name: 'Balance sheet (§ 266 HGB)' }] } + }), + [BALANCE_SHEET]: BookkeepingStoryUtilities.getAnswer(BALANCE_SHEET_2026) + }) + ] +}; + +/* eslint-disable unicorn/no-null -- the api answers null for the year before the first fiscal year of the books */ +export const NoPreviousYear: Story = { + decorators: [ + BookkeepingStoryUtilities.provideBackend({ + [FORMS]: BookkeepingStoryUtilities.getAnswer(STATEMENT_FORMS_2026), + [BALANCE_SHEET]: BookkeepingStoryUtilities.getAnswer({ + ...BALANCE_SHEET_2026, + previousFiscalYearId: null, + previousEnd: null, + positions: BALANCE_SHEET_2026.positions.map(position => ({ ...position, previousAmount: null })) + }) + }) + ] +}; +/* eslint-enable unicorn/no-null */ diff --git a/projects/ngx-bookkeeping/balance-sheet/ng-package.json b/projects/ngx-bookkeeping/balance-sheet/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-bookkeeping/balance-sheet/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-bookkeeping/balance-sheet/public-api.ts b/projects/ngx-bookkeeping/balance-sheet/public-api.ts new file mode 100644 index 0000000..4630249 --- /dev/null +++ b/projects/ngx-bookkeeping/balance-sheet/public-api.ts @@ -0,0 +1 @@ +export * from './balance-sheet.component'; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-account-mappings.component.html b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-account-mappings.component.html new file mode 100644 index 0000000..00a4ab5 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-account-mappings.component.html @@ -0,0 +1,118 @@ +{{ labels.accountMappings }} +

{{ labels.accountMappingsText }}

+@if (loadingFailed()) { + +} +@if (unmappedAccounts().length) { + {{ labels.unmappedAccounts }} +
    + @for (account of unmappedAccounts(); track account.accountId) { + +
  • + {{ account.label }} + {{ account.balance }} + @if (canManage()) { + + } + {{ account.message }} +
  • + } +
+} +@if (mappingViews().length) { +
+ + + + + + + + @if (canManage()) { + + } + + + + @for (view of mappingViews(); track view.mapping.accountId) { + + + + + @if (canManage()) { + + } + + } + +
{{ labels.mappedAccounts }}
{{ commonLabels.account }}{{ labels.position }}{{ labels.creditPosition }}
{{ view.account }}{{ view.mapping.position }}{{ view.creditPosition }} +
+ + +
+
+
+} @else if (!loadingFailed()) { +

{{ labels.noMappings }}

+} +@if (canManage()) { + {{ labels.mapAccountTitle }} + + + + + @if (error(); as message) { + + } +
+ +
+
+} + +

{{ announcement() }}

diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-account-mappings.component.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-account-mappings.component.ts new file mode 100644 index 0000000..3613d58 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-account-mappings.component.ts @@ -0,0 +1,287 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { afterNextRender, Component, computed, ElementRef, inject, Injector, input, InputSignal, output, OutputEmitterRef, resource, ResourceRef, Signal, signal, viewChild, WritableSignal } from '@angular/core'; +import { + BOOKKEEPING_CONFIG, + BookkeepingAmountUtilities, + BookkeepingCommonLabels, + BookkeepingService, + E_BILANZ_CONFIG, + EBilanzAccountMappingsLabels, + EBilanzService +} from '@service-soft/ngx-bookkeeping/api'; +import { ErrorResponseUtilities } from '@service-soft/ngx-error-handling/error-response'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { FormComponent } from '@service-soft/ui/form'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { InputOption } from '@service-soft/ui/input'; +import { InputSelectComponent } from '@service-soft/ui/input-select'; +import { InputStringComponent } from '@service-soft/ui/input-string'; +import { ScrollRegionDirective } from '@service-soft/ui/scroll-region'; +import { BookkeepingAccountModel, BookkeepingTrialBalanceModel, EBilanzAccountMappingModel, EBilanzFindingModel } from 'zibri-contract'; + +import { EBilanzMappingView } from './e-bilanz-mapping-view.model'; +import { EBilanzUnmappedAccountView } from './e-bilanz-unmapped-account-view.model'; +import { EBilanzViewUtilities } from './e-bilanz-view.utilities'; + +// the form is headed one level below the mappings, and a heading of level 6 has no level below. +const SUB_LEVELS: Record = { 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 6 }; + +/** + * The accounts mapped to a position of the taxonomy of their own, and the accounts the findings say need a position, + * each with its balance at the end of the fiscal year. With `canManage` the user maps an account, changes a mapping or + * removes it, which the E-Bilanz then states when it is previewed again. Only used by the E-Bilanz. + */ +@Component({ + selector: 'ngx-e-bilanz-account-mappings', + templateUrl: './e-bilanz-account-mappings.component.html', + imports: [ButtonComponent, CalloutComponent, FormComponent, HeadingComponent, InputSelectComponent, InputStringComponent, ScrollRegionDirective], + host: { class: 'grid gap-3' } +}) +export class EBilanzAccountMappingsComponent { + private readonly eBilanzService: EBilanzService = inject(EBilanzService); + + private readonly bookkeepingService: BookkeepingService = inject(BookkeepingService); + + private readonly injector: Injector = inject(Injector); + + private readonly message: Signal | undefined> = viewChild>('message'); + + private readonly form: Signal | undefined> = viewChild('form', { read: ElementRef }); + + /** + * The accounts of the books. + */ + readonly accounts: InputSignal = input.required(); + + /** + * What the E-Bilanz needs, which names the accounts without a position by their number. + */ + readonly findings: InputSignal = input.required(); + + /** + * The id of the fiscal year, whose balances the accounts show, or undefined for none. + */ + readonly fiscalYearId: InputSignal = input.required(); + + /** + * Whether the user may map accounts. + */ + readonly canManage: InputSignal = input.required(); + + /** + * How amounts are written. + */ + readonly format: InputSignal = input.required(); + + /** + * The level of its heading. + */ + readonly headingLevel: InputSignal = input.required(); + + /** + * What the ids of the E-Bilanz start with, unique on the page. + */ + readonly idPrefix: InputSignal = input.required(); + + /** + * Emits once a mapping changed, after which the E-Bilanz is loaded again. + */ + readonly changed: OutputEmitterRef = output(); + + /** + * The texts of the account mappings. + */ + protected readonly labels: EBilanzAccountMappingsLabels = inject(E_BILANZ_CONFIG).labels.accountMappings; + + /** + * The texts several views show. + */ + protected readonly commonLabels: BookkeepingCommonLabels = inject(BOOKKEEPING_CONFIG).labels.common; + + /** + * The level of the heading of the form. + */ + protected readonly subLevel: Signal = computed(() => SUB_LEVELS[this.headingLevel()]); + + private readonly mappings: ResourceRef = resource({ + loader: async () => await this.eBilanzService.resolveAccountMappings() + }); + + /** + * Whether the mappings couldn't be loaded. + */ + protected readonly loadingFailed: Signal = computed(() => this.mappings.error() != undefined); + + private readonly accountsById: Signal> = computed(() => { + return new Map(this.accounts().map(account => [account.id, account])); + }); + + // the findings about an account, by the account they name. + private readonly accountFindings: Signal<[BookkeepingAccountModel, EBilanzFindingModel][]> = computed(() => { + const byNumber: Map = new Map(this.accounts().map(account => [account.number, account])); + return this.findings().flatMap((finding): [BookkeepingAccountModel, EBilanzFindingModel][] => { + const account: BookkeepingAccountModel | undefined = byNumber.get(finding.position ?? ''); + return account == undefined ? [] : [[account, finding]]; + }); + }); + + // only loaded while a finding names an account, whose balance it shows + private readonly trialBalance: ResourceRef = resource({ + params: () => this.accountFindings().length ? this.fiscalYearId() : undefined, + loader: async ({ params }) => await this.bookkeepingService.resolveTrialBalance(params, undefined) + }); + + /** + * The accounts the findings say need a position. + */ + protected readonly unmappedAccounts: Signal = computed(() => { + const trialBalance: BookkeepingTrialBalanceModel | undefined = this.trialBalance.hasValue() ? this.trialBalance.value() : undefined; + return this.accountFindings().map(([account, finding]) => { + const balance: string | undefined = trialBalance?.rows.find(row => row.account.id === account.id)?.balance; + const label: string = this.getAccountLabel(account); + return { + accountId: account.id, + id: EBilanzViewUtilities.getTargetId(this.idPrefix(), 'account', account.number), + label, + balance: balance == undefined ? '' : BookkeepingAmountUtilities.format(balance, this.format()), + message: finding.message, + mapLabel: this.labels.mapOf(label) + }; + }); + }); + + /** + * The accounts mapped to a position of their own, by number. + */ + protected readonly mappingViews: Signal = computed(() => { + const mappings: EBilanzAccountMappingModel[] = this.mappings.hasValue() ? this.mappings.value() ?? [] : []; + return mappings + .map(mapping => { + const account: BookkeepingAccountModel | undefined = this.accountsById().get(mapping.accountId); + const label: string = account == undefined ? mapping.accountId : this.getAccountLabel(account); + return { + mapping, + account: label, + creditPosition: mapping.creditPosition ?? '', + editLabel: this.labels.editOf(label), + removeLabel: this.labels.removeOf(label) + }; + }) + .sort((a, b) => a.account.localeCompare(b.account)); + }); + + /** + * The open accounts to map. + */ + protected readonly accountOptions: Signal[]> = computed(() => this.accounts() + .filter(account => account.closedAt == undefined) + .map(account => ({ label: this.getAccountLabel(account), value: account.id }))); + + /** + * The account to map. + */ + protected readonly accountId: WritableSignal = signal(undefined); + + /** + * The element name of the position it reports as. + */ + protected readonly position: WritableSignal = signal(''); + + /** + * The element name of the position of a credit balance, empty for the position. + */ + protected readonly creditPosition: WritableSignal = signal(''); + + /** + * Whether a mapping is being saved or removed. + */ + protected readonly sending: WritableSignal = signal(false); + + /** + * What the view last said about a mapping, or an empty string. + */ + protected readonly announcement: WritableSignal = signal(''); + + /** + * Why the api refused a mapping, or undefined while it refused none. + */ + protected readonly error: WritableSignal = signal(undefined); + + /** + * Fills the form with an account to map, and moves the focus to its position. + * @param accountId - The id of the account. + * @param mapping - Its mapping, to change it, or undefined for an account without one. + */ + protected edit(accountId: string, mapping: EBilanzAccountMappingModel | undefined): void { + this.accountId.set(accountId); + this.position.set(mapping?.position ?? ''); + this.creditPosition.set(mapping?.creditPosition ?? ''); + afterNextRender(() => this.form()?.nativeElement.querySelector('input[name="position"]')?.focus(), { injector: this.injector }); + } + + /** + * Maps the account of the form, which it only submits with an account and a position. + */ + protected async save(): Promise { + const accountId: string | undefined = this.accountId(); + if (accountId == undefined) { + return; + } + const creditPosition: string = this.creditPosition().trim(); + await this.send(this.labels.mapped(this.resolveAccountLabel(accountId)), async () => { + await this.eBilanzService.updateAccountMapping(accountId, { + position: this.position().trim(), + // eslint-disable-next-line unicorn/no-null -- the api takes null for the position of a credit balance it doesn't have + creditPosition: creditPosition === '' ? null : creditPosition + }); + this.accountId.set(undefined); + this.position.set(''); + this.creditPosition.set(''); + }); + } + + /** + * Removes the mapping of an account, which then reports by its statement position again. + * @param mapping - The mapping. + */ + protected async remove(mapping: EBilanzAccountMappingModel): Promise { + await this.send(this.labels.removed(this.resolveAccountLabel(mapping.accountId)), async () => { + await this.eBilanzService.deleteAccountMapping(mapping.accountId); + }); + } + + private async send(announcement: string, request: () => Promise): Promise { + this.sending.set(true); + this.announcement.set(''); + this.error.set(undefined); + try { + await request(); + this.mappings.reload(); + this.announcement.set(announcement); + this.changed.emit(); + // the button that had the focus can be gone with its mapping, and the message says what happened. + afterNextRender(() => this.message()?.nativeElement.focus(), { injector: this.injector }); + } + catch (error) { + // a refusal of the api is the answer, like for an account the books don't have. Anything else is a mistake, + // which goes on to the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.error.set(ErrorResponseUtilities.findMessage(error) ?? this.commonLabels.requestFailed); + } + finally { + this.sending.set(false); + } + } + + private resolveAccountLabel(accountId: string): string { + const account: BookkeepingAccountModel | undefined = this.accountsById().get(accountId); + return account == undefined ? accountId : this.getAccountLabel(account); + } + + private getAccountLabel(account: BookkeepingAccountModel): string { + return `${account.number} ${account.name}`; + } +} diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-account-view.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-account-view.model.ts new file mode 100644 index 0000000..ea50df5 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-account-view.model.ts @@ -0,0 +1,17 @@ +/** + * An account of a position, as the E-Bilanz shows it below the position. + */ +export type EBilanzAccountView = { + /** + * The number and the name of the account. + */ + label: string, + /** + * The classes of the cell of its label, indented one level below its position. + */ + labelClasses: string, + /** + * Its balance, formatted. + */ + balance: string +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-action-view.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-action-view.model.ts new file mode 100644 index 0000000..1bc90f1 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-action-view.model.ts @@ -0,0 +1,17 @@ +/** + * A button of the filing of the E-Bilanz, and why it is disabled. + */ +export type EBilanzActionView = { + /** + * Whether the button is disabled: for its reason, or while something is sent. + */ + disabled: boolean, + /** + * Why the button is disabled and how to enable it, or undefined while it is enabled. + */ + reason: string | undefined, + /** + * The id of the reason, which describes the button. + */ + reasonId: string +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-certificate.component.html b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-certificate.component.html new file mode 100644 index 0000000..91d2a27 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-certificate.component.html @@ -0,0 +1,41 @@ +{{ labels.certificate }} +

{{ labels.certificateText }}

+@if (loadingFailed()) { + +} @else { +

{{ status() }}

+} +@if (canManage()) { + + + + + @if (error(); as message) { + + } +
+ +
+
+} + +

{{ announcement() }}

diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-certificate.component.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-certificate.component.ts new file mode 100644 index 0000000..3739519 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-certificate.component.ts @@ -0,0 +1,149 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { afterNextRender, Component, computed, ElementRef, inject, Injector, input, InputSignal, LOCALE_ID, output, OutputEmitterRef, Signal, signal, viewChild, WritableSignal } from '@angular/core'; +import { + BOOKKEEPING_CONFIG, + BookkeepingCommonLabels, + BookkeepingConfig, + BookkeepingDayUtilities, + E_BILANZ_CONFIG, + EBilanzCertificateLabels, + EBilanzService +} from '@service-soft/ngx-bookkeeping/api'; +import { ErrorResponseUtilities } from '@service-soft/ngx-error-handling/error-response'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { FormComponent } from '@service-soft/ui/form'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { InputFileComponent, InputFileValue } from '@service-soft/ui/input-file'; +import { InputStringComponent } from '@service-soft/ui/input-string'; +import { EBilanzCertificateSettingsModel } from 'zibri-contract'; + +/** + * The ELSTER certificate the transmitter signs the E-Bilanz with: whether one is uploaded and since when, and with + * `canManage` uploading a new one with its PIN. The PIN is sent once and never shown again, and the input forgets it + * once the certificate is uploaded. Only used by the E-Bilanz, which loads whether one is uploaded. + */ +@Component({ + selector: 'ngx-e-bilanz-certificate', + templateUrl: './e-bilanz-certificate.component.html', + imports: [ButtonComponent, CalloutComponent, FormComponent, HeadingComponent, InputFileComponent, InputStringComponent], + host: { class: 'grid gap-3' } +}) +export class EBilanzCertificateComponent { + private readonly config: BookkeepingConfig = inject(BOOKKEEPING_CONFIG); + + private readonly eBilanzService: EBilanzService = inject(EBilanzService); + + private readonly locale: string = inject(LOCALE_ID); + + private readonly injector: Injector = inject(Injector); + + private readonly message: Signal | undefined> = viewChild>('message'); + + /** + * Whether a certificate is uploaded, undefined while it loads. + */ + readonly settings: InputSignal = input.required(); + + /** + * Whether it couldn't be loaded whether a certificate is uploaded. + */ + readonly loadingFailed: InputSignal = input.required(); + + /** + * Whether the user may upload the certificate. + */ + readonly canManage: InputSignal = input.required(); + + /** + * The level of its heading. + */ + readonly headingLevel: InputSignal = input.required(); + + /** + * Emits whether a certificate is uploaded once one was, after which the E-Bilanz is loaded again, which can be + * sent then. + */ + readonly uploaded: OutputEmitterRef = output(); + + /** + * The texts of the certificate. + */ + protected readonly labels: EBilanzCertificateLabels = inject(E_BILANZ_CONFIG).labels.certificate; + + /** + * The texts several views show. + */ + protected readonly commonLabels: BookkeepingCommonLabels = this.config.labels.common; + + /** + * Whether a certificate is uploaded and since when, or an empty string while that loads. + */ + protected readonly status: Signal = computed(() => { + const settings: EBilanzCertificateSettingsModel | undefined = this.settings(); + if (settings == undefined) { + return ''; + } + return settings.certificateUploadedAt == undefined + ? this.labels.noCertificate + : this.labels.uploadedAt(BookkeepingDayUtilities.formatMoment(new Date(settings.certificateUploadedAt), this.config.dateFormat, this.locale)); + }); + + /** + * The certificate the user chose. + */ + protected readonly files: WritableSignal = signal([]); + + /** + * Its PIN, which is only held until it is sent. + */ + protected readonly pin: WritableSignal = signal(''); + + /** + * Whether the certificate is being uploaded. + */ + protected readonly uploading: WritableSignal = signal(false); + + /** + * What the view last said about an upload, or an empty string. + */ + protected readonly announcement: WritableSignal = signal(''); + + /** + * Why the api refused the certificate, or undefined while it refused none. + */ + protected readonly error: WritableSignal = signal(undefined); + + /** + * Uploads the certificate with its PIN, which the form only submits with both. + */ + protected async upload(): Promise { + const certificate: File | undefined = this.files().find(file => file instanceof File); + if (certificate == undefined) { + return; + } + this.uploading.set(true); + this.announcement.set(''); + this.error.set(undefined); + try { + const settings: EBilanzCertificateSettingsModel = await this.eBilanzService.updateCertificate(certificate, this.pin()); + this.files.set([]); + this.pin.set(''); + this.announcement.set(this.labels.uploaded); + this.uploaded.emit(settings); + // the form starts over empty, and the message says what happened. + afterNextRender(() => this.message()?.nativeElement.focus(), { injector: this.injector }); + } + catch (error) { + // a refusal of the api is the answer, like for a PIN that is too short. Anything else is a mistake, which + // goes on to the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.error.set(ErrorResponseUtilities.findMessage(error) ?? this.commonLabels.requestFailed); + } + finally { + this.uploading.set(false); + } + } +} diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-content-tab.type.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-content-tab.type.ts new file mode 100644 index 0000000..cac066e --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-content-tab.type.ts @@ -0,0 +1,5 @@ +/** + * A tab of the content of an E-Bilanz: its balance sheet, its income statement with the appropriation of profits, or + * its statement of changes in fixed assets. + */ +export type EBilanzContentTab = 'balanceSheet' | 'incomeStatement' | 'fixedAssets'; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-content.component.html b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-content.component.html new file mode 100644 index 0000000..dbdd0a6 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-content.component.html @@ -0,0 +1,96 @@ +

{{ note() }}

+ +

{{ labels.nilText }}

+ + @for (statementTab of statementTabs(); track statementTab.value) { + +
+ @for (statement of statementTab.statements; track statement.name) { + +
+ + + + + + + + + + @for (position of statement.positions; track position.name) { + + + + + + @for (account of position.accounts; track $index) { + + + + + } + } + +
{{ statement.label }}
{{ labels.position }}{{ labels.amount }}
+ {{ position.label }} + {{ position.name }} + + @if (position.nil) { + {{ position.amount }} + } @else { + {{ position.amount }} + } +
{{ account.label }}{{ account.balance }}
+
+ } +
+
+ } + + @if (fixedAssets().length) { +
+ + + + + + @for (column of fixedAssetColumns(); track column.column) { + + } + + + + @for (row of fixedAssets(); track row.position) { + + + + @for (value of row.values; track value.column) { + + } + + } + +
{{ labels.fixedAssets }}
{{ labels.position }}{{ column.label }}
+ {{ row.label }} + {{ row.position }} + + @if (value.nil) { + {{ value.amount }} + } @else { + {{ value.amount }} + } +
+
+ } @else { +

{{ labels.noFixedAssets }}

+ } +
+
diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-content.component.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-content.component.ts new file mode 100644 index 0000000..56f222f --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-content.component.ts @@ -0,0 +1,194 @@ +import { Component, computed, inject, input, InputSignal, model, ModelSignal, Signal } from '@angular/core'; +import { BookkeepingAmountUtilities, E_BILANZ_CONFIG, EBilanzConfig, EBilanzReviewLabels } from '@service-soft/ngx-bookkeeping/api'; +import { DataListComponent, DataListItem } from '@service-soft/ui/data-list'; +import { ScrollRegionDirective } from '@service-soft/ui/scroll-region'; +import { TabComponent, TabsComponent } from '@service-soft/ui/tabs'; +import { EBilanzContentModel, EBilanzFixedAssetModel, EBilanzFixedAssetValueModel, EBilanzPositionModel } from 'zibri-contract'; + +import { EBilanzAccountView } from './e-bilanz-account-view.model'; +import { EBilanzContentTab } from './e-bilanz-content-tab.type'; +import { EBilanzFixedAssetView } from './e-bilanz-fixed-asset-view.model'; +import { EBilanzPositionView } from './e-bilanz-position-view.model'; +import { EBilanzStatementTabView } from './e-bilanz-statement-tab-view.model'; +import { EBilanzStatementView } from './e-bilanz-statement-view.model'; +import { EBilanzViewUtilities } from './e-bilanz-view.utilities'; + +// the label of a row, indented by its depth below the top, like the positions of a statement. Deeper rows keep the +// deepest indent. +const DEPTH_CLASSES: string[] = [ + 'py-2 pe-3 ps-3 text-start wrap-break-word', + 'py-2 pe-3 ps-7 text-start wrap-break-word', + 'py-2 pe-3 ps-11 text-start wrap-break-word', + 'py-2 pe-3 ps-15 text-start wrap-break-word', + 'py-2 pe-3 ps-19 text-start wrap-break-word', + 'py-2 pe-3 ps-23 text-start wrap-break-word', + 'py-2 pe-3 ps-27 text-start wrap-break-word' +]; + +// a row with rows below it adds them up, which reads best set apart from them. An account reads as a detail of its +// position. A header cell is bold otherwise. +const WEIGHT_CLASSES: Record<'sum' | 'position' | 'account', string> = { + sum: 'font-semibold', + position: 'font-normal', + account: 'font-normal text-on-surface-variant' +}; + +/** + * The content of an E-Bilanz: the version of its taxonomy, its balance sheet and its company, and a tab each for its + * balance sheet, its income statement with the appropriation of profits, and its statement of changes in fixed assets. + * Each position is indented by its depth with its amount, NIL for one the books don't state, and the accounts it is + * made of below it, and each row of the fixed assets by the row it is summed into. A finding links to the row of its + * position by its id, and the E-Bilanz opens its tab through `tab`. Only used by the E-Bilanz. + */ +@Component({ + selector: 'ngx-e-bilanz-content', + templateUrl: './e-bilanz-content.component.html', + imports: [DataListComponent, ScrollRegionDirective, TabComponent, TabsComponent], + host: { class: 'grid gap-4' } +}) +export class EBilanzContentComponent { + private readonly config: EBilanzConfig = inject(E_BILANZ_CONFIG); + + /** + * The content, of a preview or of the latest preparation. + */ + readonly content: InputSignal = input.required(); + + /** + * What the content is, like a preview, shown above it. + */ + readonly note: InputSignal = input.required(); + + /** + * How amounts are written. + */ + readonly format: InputSignal = input.required(); + + /** + * What the ids of its rows start with, unique on the page. + */ + readonly idPrefix: InputSignal = input.required(); + + /** + * The tab that shows, the balance sheet at first. + */ + readonly tab: ModelSignal = model('balanceSheet'); + + /** + * The texts of the content. + */ + protected readonly labels: EBilanzReviewLabels = this.config.labels.review; + + /** + * The version of its taxonomy, which balance sheet it states, and its company with its tax number. + */ + protected readonly facts: Signal = computed(() => { + const content: EBilanzContentModel = this.content(); + const accountingStandard: string = EBilanzViewUtilities.isAccountingStandard(content.accountingStandard) + ? this.config.labels.common.accountingStandards[content.accountingStandard] + : content.accountingStandard; + return [ + { label: this.labels.taxonomyVersion, value: content.taxonomyVersion }, + { label: this.labels.accountingStandard, value: accountingStandard }, + { label: this.labels.company, value: content.company.name }, + { label: this.labels.taxNumber, value: content.company.taxNumber } + ]; + }); + + /** + * The statements with their positions, in the order of the taxonomy. + */ + private readonly statements: Signal = computed(() => { + const positions: EBilanzPositionModel[] = this.content().positions; + const parents: Map = new Map(positions.map(position => [position.name, position.parent])); + const sums: Set = new Set(positions.map(position => position.parent ?? '')); + const statements: EBilanzStatementView[] = []; + for (const position of positions) { + let statement: EBilanzStatementView | undefined = statements.find(candidate => candidate.name === position.statement); + if (statement == undefined) { + statement = { name: position.statement, label: this.labels.statements[position.statement] ?? position.statement, positions: [] }; + statements.push(statement); + } + statement.positions.push(this.toPositionView(position, EBilanzViewUtilities.resolveDepth(position.name, parents), sums.has(position.name))); + } + return statements; + }); + + /** + * The tabs of the statements: the balance sheet, and the income statement with every other statement, like the + * appropriation of profits. Each is called by the label of its statement. + */ + protected readonly statementTabs: Signal = computed(() => { + const statements: EBilanzStatementView[] = this.statements(); + return [ + { + value: 'balanceSheet', + label: this.labels.statements['balanceSheet'] ?? 'balanceSheet', + statements: statements.filter(statement => statement.name === 'balanceSheet') + }, + { + value: 'incomeStatement', + label: this.labels.statements['incomeStatement'] ?? 'incomeStatement', + statements: statements.filter(statement => statement.name !== 'balanceSheet') + } + ]; + }); + + /** + * The columns of the statement of changes in fixed assets, those of its first row, as every row has the same. + */ + protected readonly fixedAssetColumns: Signal = computed(() => this.content().fixedAssets[0]?.values ?? []); + + /** + * The rows of the statement of changes in fixed assets, in the order of the taxonomy. + */ + protected readonly fixedAssets: Signal = computed(() => { + const rows: EBilanzFixedAssetModel[] = this.content().fixedAssets; + const parents: Map = new Map(rows.map(row => [row.position, row.parent])); + const sums: Set = new Set(rows.map(row => row.parent ?? '')); + return rows.map(row => ({ + position: row.position, + id: EBilanzViewUtilities.getTargetId(this.idPrefix(), 'fixed-asset', row.position), + label: row.label, + labelClasses: this.resolveLabelClasses(EBilanzViewUtilities.resolveDepth(row.position, parents), sums.has(row.position) ? 'sum' : 'position'), + values: this.fixedAssetColumns().map(({ column }) => { + const amount: string | null | undefined = row.values.find(value => value.column === column)?.amount; + return { column, amount: amount == undefined ? this.labels.nil : this.formatAmount(amount), nil: amount == undefined }; + }) + })); + }); + + /** + * Shows a tab, which ui-tabs names by its value. + * @param tab - The value of the tab, one of the tabs of the content. + */ + protected selectTab(tab: string | undefined): void { + if (tab === 'balanceSheet' || tab === 'incomeStatement' || tab === 'fixedAssets') { + this.tab.set(tab); + } + } + + private toPositionView(position: EBilanzPositionModel, depth: number, isSum: boolean): EBilanzPositionView { + return { + name: position.name, + id: EBilanzViewUtilities.getTargetId(this.idPrefix(), 'position', position.name), + label: position.label, + labelClasses: this.resolveLabelClasses(depth, isSum ? 'sum' : 'position'), + amount: position.amount == undefined ? this.labels.nil : this.formatAmount(position.amount), + nil: position.amount == undefined, + accounts: position.accounts.map((account): EBilanzAccountView => ({ + label: `${account.number} ${account.name}`, + labelClasses: this.resolveLabelClasses(depth + 1, 'account'), + balance: this.formatAmount(account.balance) + })) + }; + } + + private resolveLabelClasses(depth: number, weight: keyof typeof WEIGHT_CLASSES): string { + return `${DEPTH_CLASSES[Math.min(depth, DEPTH_CLASSES.length - 1)] ?? ''} ${WEIGHT_CLASSES[weight]}`; + } + + private formatAmount(amount: string): string { + return BookkeepingAmountUtilities.format(amount, this.format()); + } +} diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-exporter-view.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-exporter-view.model.ts new file mode 100644 index 0000000..bc14e83 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-exporter-view.model.ts @@ -0,0 +1,15 @@ +import { EBilanzExporterModel } from 'zibri-contract'; + +/** + * An exporter of the E-Bilanz with the text of its button. + */ +export type EBilanzExporterView = { + /** + * The exporter. + */ + exporter: EBilanzExporterModel, + /** + * The text of the button that downloads its file. + */ + label: string +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-figure-row-view.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-figure-row-view.model.ts new file mode 100644 index 0000000..8d2c346 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-figure-row-view.model.ts @@ -0,0 +1,23 @@ +import { EBilanzFigureView } from './e-bilanz-figure-view.model'; + +/** + * A row of the statement of changes in fixed assets whose figures the user enters, as the preparation shows it. + */ +export type EBilanzFigureRowView = { + /** + * The element name of its position. + */ + position: string, + /** + * The id of its group of inputs, which a finding links to. + */ + id: string, + /** + * The legend of the group, with the label of its position. + */ + legend: string, + /** + * The figures: those the books don't state, and those entered. + */ + figures: EBilanzFigureView[] +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-figure-view.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-figure-view.model.ts new file mode 100644 index 0000000..a499cc1 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-figure-view.model.ts @@ -0,0 +1,21 @@ +/** + * A figure of a row of the statement of changes in fixed assets the user can enter. + */ +export type EBilanzFigureView = { + /** + * The name of its column, like `grossCost.beginning`. + */ + column: string, + /** + * The German label of its column. + */ + label: string, + /** + * The name of its input, unique in the form. + */ + name: string, + /** + * The figure the user entered, or undefined for none. + */ + value: number | undefined +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-figures.type.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-figures.type.ts new file mode 100644 index 0000000..b2a114b --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-figures.type.ts @@ -0,0 +1,5 @@ +/** + * The figures of the statement of changes in fixed assets the user entered, by the position of their row, then by the + * name of their column. + */ +export type EBilanzFigures = Record>; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-filing-view.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-filing-view.model.ts new file mode 100644 index 0000000..f7fb0ae --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-filing-view.model.ts @@ -0,0 +1,43 @@ +import { FileReference } from 'zibri-contract'; + +/** + * A record of the E-Bilanz as it shows. + */ +export type EBilanzFilingView = { + /** + * The id of the record. + */ + id: string, + /** + * What it records. + */ + kind: string, + /** + * Which filing a preparation corrects and how, or an empty string for a record that corrects none. + */ + correction: string, + /** + * When it was recorded, formatted. + */ + recordedAt: string, + /** + * The ticket of a transmission, or an empty string for none. + */ + ticket: string, + /** + * Whether a transmission was accepted, or an empty string for a record that is no transmission. + */ + result: string, + /** + * What the tax administration answered. + */ + messages: string[], + /** + * The protocol, which downloads from its url, or undefined for none to download. + */ + protocol: FileReference | undefined, + /** + * The text of the button that downloads the protocol. + */ + downloadLabel: string +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-filing.component.html b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-filing.component.html new file mode 100644 index 0000000..d758053 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-filing.component.html @@ -0,0 +1,77 @@ +

{{ labels.filingText }}

+ +
+ @if (canTransmit()) { +
+ {{ labels.sendHeading }} +
+
+ +
+ @if (transmitAction().reason; as reason) { +

{{ reason }}

+ } +
+
+ } + @if (canPrepare() || canTransmit()) { +
+ {{ labels.manualHeading }} + @if (canPrepare()) { +
+
+ @for (view of exporters(); track view.exporter.name) { + + } @empty { + + } +
+ @if (exportAction().reason; as reason) { +

{{ reason }}

+ } + @if (downloadFailed()) { + + } +
+ } + @if (canTransmit()) { +
+
+ +
+ @if (manualFilingAction().reason; as reason) { +

{{ reason }}

+ } +
+ } +
+ } +
diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-filing.component.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-filing.component.ts new file mode 100644 index 0000000..8d76e3f --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-filing.component.ts @@ -0,0 +1,268 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { Component, computed, inject, input, InputSignal, LOCALE_ID, output, OutputEmitterRef, Signal, signal, WritableSignal } from '@angular/core'; +import { + BOOKKEEPING_CONFIG, + BookkeepingCommonLabels, + BookkeepingConfig, + BookkeepingDayUtilities, + BookkeepingFileUtilities, + E_BILANZ_CONFIG, + EBilanzConfig, + EBilanzFilingLabels, + EBilanzService +} from '@service-soft/ngx-bookkeeping/api'; +import { ErrorResponseUtilities } from '@service-soft/ngx-error-handling/error-response'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { ConfirmDialogComponent, ConfirmDialogData, DialogService } from '@service-soft/ui/dialog'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { EBilanzContentModel, EBilanzExporterModel, EBilanzFilingModel, EBilanzStateModel } from 'zibri-contract'; + +import { EBilanzActionView } from './e-bilanz-action-view.model'; +import { EBilanzExporterView } from './e-bilanz-exporter-view.model'; +import { EBilanzManualFilingDialogData } from './e-bilanz-manual-filing-dialog-data.model'; +import { EBilanzManualFilingDialogComponent } from './e-bilanz-manual-filing-dialog.component'; +import { EBilanzOutcome } from './e-bilanz-outcome.model'; +import { EBilanzViewUtilities } from './e-bilanz-view.utilities'; + +/** + * The step that files the latest preparation of an E-Bilanz, in one of two ways, each only once the user presses its + * button: sends it for real after confirming exactly what is sent, which is only possible after an accepted test of the + * same content, or downloads it with each exporter of the api and records it as filed by hand with its protocol, which + * needs no test. A button that can't be used is disabled with why and how to enable it, like while the app can't send + * it. With `canPrepare` it shows the downloads, with `canTransmit` the others. What happened is emitted on `outcome`. + * Only used by the E-Bilanz. + */ +@Component({ + selector: 'ngx-e-bilanz-filing', + templateUrl: './e-bilanz-filing.component.html', + imports: [ButtonComponent, HeadingComponent], + host: { class: 'grid gap-4' } +}) +export class EBilanzFilingComponent { + private readonly config: EBilanzConfig = inject(E_BILANZ_CONFIG); + + private readonly bookkeepingConfig: BookkeepingConfig = inject(BOOKKEEPING_CONFIG); + + private readonly eBilanzService: EBilanzService = inject(EBilanzService); + + private readonly dialogService: DialogService = inject(DialogService); + + private readonly locale: string = inject(LOCALE_ID); + + /** + * The E-Bilanz of the fiscal year. + */ + readonly state: InputSignal = input.required(); + + /** + * What the fiscal year is called, like '2025'. + */ + readonly fiscalYearLabel: InputSignal = input.required(); + + /** + * The first and the last day of the fiscal year, formatted. + */ + readonly period: InputSignal = input.required(); + + /** + * Whether the user may download the E-Bilanz. + */ + readonly canPrepare: InputSignal = input.required(); + + /** + * Whether the user may send it and record it as filed by hand. + */ + readonly canTransmit: InputSignal = input.required(); + + /** + * Whether to say that sending needs the certificate as well, to a user who uploads it. + */ + readonly certificateMissing: InputSignal = input.required(); + + /** + * The level of the headings of the two ways. + */ + readonly headingLevel: InputSignal = input.required(); + + /** + * What the ids of the E-Bilanz start with, unique on the page. + */ + readonly idPrefix: InputSignal = input.required(); + + /** + * Emits what a transmission or a filing by hand was answered with. + */ + readonly outcome: OutputEmitterRef = output(); + + /** + * The texts of filing the E-Bilanz. + */ + protected readonly labels: EBilanzFilingLabels = this.config.labels.filing; + + /** + * The texts several views show. + */ + protected readonly commonLabels: BookkeepingCommonLabels = this.bookkeepingConfig.labels.common; + + private readonly preparation: Signal = computed(() => EBilanzViewUtilities.findPreparation(this.state())); + + private readonly acceptedTest: Signal = computed(() => { + const preparation: EBilanzFilingModel | undefined = this.preparation(); + return preparation == undefined ? undefined : EBilanzViewUtilities.findAcceptedTest(this.state(), preparation); + }); + + private readonly preparationReason: Signal = computed(() => EBilanzViewUtilities.findPreparationReason(this.state(), this.config.labels)); + + /** + * The exporters of the api, each with its button. + */ + protected readonly exporters: Signal = computed(() => this.state().exporters.map(exporter => ({ + exporter, + label: this.labels.exportAs(exporter.name.toLocaleUpperCase(this.locale), exporter.fileExtension) + }))); + + /** + * Whether a file is downloading or something is sent. + */ + protected readonly sending: WritableSignal = signal(false); + + /** + * Whether sending for real is disabled, and why: while the app can't send it, it can't be filed, while a + * transmission runs or one for real may have been sent, and until a test of the same content was accepted. + */ + protected readonly transmitAction: Signal = computed(() => { + const untested: string | undefined = this.acceptedTest() == undefined ? this.labels.untestedReason : undefined; + const reason: string | undefined = EBilanzViewUtilities.findTransmitterReason(this.state(), this.config.labels, this.certificateMissing()) + ?? this.preparationReason() + ?? EBilanzViewUtilities.findTransmissionReason(this.state(), false, this.config.labels) + ?? untested; + return this.toAction(reason, 'transmit'); + }); + + /** + * Whether the downloads are disabled, and why. A filed E-Bilanz still downloads. Without an exporter, a single + * disabled button says why. + */ + protected readonly exportAction: Signal = computed(() => { + const preparation: EBilanzFilingModel | undefined = this.preparation(); + const reason: string | undefined = !this.state().exporters.length + ? this.labels.noExporters + : preparation == undefined ? this.config.labels.common.notPreparedReason : this.state().preparationCurrent ? undefined : this.config.labels.common.outdatedReason; + return this.toAction(reason, 'export'); + }); + + /** + * Whether recording a filing by hand is disabled, and why: it needs no test, but waits while a transmission runs, + * which the api refuses it during. + */ + protected readonly manualFilingAction: Signal = computed(() => { + const running: string | undefined = EBilanzViewUtilities.findRunningTransmission(this.state()) == undefined ? undefined : this.labels.runningReason; + return this.toAction(this.preparationReason() ?? running, 'manual-filing'); + }); + + /** + * Whether the last download failed. + */ + protected readonly downloadFailed: WritableSignal = signal(false); + + /** + * Downloads the latest preparation with an exporter, and saves it. + * @param exporter - The exporter. + */ + protected async downloadExport(exporter: EBilanzExporterModel): Promise { + this.sending.set(true); + this.downloadFailed.set(false); + try { + BookkeepingFileUtilities.save(await this.eBilanzService.resolveExport(this.state().fiscalYearId, exporter)); + } + catch (error) { + // a failed request is the answer to the download, anything else a mistake for the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.downloadFailed.set(true); + } + finally { + this.sending.set(false); + } + } + + /** + * Starts sending the latest preparation for real, once the user confirmed what is sent and that it is final, which + * the api sends in the background. The E-Bilanz shows its result once it has one. Nothing is sent when they cancel. + */ + protected async transmit(): Promise { + const question: ConfirmDialogData | undefined = this.resolveTransmissionQuestion(); + if (question == undefined) { + return; + } + const confirmed: boolean | undefined = await this.dialogService.open(ConfirmDialogComponent, question).closed; + if (confirmed !== true) { + return; + } + this.sending.set(true); + try { + // the api asks for the second factor of the user, which the interceptor of the auth of the app asks for + await this.eBilanzService.transmit(this.state().fiscalYearId); + this.outcome.emit({ kind: 'announcement', message: this.labels.sendingStarted, messages: [], recorded: true }); + } + catch (error) { + // a refusal of the api is the answer, like without a certificate, or a second factor the user didn't give. + // Anything else is a mistake, which goes on to the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.outcome.emit({ kind: 'error', message: ErrorResponseUtilities.findMessage(error) ?? this.commonLabels.requestFailed, messages: [], recorded: false }); + } + finally { + this.sending.set(false); + } + } + + /** + * Asks for the protocol of a filing by hand, and records it once the user confirms with one. + */ + protected async recordManualFiling(): Promise { + const data: EBilanzManualFilingDialogData = { fiscalYearId: this.state().fiscalYearId }; + const filing: EBilanzFilingModel | undefined = await this.dialogService + .open(EBilanzManualFilingDialogComponent, data) + .closed; + if (filing == undefined) { + return; + } + this.outcome.emit({ kind: 'announcement', message: this.labels.manuallyFiled, messages: [], recorded: true }); + } + + // what is sent, from the content of the latest preparation, which is what the api sends. + private resolveTransmissionQuestion(): ConfirmDialogData | undefined { + const content: EBilanzContentModel | null = this.state().content; + const preparation: EBilanzFilingModel | undefined = this.preparation(); + const test: EBilanzFilingModel | undefined = this.acceptedTest(); + if (content == undefined || preparation == undefined || test == undefined) { + return undefined; + } + const accountingStandard: string = EBilanzViewUtilities.isAccountingStandard(content.accountingStandard) + ? this.config.labels.common.accountingStandards[content.accountingStandard] + : content.accountingStandard; + return { + title: this.labels.transmissionTitle(this.fiscalYearLabel()), + paragraphs: [ + this.labels.transmissionContent(content.company.name, content.company.taxNumber, this.period(), this.formatMoment(preparation.createdAt)), + this.labels.transmissionStatement(content.positions.length, content.taxonomyVersion, accountingStandard), + this.labels.transmissionTest(this.formatMoment(test.createdAt), test.ticket ?? ''), + this.labels.transmissionFinal + ], + confirmButtonLabel: this.labels.confirmTransmission, + cancelButtonLabel: this.commonLabels.cancel, + confirmButtonColor: 'error' + }; + } + + private toAction(reason: string | undefined, name: string): EBilanzActionView { + return { disabled: this.sending() || reason != undefined, reason, reasonId: `${this.idPrefix()}-${name}-reason` }; + } + + private formatMoment(moment: string): string { + return BookkeepingDayUtilities.formatMoment(new Date(moment), this.bookkeepingConfig.dateFormat, this.locale); + } +} diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-filings.component.html b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-filings.component.html new file mode 100644 index 0000000..2dfd6dd --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-filings.component.html @@ -0,0 +1,56 @@ + + + {{ labels.records }} + +@if (downloadFailed()) { + +} +@if (views().length) { +
+ + + + + + + + + + + + + + @for (view of views(); track view.id) { + + + + + + + + + } + +
{{ labels.records }}
{{ labels.kind }}{{ labels.recordedAt }}{{ labels.ticket }}{{ labels.result }}{{ labels.messages }}{{ labels.protocol }}
+ {{ view.kind }} + @if (view.correction) { + {{ view.correction }} + } + {{ view.recordedAt }}{{ view.ticket }}{{ view.result }} + @for (message of view.messages; track $index) { +

{{ message }}

+ } +
+ @if (view.protocol; as protocol) { + + } +
+
+} @else { +

{{ labels.noRecords }}

+} diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-filings.component.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-filings.component.ts new file mode 100644 index 0000000..575bb04 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-filings.component.ts @@ -0,0 +1,132 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { Component, computed, ElementRef, inject, input, InputSignal, LOCALE_ID, Signal, signal, viewChild, WritableSignal } from '@angular/core'; +import { + BOOKKEEPING_CONFIG, + BookkeepingCommonLabels, + BookkeepingConfig, + BookkeepingDayUtilities, + BookkeepingFileUtilities, + E_BILANZ_CONFIG, + EBilanzPreparationLabels, + EBilanzRecordsLabels, + EBilanzService +} from '@service-soft/ngx-bookkeeping/api'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { ScrollRegionDirective } from '@service-soft/ui/scroll-region'; +import { EBilanzFilingModel, EBilanzRevisionStatus, FileReference } from 'zibri-contract'; + +import { EBilanzFilingView } from './e-bilanz-filing-view.model'; +import { EBilanzViewUtilities } from './e-bilanz-view.utilities'; + +/** + * The records of the E-Bilanz of a fiscal year, the earliest first: its preparations, tests, transmissions and filings + * by hand, each with when it was recorded, the ticket and the result of a transmission, what the tax administration + * answered, and its protocol to download. Only used by the E-Bilanz. + */ +@Component({ + selector: 'ngx-e-bilanz-filings', + templateUrl: './e-bilanz-filings.component.html', + imports: [ButtonComponent, HeadingComponent, ScrollRegionDirective], + host: { class: 'grid gap-3' } +}) +export class EBilanzFilingsComponent { + private readonly config: BookkeepingConfig = inject(BOOKKEEPING_CONFIG); + + private readonly eBilanzService: EBilanzService = inject(EBilanzService); + + private readonly locale: string = inject(LOCALE_ID); + + private readonly heading: Signal | undefined> = viewChild('heading', { read: ElementRef }); + + /** + * The records, the earliest first. + */ + readonly filings: InputSignal = input.required(); + + /** + * The level of its heading. + */ + readonly headingLevel: InputSignal = input.required(); + + /** + * The texts of the records. + */ + protected readonly labels: EBilanzRecordsLabels = inject(E_BILANZ_CONFIG).labels.records; + + private readonly preparationLabels: EBilanzPreparationLabels = inject(E_BILANZ_CONFIG).labels.preparation; + + /** + * The texts several views show. + */ + protected readonly commonLabels: BookkeepingCommonLabels = this.config.labels.common; + + /** + * The records as they show. + */ + protected readonly views: Signal = computed(() => this.filings().map(filing => this.toView(filing))); + + /** + * Whether the last protocol couldn't be downloaded. + */ + protected readonly downloadFailed: WritableSignal = signal(false); + + /** + * Moves the focus to the heading of the records, like once the E-Bilanz opened their tab. + */ + focusHeading(): void { + this.heading()?.nativeElement.focus(); + } + + /** + * Downloads a protocol and saves it. + * @param protocol - The protocol. + */ + protected async downloadProtocol(protocol: FileReference): Promise { + this.downloadFailed.set(false); + try { + BookkeepingFileUtilities.save(await this.eBilanzService.resolveProtocol(protocol)); + } + catch (error) { + // a failed request is the answer to the download, anything else a mistake for the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.downloadFailed.set(true); + } + } + + private toView(filing: EBilanzFilingModel): EBilanzFilingView { + // a protocol without a url has no route it downloads from, so only its name shows + const protocol: FileReference | undefined = filing.protocol?.url == undefined ? undefined : filing.protocol; + return { + id: filing.id, + kind: this.labels.kinds[filing.kind], + correction: this.resolveCorrection(filing), + recordedAt: this.formatMoment(filing.createdAt), + ticket: filing.ticket ?? '', + // the record a transmission started with is `transmitting`, those of its result say how it ended + result: filing.status == undefined ? '' : this.labels.statuses[filing.status], + messages: [...filing.messages, ...EBilanzViewUtilities.getErrorParagraphs(filing)], + protocol, + downloadLabel: this.labels.downloadProtocol(filing.protocol?.name ?? '') + }; + } + + // the filing a preparation corrects is one of the records, the earlier ones. + private resolveCorrection(filing: EBilanzFilingModel): string { + const corrected: EBilanzFilingModel | undefined = filing.correctsFilingId == undefined + ? undefined + : this.filings().find(candidate => candidate.id === filing.correctsFilingId); + if (corrected == undefined) { + return ''; + } + const revisionStatus: EBilanzRevisionStatus | null | undefined = filing.input?.revisionStatus; + const status: string = EBilanzViewUtilities.isCorrectionStatus(revisionStatus) ? this.preparationLabels.revisionStatuses[revisionStatus] : revisionStatus ?? ''; + return this.labels.corrects(this.labels.kinds[corrected.kind], this.formatMoment(corrected.createdAt), status); + } + + private formatMoment(moment: string): string { + return BookkeepingDayUtilities.formatMoment(new Date(moment), this.config.dateFormat, this.locale); + } +} diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-finding-target.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-finding-target.model.ts new file mode 100644 index 0000000..626287f --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-finding-target.model.ts @@ -0,0 +1,16 @@ +import { EBilanzContentTab } from './e-bilanz-content-tab.type'; + +/** + * The element a finding links to, and where the E-Bilanz shows it: the figures of a row of the statement of changes in + * fixed assets in the step that prepares it, a row of a tab of its content, or an account in the account mappings. + */ +export type EBilanzFindingTarget = { + /** + * The id of the element, which takes the focus once it shows. + */ + id: string, + /** + * Where it shows. + */ + place: EBilanzContentTab | 'figures' | 'account' +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-finding-view.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-finding-view.model.ts new file mode 100644 index 0000000..00abe9e --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-finding-view.model.ts @@ -0,0 +1,27 @@ +import { EBilanzFindingTarget } from './e-bilanz-finding-target.model'; + +/** + * A finding of the E-Bilanz as it shows. + */ +export type EBilanzFindingView = { + /** + * What it is about: the label of its position, the number of an account, or the whole E-Bilanz. + */ + subject: string, + /** + * The element name of its position, shown after its label, or an empty string when the subject is the name already. + */ + detail: string, + /** + * What needs to change, in the language of the api. + */ + message: string, + /** + * The element it is about, or undefined when the E-Bilanz doesn't show it. + */ + target: EBilanzFindingTarget | undefined, + /** + * The href of that element on the page, or an empty string for none. + */ + href: string +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-findings.component.html b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-findings.component.html new file mode 100644 index 0000000..0a9e74c --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-findings.component.html @@ -0,0 +1,21 @@ + +

{{ labels.findingsText }}

+
    + @for (finding of views(); track $index) { +
  • + + @if (finding.target; as target) { + + {{ finding.subject }} + } @else { + {{ finding.subject }} + } + + @if (finding.detail) { + ({{ finding.detail }}) + } + {{ finding.message }} +
  • + } +
+
diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-findings.component.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-findings.component.ts new file mode 100644 index 0000000..d225290 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-findings.component.ts @@ -0,0 +1,108 @@ +import { Location } from '@angular/common'; +import { Component, computed, inject, input, InputSignal, output, OutputEmitterRef, Signal } from '@angular/core'; +import { E_BILANZ_CONFIG, EBilanzConfig, EBilanzReviewLabels } from '@service-soft/ngx-bookkeeping/api'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { LinkComponent, LinkUtilities } from '@service-soft/ui/link'; +import { EBilanzContentModel, EBilanzFindingModel } from 'zibri-contract'; + +import { EBilanzFindingTarget } from './e-bilanz-finding-target.model'; +import { EBilanzFindingView } from './e-bilanz-finding-view.model'; +import { EBilanzViewUtilities } from './e-bilanz-view.utilities'; + +/** + * What the E-Bilanz needs before it can be prepared: each finding with what it is about, linked to it where the + * E-Bilanz shows it, and the message of the api. A finding about the statement of changes in fixed assets links to the + * figures of its row, one about a position to its row in the content, and one about an account to the account among + * those that need a position. A link emits on `chosen`, so the E-Bilanz opens the step or the tab the element is in. + * Only used by the E-Bilanz. + */ +@Component({ + selector: 'ngx-e-bilanz-findings', + templateUrl: './e-bilanz-findings.component.html', + imports: [CalloutComponent, LinkComponent], + host: { class: 'block' } +}) +export class EBilanzFindingsComponent { + private readonly config: EBilanzConfig = inject(E_BILANZ_CONFIG); + + private readonly location: Location = inject(Location); + + /** + * The findings. + */ + readonly findings: InputSignal = input.required(); + + /** + * The content they are of, whose positions they name, or undefined for none. + */ + readonly content: InputSignal = input.required(); + + /** + * The numbers of the accounts of the books, which a finding about an account names and links to. None while the + * E-Bilanz doesn't show the accounts to map, as the user may not map them. + */ + readonly accountNumbers: InputSignal> = input.required>(); + + /** + * What the ids of the E-Bilanz start with, unique on the page. + */ + readonly idPrefix: InputSignal = input.required(); + + /** + * Emits the element of a finding whose link the user follows. + */ + readonly chosen: OutputEmitterRef = output(); + + /** + * The texts of what the E-Bilanz needs. + */ + protected readonly labels: EBilanzReviewLabels = this.config.labels.review; + + /** + * The findings as they show. + */ + protected readonly views: Signal = computed(() => { + const content: EBilanzContentModel | undefined = this.content(); + const labels: Map = new Map([ + ...(content?.positions ?? []).map((position): [string, string] => [position.name, position.label]), + ...(content?.fixedAssets ?? []).map((row): [string, string] => [row.position, row.label]) + ]); + return this.findings().map(finding => { + const name: string = finding.position ?? ''; + const label: string | undefined = labels.get(name); + const target: EBilanzFindingTarget | undefined = this.findTarget(name, content); + return { + subject: finding.position == undefined ? this.labels.wholeFinding : label ?? name, + detail: label == undefined ? '' : name, + message: finding.message, + target, + href: target == undefined ? '' : LinkUtilities.resolveFragmentHref(this.location, target.id) + }; + }); + }); + + // the element that lets the user change what the finding asks for comes first: the figures of a row, then the row + // of a position or of the fixed assets, then the account to map. + private findTarget(name: string, content: EBilanzContentModel | undefined): EBilanzFindingTarget | undefined { + const prefix: string = this.idPrefix(); + if (content == undefined) { + return this.findAccountTarget(prefix, name); + } + if (EBilanzViewUtilities.findFigurePositions(content, this.findings()).has(name)) { + return { id: EBilanzViewUtilities.getTargetId(prefix, 'figures', name), place: 'figures' }; + } + const statement: string | undefined = content.positions.find(position => position.name === name)?.statement; + if (statement != undefined) { + const place: EBilanzFindingTarget['place'] = statement === 'balanceSheet' ? 'balanceSheet' : 'incomeStatement'; + return { id: EBilanzViewUtilities.getTargetId(prefix, 'position', name), place }; + } + if (content.fixedAssets.some(row => row.position === name)) { + return { id: EBilanzViewUtilities.getTargetId(prefix, 'fixed-asset', name), place: 'fixedAssets' }; + } + return this.findAccountTarget(prefix, name); + } + + private findAccountTarget(prefix: string, name: string): EBilanzFindingTarget | undefined { + return this.accountNumbers().has(name) ? { id: EBilanzViewUtilities.getTargetId(prefix, 'account', name), place: 'account' } : undefined; + } +} diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-fixed-asset-value-view.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-fixed-asset-value-view.model.ts new file mode 100644 index 0000000..fec1d62 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-fixed-asset-value-view.model.ts @@ -0,0 +1,17 @@ +/** + * A value of a row of the statement of changes in fixed assets, as it shows. + */ +export type EBilanzFixedAssetValueView = { + /** + * The name of its column, like `grossCost.beginning`. + */ + column: string, + /** + * The amount, formatted, or the text of NIL for one the books don't state. + */ + amount: string, + /** + * Whether the books don't state it. + */ + nil: boolean +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-fixed-asset-view.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-fixed-asset-view.model.ts new file mode 100644 index 0000000..2ee3af8 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-fixed-asset-view.model.ts @@ -0,0 +1,27 @@ +import { EBilanzFixedAssetValueView } from './e-bilanz-fixed-asset-value-view.model'; + +/** + * A row of the statement of changes in fixed assets as it shows. + */ +export type EBilanzFixedAssetView = { + /** + * The element name of its position. + */ + position: string, + /** + * The id of the row, which a finding links to. + */ + id: string, + /** + * The German label of its position. + */ + label: string, + /** + * The classes of the cell of its label, indented by the rows it is summed into. + */ + labelClasses: string, + /** + * The value of each column, in the order of the columns. + */ + values: EBilanzFixedAssetValueView[] +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-manual-filing-dialog-data.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-manual-filing-dialog-data.model.ts new file mode 100644 index 0000000..f1f6936 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-manual-filing-dialog-data.model.ts @@ -0,0 +1,9 @@ +/** + * The E-Bilanz the dialog records as filed by hand. + */ +export type EBilanzManualFilingDialogData = { + /** + * The id of its fiscal year. + */ + fiscalYearId: string +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-manual-filing-dialog.component.html b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-manual-filing-dialog.component.html new file mode 100644 index 0000000..9abf3ad --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-manual-filing-dialog.component.html @@ -0,0 +1,16 @@ + +

{{ labels.manualFilingTitle }}

+

{{ labels.manualFilingText }}

+ + @if (error(); as message) { +
+ +

{{ message }}

+
+ } + +
+ + +
+
diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-manual-filing-dialog.component.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-manual-filing-dialog.component.ts new file mode 100644 index 0000000..f091bb9 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-manual-filing-dialog.component.ts @@ -0,0 +1,87 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { Component, inject, signal, WritableSignal } from '@angular/core'; +import { BOOKKEEPING_CONFIG, BookkeepingCommonLabels, E_BILANZ_CONFIG, EBilanzFilingLabels, EBilanzService } from '@service-soft/ngx-bookkeeping/api'; +import { ErrorResponseUtilities } from '@service-soft/ngx-error-handling/error-response'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { DIALOG_DATA, DialogRef } from '@service-soft/ui/dialog'; +import { FormComponent } from '@service-soft/ui/form'; +import { InputFileComponent, InputFileValue } from '@service-soft/ui/input-file'; +import { EBilanzFilingModel } from 'zibri-contract'; + +import { EBilanzManualFilingDialogData } from './e-bilanz-manual-filing-dialog-data.model'; + +/** + * Asks for the transmission protocol of an E-Bilanz filed with another program, and records it as filed by hand once + * the user confirms with the protocol, which is required. It stays open with the message of the api when the api + * refuses, like for an E-Bilanz filed already, and closes with the record once it is recorded. Only used by the + * E-Bilanz. + */ +@Component({ + selector: 'ngx-e-bilanz-manual-filing-dialog', + templateUrl: './e-bilanz-manual-filing-dialog.component.html', + imports: [ButtonComponent, CalloutComponent, FormComponent, InputFileComponent] +}) +export class EBilanzManualFilingDialogComponent { + private readonly eBilanzService: EBilanzService = inject(EBilanzService); + + /** + * The E-Bilanz to record. + */ + protected readonly data: EBilanzManualFilingDialogData = inject(DIALOG_DATA); + + /** + * The dialog, to close it with the record. + */ + protected readonly dialogRef: DialogRef = inject>(DialogRef); + + /** + * The texts of filing the E-Bilanz. + */ + protected readonly labels: EBilanzFilingLabels = inject(E_BILANZ_CONFIG).labels.filing; + + /** + * The texts several views show. + */ + protected readonly commonLabels: BookkeepingCommonLabels = inject(BOOKKEEPING_CONFIG).labels.common; + + /** + * The protocol the user chose. + */ + protected readonly files: WritableSignal = signal([]); + + /** + * Whether the filing is being recorded. + */ + protected readonly recording: WritableSignal = signal(false); + + /** + * Why the api refused the filing, its paragraphs one per line, or undefined while it refused none. + */ + protected readonly error: WritableSignal = signal(undefined); + + /** + * Records the E-Bilanz as filed by hand, which the form only submits with a protocol. + */ + protected async record(): Promise { + const protocol: File | undefined = this.files().find(file => file instanceof File); + if (protocol == undefined) { + return; + } + this.recording.set(true); + this.error.set(undefined); + try { + this.dialogRef.close(await this.eBilanzService.recordManualFiling(this.data.fiscalYearId, protocol)); + } + catch (error) { + // a refusal of the api is the answer to the filing, anything else a mistake for the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.error.set(ErrorResponseUtilities.findMessage(error) ?? this.commonLabels.requestFailed); + } + finally { + this.recording.set(false); + } + } +} diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-mapping-view.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-mapping-view.model.ts new file mode 100644 index 0000000..88e5a30 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-mapping-view.model.ts @@ -0,0 +1,27 @@ +import { EBilanzAccountMappingModel } from 'zibri-contract'; + +/** + * An account mapped to a position of its own, as the account mappings show it. + */ +export type EBilanzMappingView = { + /** + * The mapping. + */ + mapping: EBilanzAccountMappingModel, + /** + * The number and the name of the account. + */ + account: string, + /** + * The position of a credit balance, or an empty string for the position. + */ + creditPosition: string, + /** + * The name of the button that edits it. + */ + editLabel: string, + /** + * The name of the button that removes it. + */ + removeLabel: string +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-outcome.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-outcome.model.ts new file mode 100644 index 0000000..3240e1e --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-outcome.model.ts @@ -0,0 +1,22 @@ +/** + * What a step of filing the E-Bilanz says once a request the user sent was answered, which the E-Bilanz shows above + * its steps. + */ +export type EBilanzOutcome = { + /** + * Whether it is said, refused by the tax administration with its messages, or refused by the api. + */ + kind: 'announcement' | 'refusal' | 'error', + /** + * What happened. The paragraphs of a message of the api are one per line. + */ + message: string, + /** + * What the tax administration answered, none for an announcement or an error. + */ + messages: string[], + /** + * Whether a record was made, after which the E-Bilanz is loaded again. + */ + recorded: boolean +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-phase.type.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-phase.type.ts new file mode 100644 index 0000000..4062d1f --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-phase.type.ts @@ -0,0 +1,5 @@ +/** + * How far the E-Bilanz of a fiscal year is filed, which step of filing it opens at: not prepared, prepared before the + * books changed, prepared, prepared with an accepted test of the same content, or filed. + */ +export type EBilanzPhase = 'unprepared' | 'outdated' | 'prepared' | 'tested' | 'filed'; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-position-view.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-position-view.model.ts new file mode 100644 index 0000000..9beecef --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-position-view.model.ts @@ -0,0 +1,35 @@ +import { EBilanzAccountView } from './e-bilanz-account-view.model'; + +/** + * A position of the E-Bilanz as it shows. + */ +export type EBilanzPositionView = { + /** + * The element name of the position, like `bs.ass.currAss.cashEquiv.bank`. + */ + name: string, + /** + * The id of its row, which a finding links to. + */ + id: string, + /** + * Its German label. + */ + label: string, + /** + * The classes of the cell of its label: indented by its depth, and bold for a position with positions below it. + */ + labelClasses: string, + /** + * Its amount, formatted, or the text of NIL for one the books don't state. + */ + amount: string, + /** + * Whether the books don't state it. + */ + nil: boolean, + /** + * The accounts its amount is made of. + */ + accounts: EBilanzAccountView[] +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-preparation.component.html b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-preparation.component.html new file mode 100644 index 0000000..4d2440e --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-preparation.component.html @@ -0,0 +1,81 @@ +

{{ labels.preparationText }}

+
+ + @if (filed()) { + + } + @if (figureRows().length) { + {{ labels.fixedAssetFigures }} +

{{ labels.fixedAssetFiguresText }}

+ @for (row of figureRows(); track row.position) { + +
+ {{ row.legend }} + @for (figure of row.figures; track figure.column) { + + } +
+ } + } + @if (error(); as message) { +
+ +

{{ message }}

+
+ } + +
+ + @if (canPrepare()) { + + } +
+ @if (previewReason(); as reason) { +

{{ reason }}

+ } + @if (canPrepare() && prepareReason(); as reason) { +

{{ reason }}

+ } + +

{{ announcement() }}

+
diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-preparation.component.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-preparation.component.ts new file mode 100644 index 0000000..561650b --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-preparation.component.ts @@ -0,0 +1,364 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { Component, computed, inject, input, InputSignal, linkedSignal, model, ModelSignal, output, OutputEmitterRef, Signal, signal, untracked, WritableSignal } from '@angular/core'; +import { + BOOKKEEPING_CONFIG, + BookkeepingAmountUtilities, + BookkeepingCommonLabels, + E_BILANZ_CONFIG, + EBilanzConfig, + EBilanzCorrectionStatus, + EBilanzPreparationLabels, + EBilanzService +} from '@service-soft/ngx-bookkeeping/api'; +import { ErrorResponseUtilities } from '@service-soft/ngx-error-handling/error-response'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { InputOption } from '@service-soft/ui/input'; +import { InputCardOption, InputCardsComponent } from '@service-soft/ui/input-cards'; +import { InputNumberComponent } from '@service-soft/ui/input-number'; +import { InputSelectComponent } from '@service-soft/ui/input-select'; +import { + EBilanzAccountingStandard, + EBilanzContentModel, + EBilanzFilingModel, + EBilanzFindingModel, + EBilanzFixedAssetInputModel, + EBilanzPreparationInputModel, + EBilanzPreviewModel, + EBilanzRevisionStatus, + EBilanzStateModel +} from 'zibri-contract'; + +import { EBilanzFigureRowView } from './e-bilanz-figure-row-view.model'; +import { EBilanzFigures } from './e-bilanz-figures.type'; +import { EBilanzViewUtilities } from './e-bilanz-view.utilities'; + +/** + * The step that prepares the E-Bilanz of a fiscal year, in two parts the user takes: the preview with the balance + * sheet the user chooses, of which there is no default, and the figures of the statement of changes in fixed assets + * the findings ask for, and then the preparation of exactly what was previewed, once it needs nothing more. The + * preview emits on `preview`, so the E-Bilanz shows its content and its findings, and the preparation on `prepared`. + * Once the E-Bilanz is filed, a preparation corrects it, and the user chooses what it corrects as well, which has no + * default either. Its controls belong to the form of the step, so it has no form of its own. Only used by the + * E-Bilanz. + */ +@Component({ + selector: 'ngx-e-bilanz-preparation', + templateUrl: './e-bilanz-preparation.component.html', + imports: [ButtonComponent, CalloutComponent, HeadingComponent, InputCardsComponent, InputNumberComponent, InputSelectComponent], + host: { class: 'grid gap-3' } +}) +export class EBilanzPreparationComponent { + private readonly config: EBilanzConfig = inject(E_BILANZ_CONFIG); + + private readonly eBilanzService: EBilanzService = inject(EBilanzService); + + /** + * The E-Bilanz of the fiscal year. + */ + readonly state: InputSignal = input.required(); + + /** + * The last preview, undefined before the first, which the E-Bilanz shows in place of its latest preparation. + */ + readonly preview: ModelSignal = model(); + + /** + * Whether the user may prepare the E-Bilanz. A preview needs no more than reading it. + */ + readonly canPrepare: InputSignal = input.required(); + + /** + * How amounts are written, whose decimals the figures have. + */ + readonly format: InputSignal = input.required(); + + /** + * The level of the heading of the figures. + */ + readonly headingLevel: InputSignal = input.required(); + + /** + * What the ids of the E-Bilanz start with, unique on the page. + */ + readonly idPrefix: InputSignal = input.required(); + + /** + * Emits the record of the preparation. + */ + readonly prepared: OutputEmitterRef = output(); + + /** + * The texts of the step. + */ + protected readonly labels: EBilanzPreparationLabels = this.config.labels.preparation; + + /** + * The texts several views show. + */ + protected readonly commonLabels: BookkeepingCommonLabels = inject(BOOKKEEPING_CONFIG).labels.common; + + /** + * The id of why the E-Bilanz can't be previewed, which describes the button. + */ + protected readonly previewReasonId: Signal = computed(() => `${this.idPrefix()}-preview-reason`); + + /** + * The id of why the E-Bilanz can't be prepared, which describes the button. + */ + protected readonly prepareReasonId: Signal = computed(() => `${this.idPrefix()}-prepare-reason`); + + /** + * The balance sheets to choose from. + */ + protected readonly accountingStandardOptions: InputOption[] = EBilanzViewUtilities.getAccountingStandards() + .map(standard => ({ label: this.config.labels.common.accountingStandards[standard], value: standard })); + + private readonly fiscalYearId: Signal = computed(() => this.state().fiscalYearId); + + // what the inputs start from: what the latest preparation of the fiscal year took + private readonly preparationKey: Signal = computed(() => `${this.fiscalYearId()} ${this.state().preparationId ?? ''}`); + + /** + * Which balance sheet the E-Bilanz states. There is no default, as both are legitimate: the user chooses, again for + * every fiscal year. Once it is prepared, it is the one the user chose for the preparation. + */ + // the select belongs to the form of the step, whose button that goes on would ask for a balance sheet again after + // the E-Bilanz was prepared with one. Read untracked: the state loads again after every change, like a mapping, + // which would drop what the user chose. + protected readonly accountingStandard: WritableSignal = linkedSignal< + string, + EBilanzAccountingStandard | undefined + >({ source: this.preparationKey, computation: () => untracked(() => this.findPreparedAccountingStandard()) }); + + /** + * Whether the E-Bilanz is filed, so a preparation corrects it and says how. + */ + protected readonly filed: Signal = computed(() => this.state().filed); + + /** + * How a correction can correct the filed E-Bilanz, each with when it applies. + */ + protected readonly revisionStatusOptions: InputCardOption[] = EBilanzViewUtilities.getCorrectionStatuses() + .map(status => ({ label: this.labels.revisionStatuses[status], value: status, description: this.labels.revisionStatusDescriptions[status] })); + + /** + * What a correction corrects. There is no default, as only the user knows: the books can't tell a fixed error from a + * changed choice. Once a correction is prepared, it is the one the user chose for it. + */ + // read untracked like the balance sheet, which would drop what the user chose. + protected readonly revisionStatus: WritableSignal = linkedSignal({ + source: this.preparationKey, + computation: () => untracked(() => this.findPreparedRevisionStatus()) + }); + + /** + * The figures the user entered, those of the latest preparation at first. + */ + // read untracked like the balance sheet, which would drop what the user entered. + private readonly figures: WritableSignal = linkedSignal({ + source: this.preparationKey, + computation: () => untracked(() => this.resolvePreparedFigures()) + }); + + /** + * The step of the inputs of the figures, the minor unit of the currency. + */ + protected readonly figureStep: Signal = computed(() => 10 ** -BookkeepingAmountUtilities.resolveFractionDigits(this.format())); + + private readonly content: Signal = computed(() => this.preview()?.content ?? this.state().content ?? undefined); + + private readonly findings: Signal = computed(() => this.preview()?.findings ?? this.state().findings); + + /** + * The rows whose figures the user enters: those a finding asks figures of, and those with figures entered. Each + * shows the columns the books don't state, and those entered. + */ + protected readonly figureRows: Signal = computed(() => { + const content: EBilanzContentModel | undefined = this.content(); + if (content == undefined) { + return []; + } + const named: Set = EBilanzViewUtilities.findFigurePositions(content, this.findings()); + const figures: EBilanzFigures = this.figures(); + return content.fixedAssets + .filter(row => named.has(row.position) || figures[row.position] != undefined) + .map(row => ({ + position: row.position, + id: EBilanzViewUtilities.getTargetId(this.idPrefix(), 'figures', row.position), + legend: this.labels.figuresOf(row.label), + figures: row.values + .filter(value => value.amount == undefined || figures[row.position]?.[value.column] != undefined) + .map(value => ({ + column: value.column, + label: value.label, + name: `${row.position}:${value.column}`, + value: figures[row.position]?.[value.column] + })) + })); + }); + + /** + * What a preview and a preparation send now, undefined until the user chose the balance sheet, and for a filed + * E-Bilanz what the correction corrects, which the api requires then and refuses before. + */ + private readonly preparationInput: Signal = computed(() => { + const accountingStandard: EBilanzAccountingStandard | undefined = this.accountingStandard(); + const revisionStatus: EBilanzCorrectionStatus | undefined = this.revisionStatus(); + if (accountingStandard == undefined || (this.filed() && revisionStatus == undefined)) { + return undefined; + } + const fractionDigits: number = BookkeepingAmountUtilities.resolveFractionDigits(this.format()); + const fixedAssets: EBilanzFixedAssetInputModel[] = Object.entries(this.figures()).map(([position, columns]) => ({ + position, + values: Object.entries(columns).map(([column, amount]) => ({ + column, + amount: BookkeepingAmountUtilities.resolveDecimal(BookkeepingAmountUtilities.resolveMinorUnits(amount, fractionDigits), fractionDigits) + })) + })); + return this.filed() ? { accountingStandard, fixedAssets, revisionStatus } : { accountingStandard, fixedAssets }; + }); + + // what was previewed, which is exactly what a preparation sends. It starts over with another fiscal year. + private readonly previewedInput: WritableSignal = linkedSignal({ + source: this.fiscalYearId, + computation: () => undefined + }); + + /** + * Whether a preview or a preparation is being sent. + */ + protected readonly sending: WritableSignal = signal(false); + + /** + * Why the E-Bilanz can't be previewed now, or undefined when it can: without a balance sheet, and for a correction + * without what it corrects, which its content states. + */ + protected readonly previewReason: Signal = computed(() => { + if (this.accountingStandard() == undefined) { + return this.labels.accountingStandardMissing; + } + return this.filed() && this.revisionStatus() == undefined ? this.labels.revisionStatusMissing : undefined; + }); + + /** + * Whether the button that previews waits: while something is sent, or the E-Bilanz can't be previewed. + */ + protected readonly previewDisabled: Signal = computed(() => this.sending() || this.previewReason() != undefined); + + /** + * Why the E-Bilanz can't be prepared now, or undefined when it can: without a preview of what the step holds, or + * while that preview needs something. + */ + protected readonly prepareReason: Signal = computed(() => { + const preview: EBilanzPreviewModel | undefined = this.preview(); + if (preview == undefined || this.previewedInput() == undefined || this.previewedInput() !== JSON.stringify(this.preparationInput())) { + return this.labels.previewMissing; + } + return preview.findings.length ? this.labels.previewHasFindings : undefined; + }); + + /** + * Whether the button that prepares waits: while something is sent, or the E-Bilanz can't be prepared. + */ + protected readonly prepareDisabled: Signal = computed(() => this.sending() || this.prepareReason() != undefined); + + /** + * What the view last said about a preview, or an empty string. It starts over with another fiscal year. + */ + protected readonly announcement: WritableSignal = linkedSignal({ source: this.fiscalYearId, computation: () => '' }); + + /** + * Why the api refused a preview or the preparation, or undefined while it refused none. + */ + protected readonly error: WritableSignal = linkedSignal({ + source: this.fiscalYearId, + computation: () => undefined + }); + + /** + * Changes a figure the user entered. + * @param position - The position of its row. + * @param column - The name of its column. + * @param value - The figure, or undefined for none. + */ + protected updateFigure(position: string, column: string, value: number | undefined): void { + this.figures.update(figures => { + const others: [string, number][] = Object.entries(figures[position] ?? {}).filter(([key]) => key !== column); + const columns: [string, number][] = value == undefined ? others : [...others, [column, value]]; + const rows: [string, Record][] = Object.entries(figures).filter(([key]) => key !== position); + // a row without figures is left out, so it only shows while a finding asks for it + return Object.fromEntries(columns.length ? [...rows, [position, Object.fromEntries(columns)]] : rows); + }); + } + + /** + * Previews the E-Bilanz with what the step holds, which the button only does with a balance sheet. + */ + protected async resolvePreview(): Promise { + const preparationInput: EBilanzPreparationInputModel | undefined = this.preparationInput(); + if (preparationInput == undefined) { + return; + } + await this.send(async () => { + const preview: EBilanzPreviewModel = await this.eBilanzService.resolvePreview(this.fiscalYearId(), preparationInput); + this.preview.set(preview); + this.previewedInput.set(JSON.stringify(preparationInput)); + this.announcement.set(this.labels.previewed); + }); + } + + /** + * Prepares exactly what was previewed, which the button only does once that needs nothing more. + */ + protected async prepare(): Promise { + const preparationInput: EBilanzPreparationInputModel | undefined = this.preparationInput(); + if (preparationInput == undefined || this.prepareReason() != undefined) { + return; + } + await this.send(async () => { + const filing: EBilanzFilingModel = await this.eBilanzService.prepare(this.fiscalYearId(), preparationInput); + this.prepared.emit(filing); + }); + } + + private async send(request: () => Promise): Promise { + this.sending.set(true); + this.announcement.set(''); + this.error.set(undefined); + try { + await request(); + } + catch (error) { + // a refusal of the api is the answer, like for an E-Bilanz that still needs something. Anything else is a + // mistake, which goes on to the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.error.set(ErrorResponseUtilities.findMessage(error) ?? this.commonLabels.requestFailed); + } + finally { + this.sending.set(false); + } + } + + private findPreparedAccountingStandard(): EBilanzAccountingStandard | undefined { + const accountingStandard: string | undefined = EBilanzViewUtilities.findPreparation(this.state())?.input?.accountingStandard; + return accountingStandard != undefined && EBilanzViewUtilities.isAccountingStandard(accountingStandard) ? accountingStandard : undefined; + } + + // the latest preparation states `original` until the E-Bilanz is filed, which a correction doesn't start from. + private findPreparedRevisionStatus(): EBilanzCorrectionStatus | undefined { + const revisionStatus: EBilanzRevisionStatus | null | undefined = EBilanzViewUtilities.findPreparation(this.state())?.input?.revisionStatus; + return EBilanzViewUtilities.isCorrectionStatus(revisionStatus) ? revisionStatus : undefined; + } + + private resolvePreparedFigures(): EBilanzFigures { + const inputs: EBilanzFixedAssetInputModel[] = EBilanzViewUtilities.findPreparation(this.state())?.input?.fixedAssets ?? []; + return Object.fromEntries(inputs.map(row => [ + row.position, + Object.fromEntries(row.values.map(value => [value.column, Number(value.amount)])) + ])); + } +} diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-statement-tab-view.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-statement-tab-view.model.ts new file mode 100644 index 0000000..632f042 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-statement-tab-view.model.ts @@ -0,0 +1,21 @@ +import { EBilanzContentTab } from './e-bilanz-content-tab.type'; +import { EBilanzStatementView } from './e-bilanz-statement-view.model'; + +/** + * A tab of the content of the E-Bilanz with the statements it shows: the balance sheet, or the income statement with + * the appropriation of profits. + */ +export type EBilanzStatementTabView = { + /** + * The value of the tab. + */ + value: EBilanzContentTab, + /** + * What the tab is called. + */ + label: string, + /** + * Its statements, in the order of the taxonomy. + */ + statements: EBilanzStatementView[] +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-statement-view.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-statement-view.model.ts new file mode 100644 index 0000000..28be295 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-statement-view.model.ts @@ -0,0 +1,19 @@ +import { EBilanzPositionView } from './e-bilanz-position-view.model'; + +/** + * A statement of the E-Bilanz, like its balance sheet, with its positions in their order. + */ +export type EBilanzStatementView = { + /** + * The name of the statement in the api, like `balanceSheet`. + */ + name: string, + /** + * What it is called. + */ + label: string, + /** + * Its positions. + */ + positions: EBilanzPositionView[] +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-tab.type.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-tab.type.ts new file mode 100644 index 0000000..98aa42f --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-tab.type.ts @@ -0,0 +1,4 @@ +/** + * A tab of the E-Bilanz: the steps of filing it, its records, the account mappings and the ELSTER certificate. + */ +export type EBilanzTab = 'filing' | 'records' | 'accountMappings' | 'certificate'; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-test.component.html b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-test.component.html new file mode 100644 index 0000000..f466727 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-test.component.html @@ -0,0 +1,20 @@ +

{{ labels.testText }}

+
+
+ + +
+ @if (testAction().reason; as reason) { +

{{ reason }}

+ } +
+

{{ labels.skipTestText }}

diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-test.component.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-test.component.ts new file mode 100644 index 0000000..45d90f2 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-test.component.ts @@ -0,0 +1,94 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { Component, computed, inject, input, InputSignal, output, OutputEmitterRef, Signal, signal, WritableSignal } from '@angular/core'; +import { BOOKKEEPING_CONFIG, BookkeepingCommonLabels, E_BILANZ_CONFIG, EBilanzConfig, EBilanzFilingLabels, EBilanzService } from '@service-soft/ngx-bookkeeping/api'; +import { ErrorResponseUtilities } from '@service-soft/ngx-error-handling/error-response'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { EBilanzStateModel } from 'zibri-contract'; + +import { EBilanzActionView } from './e-bilanz-action-view.model'; +import { EBilanzOutcome } from './e-bilanz-outcome.model'; +import { EBilanzViewUtilities } from './e-bilanz-view.utilities'; + +/** + * The step that sends the latest preparation of an E-Bilanz as a test, which the tax administration checks and doesn't + * keep, once the user presses its button. The button is disabled with why and how to enable it, like while the app + * can't send it. Whoever files the E-Bilanz by hand goes on without a test. What the tax administration answered is + * emitted on `outcome`. Only used by the E-Bilanz. + */ +@Component({ + selector: 'ngx-e-bilanz-test', + templateUrl: './e-bilanz-test.component.html', + imports: [ButtonComponent], + host: { class: 'grid gap-3' } +}) +export class EBilanzTestComponent { + private readonly config: EBilanzConfig = inject(E_BILANZ_CONFIG); + + private readonly eBilanzService: EBilanzService = inject(EBilanzService); + + /** + * The E-Bilanz of the fiscal year. + */ + readonly state: InputSignal = input.required(); + + /** + * Whether to say that sending needs the certificate as well, to a user who uploads it. + */ + readonly certificateMissing: InputSignal = input.required(); + + /** + * What the ids of the E-Bilanz start with, unique on the page. + */ + readonly idPrefix: InputSignal = input.required(); + + /** + * Emits what the test was answered with. + */ + readonly outcome: OutputEmitterRef = output(); + + /** + * The texts of sending the E-Bilanz. + */ + protected readonly labels: EBilanzFilingLabels = this.config.labels.filing; + + private readonly commonLabels: BookkeepingCommonLabels = inject(BOOKKEEPING_CONFIG).labels.common; + + /** + * Whether the test is being sent. + */ + protected readonly sending: WritableSignal = signal(false); + + /** + * Whether sending as a test is disabled, and why. + */ + protected readonly testAction: Signal = computed(() => { + const state: EBilanzStateModel = this.state(); + const reason: string | undefined = EBilanzViewUtilities.findTransmitterReason(state, this.config.labels, this.certificateMissing()) + ?? EBilanzViewUtilities.findPreparationReason(state, this.config.labels) + ?? EBilanzViewUtilities.findTransmissionReason(state, true, this.config.labels); + return { disabled: this.sending() || reason != undefined, reason, reasonId: `${this.idPrefix()}-test-reason` }; + }); + + /** + * Starts sending the latest preparation as a test, which the api sends in the background. The E-Bilanz shows its + * result once it has one. + */ + protected async transmitTest(): Promise { + this.sending.set(true); + try { + await this.eBilanzService.transmitTest(this.state().fiscalYearId); + this.outcome.emit({ kind: 'announcement', message: this.labels.sendingStarted, messages: [], recorded: true }); + } + catch (error) { + // a refusal of the api is the answer, like without a certificate. Anything else is a mistake, which goes on + // to the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.outcome.emit({ kind: 'error', message: ErrorResponseUtilities.findMessage(error) ?? this.commonLabels.requestFailed, messages: [], recorded: false }); + } + finally { + this.sending.set(false); + } + } +} diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-transmission.component.html b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-transmission.component.html new file mode 100644 index 0000000..f76c3bc --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-transmission.component.html @@ -0,0 +1,41 @@ +@if (running()) { + +
+ +

{{ labels.sendingText }}

+
+
+} +@if (unsettled().length) { + +
+ +
+

{{ labels.unsettledText }}

+
    + @for (view of unsettled(); track view.id) { +
  • + {{ view.text }} + @for (detail of view.details; track $index) { + + {{ detail }} + } +
  • + } +
+ @if (canTransmit()) { +

{{ labels.unsettledActionsText }}

+ +
+ @if (canFileByHand()) { + + } + +
+ } +
+
+
+} diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-transmission.component.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-transmission.component.ts new file mode 100644 index 0000000..6c9daed --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-transmission.component.ts @@ -0,0 +1,153 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { Component, computed, inject, input, InputSignal, LOCALE_ID, output, OutputEmitterRef, Signal, signal, WritableSignal } from '@angular/core'; +import { + BOOKKEEPING_CONFIG, + BookkeepingCommonLabels, + BookkeepingConfig, + BookkeepingDayUtilities, + E_BILANZ_CONFIG, + EBilanzConfig, + EBilanzFilingLabels, + EBilanzService +} from '@service-soft/ngx-bookkeeping/api'; +import { ErrorResponseUtilities } from '@service-soft/ngx-error-handling/error-response'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { ConfirmDialogComponent, ConfirmDialogData, DialogService } from '@service-soft/ui/dialog'; +import { SpinnerComponent } from '@service-soft/ui/spinner'; +import { EBilanzFilingModel, EBilanzStateModel, EBilanzTransmissionModel } from 'zibri-contract'; + +import { EBilanzManualFilingDialogData } from './e-bilanz-manual-filing-dialog-data.model'; +import { EBilanzManualFilingDialogComponent } from './e-bilanz-manual-filing-dialog.component'; +import { EBilanzOutcome } from './e-bilanz-outcome.model'; +import { EBilanzUnsettledView } from './e-bilanz-unsettled-view.model'; +import { EBilanzViewUtilities } from './e-bilanz-view.utilities'; + +/** + * Where the transmissions of an E-Bilanz stand, above its steps: that one is being sent right now, which can take + * minutes, and a warning about each one whose result is not known, as it may have reached the tax administration. The + * user checks that in ELSTER and then, with `canTransmit`, marks the E-Bilanz as filed by hand, or confirms that ELSTER + * didn't receive it after a question saying what that means. Until then, no transmission of its kind is sent. What + * happened is emitted on `outcome`. Only used by the E-Bilanz. + */ +@Component({ + selector: 'ngx-e-bilanz-transmission', + templateUrl: './e-bilanz-transmission.component.html', + imports: [ButtonComponent, CalloutComponent, SpinnerComponent], + host: { class: 'grid gap-2 empty:hidden' } +}) +export class EBilanzTransmissionComponent { + private readonly config: EBilanzConfig = inject(E_BILANZ_CONFIG); + + private readonly bookkeepingConfig: BookkeepingConfig = inject(BOOKKEEPING_CONFIG); + + private readonly eBilanzService: EBilanzService = inject(EBilanzService); + + private readonly dialogService: DialogService = inject(DialogService); + + private readonly locale: string = inject(LOCALE_ID); + + /** + * The E-Bilanz of the fiscal year. + */ + readonly state: InputSignal = input.required(); + + /** + * Whether the user may settle a transmission whose result is not known. + */ + readonly canTransmit: InputSignal = input.required(); + + /** + * Emits what settling a transmission was answered with. + */ + readonly outcome: OutputEmitterRef = output(); + + /** + * The texts of filing the E-Bilanz. + */ + protected readonly labels: EBilanzFilingLabels = this.config.labels.filing; + + private readonly commonLabels: BookkeepingCommonLabels = this.bookkeepingConfig.labels.common; + + /** + * The transmission being sent right now, or undefined for none. + */ + protected readonly running: Signal = computed(() => EBilanzViewUtilities.findRunningTransmission(this.state())); + + /** + * Each transmission whose result is not known, as the warning names it. + */ + protected readonly unsettled: Signal = computed(() => { + return EBilanzViewUtilities.findUnsettledTransmissions(this.state()).map(transmission => { + const moment: string = BookkeepingDayUtilities.formatMoment(new Date(transmission.startedAt), this.bookkeepingConfig.dateFormat, this.locale); + return { + id: transmission.id, + text: transmission.test ? this.labels.unsettledTest(moment) : this.labels.unsettledTransmission(moment), + details: transmission.result == undefined ? [] : EBilanzViewUtilities.getErrorParagraphs(transmission.result) + }; + }); + }); + + /** + * Whether the warning offers to mark the E-Bilanz as filed by hand: for a transmission for real, which is what files + * it, while the latest preparation can be marked as filed. + */ + protected readonly canFileByHand: Signal = computed(() => { + const state: EBilanzStateModel = this.state(); + return EBilanzViewUtilities.findUnsettledTransmissions(state).some(transmission => !transmission.test) + && EBilanzViewUtilities.findPreparationReason(state, this.config.labels) == undefined; + }); + + /** + * Whether a request settling a transmission is being sent. + */ + protected readonly sending: WritableSignal = signal(false); + + /** + * Asks for the protocol of the filing by hand, like the last step, and records it once the user confirms with one. + */ + protected async recordManualFiling(): Promise { + const data: EBilanzManualFilingDialogData = { fiscalYearId: this.state().fiscalYearId }; + const filing: EBilanzFilingModel | undefined = await this.dialogService + .open(EBilanzManualFilingDialogComponent, data) + .closed; + if (filing != undefined) { + this.outcome.emit({ kind: 'announcement', message: this.labels.manuallyFiled, messages: [], recorded: true }); + } + } + + /** + * Confirms that ELSTER didn't receive the transmissions whose result is not known, once the user answered the + * question saying what that means. Nothing is sent when they cancel. + */ + protected async recordNotReceived(): Promise { + const question: ConfirmDialogData = { + title: this.labels.notReceivedTitle, + paragraphs: [this.labels.notReceivedText, this.labels.notReceivedConsequence], + confirmButtonLabel: this.labels.confirmNotReceived, + cancelButtonLabel: this.commonLabels.cancel, + confirmButtonColor: 'error' + }; + const confirmed: boolean | undefined = await this.dialogService.open(ConfirmDialogComponent, question).closed; + if (confirmed !== true) { + return; + } + this.sending.set(true); + try { + // the api asks for the second factor of the user, which the interceptor of the auth of the app asks for + await this.eBilanzService.recordNotReceived(this.state().fiscalYearId); + this.outcome.emit({ kind: 'announcement', message: this.labels.notReceivedRecorded, messages: [], recorded: true }); + } + catch (error) { + // a refusal of the api is the answer, like a second factor the user didn't give. Anything else is a mistake, + // which goes on to the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.outcome.emit({ kind: 'error', message: ErrorResponseUtilities.findMessage(error) ?? this.commonLabels.requestFailed, messages: [], recorded: false }); + } + finally { + this.sending.set(false); + } + } +} diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-unmapped-account-view.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-unmapped-account-view.model.ts new file mode 100644 index 0000000..093106f --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-unmapped-account-view.model.ts @@ -0,0 +1,29 @@ +/** + * An account a finding says needs a position, as the account mappings show it. + */ +export type EBilanzUnmappedAccountView = { + /** + * The id of the account. + */ + accountId: string, + /** + * The id of its item, which the finding links to. + */ + id: string, + /** + * The number and the name of the account. + */ + label: string, + /** + * Its balance at the end of the fiscal year, formatted, or an empty string while it loads. + */ + balance: string, + /** + * What the finding says. + */ + message: string, + /** + * The name of the button that maps it. + */ + mapLabel: string +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-unsettled-view.model.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-unsettled-view.model.ts new file mode 100644 index 0000000..75703ca --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-unsettled-view.model.ts @@ -0,0 +1,17 @@ +/** + * A transmission whose result is not known, as the warning about it names it. + */ +export type EBilanzUnsettledView = { + /** + * The id of the transmission. + */ + id: string, + /** + * Which transmission it is, and when it started. + */ + text: string, + /** + * What it failed with, one paragraph each, or none. + */ + details: string[] +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz-view.utilities.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-view.utilities.ts new file mode 100644 index 0000000..672f44e --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz-view.utilities.ts @@ -0,0 +1,303 @@ +import { EBilanzCorrectionStatus, EBilanzLabels } from '@service-soft/ngx-bookkeeping/api'; +import { + EBilanzAccountingStandard, + EBilanzContentModel, + EBilanzFilingKind, + EBilanzFilingModel, + EBilanzFindingModel, + EBilanzRevisionStatus, + EBilanzStateModel, + EBilanzTransmissionModel, + EBilanzTransmissionStatus +} from 'zibri-contract'; + +import { EBilanzOutcome } from './e-bilanz-outcome.model'; +import { EBilanzPhase } from './e-bilanz-phase.type'; + +const ACCOUNTING_STANDARDS: EBilanzAccountingStandard[] = [EBilanzAccountingStandard.UNIFIED, EBilanzAccountingStandard.TAX]; + +const CORRECTION_STATUSES: EBilanzCorrectionStatus[] = [ + EBilanzRevisionStatus.CORRECTED, + EBilanzRevisionStatus.CHANGED, + EBilanzRevisionStatus.CORRECTED_AND_CHANGED, + EBilanzRevisionStatus.MORE_DETAIL, + EBilanzRevisionStatus.OTHER_CORRECTION +]; + +/** + * What the parts of the E-Bilanz read from its state and its content alike: how far it is filed, the latest + * preparation and the records of it, where its transmissions stand, and the rows of the statement of changes in fixed + * assets the findings ask figures of. Only used by the E-Bilanz. + */ +export abstract class EBilanzViewUtilities { + /** + * Resolves how far the E-Bilanz is filed, which the step of filing it opens at follows. A filed E-Bilanz whose + * books changed since is prepared again, as a correction, so it is 'outdated' then, and 'prepared' or 'tested' + * once its correction is. + * @param state - The E-Bilanz of the fiscal year. + * @returns Filed as prepared, prepared before the books changed, prepared with an accepted test of the same + * content, prepared, or not prepared. + */ + static resolvePhase(state: EBilanzStateModel): EBilanzPhase { + const preparation: EBilanzFilingModel | undefined = this.findPreparation(state); + if (preparation == undefined) { + return state.filed ? 'filed' : 'unprepared'; + } + if (!state.preparationCurrent) { + return 'outdated'; + } + if (this.isFiled(state, preparation)) { + return 'filed'; + } + return this.findAcceptedTest(state, preparation) == undefined ? 'prepared' : 'tested'; + } + + /** + * Finds the transmission that is being sent right now, in the background of the api. + * @param state - The E-Bilanz of the fiscal year. + * @returns The transmission, or undefined while none is `transmitting`. + */ + static findRunningTransmission(state: EBilanzStateModel): EBilanzTransmissionModel | undefined { + return state.transmissions.find(transmission => transmission.status === EBilanzTransmissionStatus.TRANSMITTING); + } + + /** + * Finds the transmissions whose result is not known: `unknown`, or `failed` while they may have been sent. Each + * keeps one of its kind from being sent until the user marks the E-Bilanz as filed by hand or confirms that ELSTER + * didn't receive it, as the api refuses it until then. A filing by hand settles those before it. + * @param state - The E-Bilanz of the fiscal year. + * @returns The transmissions, the earliest first. + */ + static findUnsettledTransmissions(state: EBilanzStateModel): EBilanzTransmissionModel[] { + const manualFiling: number = state.filings.map(filing => filing.kind).lastIndexOf(EBilanzFilingKind.MANUAL_FILING); + return state.transmissions.filter(transmission => { + const notKnown: boolean = transmission.status === EBilanzTransmissionStatus.UNKNOWN + || (transmission.status === EBilanzTransmissionStatus.FAILED && transmission.mayHaveBeenSent); + return notKnown && state.filings.findIndex(filing => filing.id === transmission.id) > manualFiling; + }); + } + + /** + * Finds why sending is disabled by the transmissions of the E-Bilanz: while one runs, and while one of the same + * kind has a result that is not known. + * @param state - The E-Bilanz of the fiscal year. + * @param test - Whether it is about sending as a test. + * @param labels - The texts of the E-Bilanz. + * @returns Why, or undefined while the transmissions don't keep it from being sent. + */ + static findTransmissionReason(state: EBilanzStateModel, test: boolean, labels: EBilanzLabels): string | undefined { + if (this.findRunningTransmission(state) != undefined) { + return labels.filing.runningReason; + } + return this.findUnsettledTransmissions(state).some(transmission => transmission.test === test) ? labels.filing.unsettledReason : undefined; + } + + /** + * Resolves what the view says once a transmission has its result. A result that is not known says nothing here: + * the warning about it shows as long as it isn't settled. + * @param transmission - The transmission, with its result. + * @param labels - The texts of the E-Bilanz. + * @returns What to say, or undefined for nothing. + */ + static resolveTransmissionOutcome(transmission: EBilanzTransmissionModel, labels: EBilanzLabels): EBilanzOutcome | undefined { + const result: EBilanzFilingModel | null = transmission.result; + switch (transmission.status) { + case EBilanzTransmissionStatus.ACCEPTED: { + const message: string = transmission.test ? labels.filing.testAccepted : labels.filing.transmitted(result?.ticket ?? ''); + return { kind: 'announcement', message, messages: [], recorded: true }; + } + case EBilanzTransmissionStatus.REFUSED: { + const message: string = transmission.test ? labels.filing.testRefused : labels.filing.transmissionRefused; + return { kind: 'refusal', message, messages: result?.messages ?? [], recorded: true }; + } + case EBilanzTransmissionStatus.FAILED: { + return transmission.mayHaveBeenSent + ? undefined + : { kind: 'error', message: labels.filing.failedNotSent, messages: result == undefined ? [] : this.getErrorParagraphs(result), recorded: true }; + } + case EBilanzTransmissionStatus.TRANSMITTING: + case EBilanzTransmissionStatus.UNKNOWN: + case EBilanzTransmissionStatus.NOT_RECEIVED: { + return undefined; + } + } + } + + /** + * Gets what a transmitter failed with, as a record of it keeps it. + * @param filing - The record. + * @returns The paragraphs of the error, or its message when it has none, and none without an error. + */ + static getErrorParagraphs(filing: EBilanzFilingModel): string[] { + if (filing.error == undefined) { + return []; + } + return filing.error.paragraphs.length ? filing.error.paragraphs : [filing.error.message]; + } + + /** + * Gets how a correction can correct a filed E-Bilanz, in the order they are offered. + * @returns Every revision status but `original`. + */ + static getCorrectionStatuses(): EBilanzCorrectionStatus[] { + return CORRECTION_STATUSES; + } + + /** + * Whether a revision status of the api is one a correction states. + * @param value - The revisionStatus of a preparation. + * @returns Whether it is one of them, not `original`. + */ + static isCorrectionStatus(value: EBilanzRevisionStatus | null | undefined): value is EBilanzCorrectionStatus { + return CORRECTION_STATUSES.some(status => status === value); + } + + /** + * Finds why the latest preparation can't be sent or marked as filed, as the api refuses it then. + * @param state - The E-Bilanz of the fiscal year. + * @param labels - The texts of the E-Bilanz. + * @returns That it isn't prepared, was prepared before the books changed or is filed as prepared, or undefined + * when it can be filed. + */ + static findPreparationReason(state: EBilanzStateModel, labels: EBilanzLabels): string | undefined { + const preparation: EBilanzFilingModel | undefined = this.findPreparation(state); + if (preparation == undefined) { + return labels.common.notPreparedReason; + } + if (!state.preparationCurrent) { + return labels.common.outdatedReason; + } + return this.isFiled(state, preparation) ? labels.filing.filedReason : undefined; + } + + /** + * Finds why the E-Bilanz can't be sent from the app, in words for its users: the reason of the api names what a + * developer sets up, so it isn't shown. + * @param state - The E-Bilanz of the fiscal year. + * @param labels - The texts of the E-Bilanz. + * @param certificateMissing - Whether to say that the certificate needs to be uploaded as well, to a user who may. + * @returns Why, or undefined while it can be sent. + */ + static findTransmitterReason(state: EBilanzStateModel, labels: EBilanzLabels, certificateMissing: boolean): string | undefined { + if (state.transmitterConfigured) { + return undefined; + } + return certificateMissing ? `${labels.filing.noTransmitter} ${labels.filing.certificateMissing}` : labels.filing.noTransmitter; + } + + /** + * Finds the latest record that files the E-Bilanz: an accepted transmission, or a filing by hand. + * @param state - The E-Bilanz of the fiscal year. + * @returns The record, or undefined while it isn't filed. + */ + static findFiling(state: EBilanzStateModel): EBilanzFilingModel | undefined { + return state.filings.filter(filing => this.isFiling(filing)).at(-1); + } + + /** + * Gets the balance sheets an E-Bilanz can state, in the order they are offered. + * @returns The values the api takes. + */ + static getAccountingStandards(): EBilanzAccountingStandard[] { + return ACCOUNTING_STANDARDS; + } + + /** + * Whether a value of the api is one of the balance sheets the labels name. + * @param value - The accountingStandard of a content. + * @returns Whether it is `unified` or `tax`. + */ + static isAccountingStandard(value: string): value is EBilanzAccountingStandard { + return ACCOUNTING_STANDARDS.some(standard => standard === value); + } + + /** + * Finds the record of the latest preparation, which an export and a transmission send. + * @param state - The E-Bilanz of the fiscal year. + * @returns The record, or undefined while it isn't prepared. + */ + static findPreparation(state: EBilanzStateModel): EBilanzFilingModel | undefined { + return state.preparationId == undefined ? undefined : state.filings.find(filing => filing.id === state.preparationId); + } + + /** + * Finds the latest accepted test of the content of a preparation, after which it can be sent for real. + * @param state - The E-Bilanz of the fiscal year. + * @param preparation - The record of the preparation. + * @returns The record of the test, or undefined while none of the same content was accepted. + */ + static findAcceptedTest(state: EBilanzStateModel, preparation: EBilanzFilingModel): EBilanzFilingModel | undefined { + // the records are the earliest first + return [...state.filings].reverse().find(filing => { + return filing.kind === EBilanzFilingKind.TEST_TRANSMISSION && filing.succeeded && filing.contentHash === preparation.contentHash; + }); + } + + /** + * Whether the content of a preparation is filed: sent and accepted, or filed by hand. The api refuses to send or + * record it again then. + * @param state - The E-Bilanz of the fiscal year. + * @param preparation - The record of the preparation. + * @returns Whether a record of its content files it. + */ + static isFiled(state: EBilanzStateModel, preparation: EBilanzFilingModel): boolean { + return state.filings.some(filing => filing.contentHash === preparation.contentHash && this.isFiling(filing)); + } + + /** + * Finds the rows of the statement of changes in fixed assets a finding asks figures of: rows of a position with + * accounts, the only ones the api takes figures of. A row above them names what the rows below it need. + * @param content - The content the findings are of. + * @param findings - The findings. + * @returns The positions of the rows. + */ + static findFigurePositions(content: EBilanzContentModel, findings: EBilanzFindingModel[]): Set { + const named: Set = new Set(findings.map(finding => finding.position ?? '')); + const withAccounts: Set = new Set(content.positions.filter(position => position.accounts.length).map(position => position.name)); + return new Set(content.fixedAssets.map(row => row.position).filter(position => named.has(position) && withAccounts.has(position))); + } + + /** + * Gets the id of the element a finding links to: the row of a position, of the statement of changes in fixed + * assets, the figures of such a row, or an account that needs a position. + * @param idPrefix - What the ids of the E-Bilanz start with, unique on the page. + * @param target - What the element shows. + * @param name - The element name of the position, or the number of the account. + * @returns The id. + */ + static getTargetId(idPrefix: string, target: 'position' | 'fixed-asset' | 'figures' | 'account', name: string): string { + return `${idPrefix}-${target}-${name}`; + } + + /** + * Resolves how deep a position is below the top, by the positions it is below. + * @param name - The name of the position. + * @param parents - The parent of each position, null at the top. + * @returns 0 at the top, 1 below it and so on. A parent the map doesn't hold counts as the top. + */ + static resolveDepth(name: string, parents: Map): number { + let depth: number = 0; + let parent: string | null | undefined = parents.get(name); + // the parents of the api form a tree, the limit only guards against a loop in data of another api. + while (parent != undefined && parents.has(parent) && depth < parents.size) { + depth++; + parent = parents.get(parent); + } + return depth; + } + + private static isFiling(filing: EBilanzFilingModel): boolean { + switch (filing.kind) { + case EBilanzFilingKind.TRANSMISSION: { + return filing.succeeded; + } + case EBilanzFilingKind.MANUAL_FILING: { + return true; + } + case EBilanzFilingKind.PREPARED: + case EBilanzFilingKind.TEST_TRANSMISSION: { + return false; + } + } + } +} diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz.component.html b/projects/ngx-bookkeeping/e-bilanz/e-bilanz.component.html new file mode 100644 index 0000000..162cbfd --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz.component.html @@ -0,0 +1,190 @@ +
+ @if (alert(); as alert) { + + } + @if (hasNoFiscalYears()) { + + } @else if (hasNoClosedFiscalYears()) { + + } @else if (closedFiscalYearOptions().length) { +
+ +
+ @if (stateFailed()) { + + } + @if (stateValue(); as state) { +
+
+ {{ title() }} + @if (status(); as status) { + {{ status.label }} + } +
+ + + +
+ @if (phase() === 'outdated') { + +

{{ state.filed ? labels.common.correctionReason : labels.common.outdatedReason }}

+
+ } + @if (filedSummary(); as filedSummary) { + +

{{ filedSummary }}

+ @if (phase() === 'filed') { +

{{ labels.common.correctionHint }}

+ } +
+ } + +
+ +

{{ announcement() }}

+

{{ stepReason() }}

+ + + @if (outcome(); as outcome) { + @if (outcome.kind !== 'announcement') { +
+ + +

{{ outcome.message }}

+ @if (outcome.messages.length) { +
    + @for (message of outcome.messages; track $index) { +
  • {{ message }}
  • + } +
+ } +
+
+ } + } +
+ + +
+ @if (format(); as format) { + + } + @if (findings().length) { + + } +
+
+ +
+ @if (findings().length) { + + } + @if (content(); as content) { + @if (format(); as format) { + + } + } @else { +

{{ labels.review.noContent }}

+ } +
+
+ + @if (canTransmit()) { + + } @else { +

{{ labels.common.noPermission }}

+ } +
+ + @if (mayNotFile()) { +

{{ labels.common.noPermission }}

+ } @else { + + } +
+
+
+
+ + + + @if (canManage()) { + + @if (format(); as format) { + + } + + + + + } +
+
+ } + } +
diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz.component.spec.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz.component.spec.ts new file mode 100644 index 0000000..1dd2a63 --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz.component.spec.ts @@ -0,0 +1,941 @@ +import { HttpRequest } from '@angular/common/http'; +import { Component, signal, WritableSignal } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { EBilanzConfigChanges } from '@service-soft/ngx-bookkeeping/api'; +import { DialogTestingUtilities } from 'testing/dialog'; +import { FormTestingUtilities } from 'testing/form'; +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; +import { EBilanzFilingKind } from 'zibri-contract'; + +import { BookkeepingTestingUtilities } from '../fixtures/bookkeeping-testing.utilities'; +import { FISCAL_YEAR_IDS } from '../fixtures/bookkeeping.fixtures'; +import { DEPRECIATION_COLUMN, OFFICE_EQUIPMENT_POSITION, TRANSIT_POSITION } from '../fixtures/e-bilanz.fixtures'; +import { FakeEBilanzBackendOptions } from '../fixtures/fake-e-bilanz-backend-options.model'; +import { FakeEBilanzBackend } from '../fixtures/fake-e-bilanz-backend.model'; +import { EBilanzComponent } from './e-bilanz.component'; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [EBilanzComponent] +}) +class HostComponent { + readonly canPrepare: WritableSignal = signal(true); + readonly canTransmit: WritableSignal = signal(true); + readonly canManage: WritableSignal = signal(true); +} + +@Component({ + selector: 'ngx-configured-host', + template: '', + imports: [EBilanzComponent] +}) +class ConfiguredHostComponent {} + +const UNIFIED: string = 'The commercial balance sheet, which is the tax balance sheet as well (Einheitsbilanz)'; +const NO_TRANSMITTER: string = 'Sending isn\'t set up in this app. Download the file, file it with another program and mark it as filed here. ' + + 'To send from here, ask your administrator to set up sending.'; +const CERTIFICATE_MISSING: string = 'Sending also needs the ELSTER certificate of the company, which isn\'t uploaded yet: upload it under ELSTER ' + + 'certificate.'; +// what the api answers as the reason, which names what a developer sets up +const TECHNICAL_REASONS: string[] = ['EBilanzTransmitterInterface', 'E_BILANZ_TRANSMITTER_DI_VARIANT', 'The ELSTER certificate of the company and its PIN need']; +const STATE_URL: string = `/api/e-bilanz/fiscal-years/${FISCAL_YEAR_IDS.year2025}`; +const STEPS: string[] = ['Prepare', 'Review', 'Test', 'Send or file by hand']; + +let backend: FakeEBilanzBackend; + +/** + * Renders the E-Bilanz against a fake backend. + * @param options - How the backend answers. + * @param config - The config of the E-Bilanz beside its url. + * @param host - The component rendering it. + * @returns The fixture and its element. + */ +async function render( + options: FakeEBilanzBackendOptions = {}, + config: EBilanzConfigChanges = {}, + host: typeof HostComponent | typeof ConfiguredHostComponent = HostComponent +): Promise<[ComponentFixture, HTMLElement]> { + backend = new FakeEBilanzBackend(options); + TestBed.configureTestingModule({ providers: BookkeepingTestingUtilities.getEBilanzProviders(backend, config) }); + const fixture: ComponentFixture = TestBed.createComponent(host); + // the focus is only followed in the document + document.body.append(fixture.nativeElement as HTMLElement); + await BookkeepingTestingUtilities.renderAnswered(fixture); + return [fixture, fixture.nativeElement as HTMLElement]; +} + +function getElement(root: ParentNode, selector: string): HTMLElement { + const element: HTMLElement | null = root.querySelector(selector); + if (element == undefined) { + throw new Error(`There is no ${selector}.`); + } + return element; +} + +function findButton(root: ParentNode, text: string): HTMLButtonElement { + const button: HTMLButtonElement | undefined = [...root.querySelectorAll('button')].find(candidate => candidate.textContent.trim() === text); + if (button == undefined) { + throw new Error(`There is no button "${text}".`); + } + return button; +} + +function findButtonTexts(root: ParentNode): string[] { + return [...root.querySelectorAll('button')].map(button => button.textContent.trim()); +} + +// the text that describes a button, like why it is disabled. +function getDescription(button: HTMLButtonElement): string { + const ids: string[] = button.getAttribute('aria-describedby')?.split(' ') ?? []; + return ids.map(id => BookkeepingTestingUtilities.getText(document.getElementById(id))).join(' '); +} + +function findRequests(method: string, path: string): HttpRequest[] { + return backend.requests.filter(request => request.method === method && request.url === `${STATE_URL}/${path}`); +} + +// what was sent that changes something or sends the E-Bilanz: everything but reading. +function findSent(): string[] { + return backend.requests.filter(request => request.method !== 'GET').map(request => `${request.method} ${request.url}`); +} + +async function click(fixture: ComponentFixture, root: ParentNode, text: string): Promise { + FormTestingUtilities.click(root, text); + await BookkeepingTestingUtilities.renderAnswered(fixture); +} + +// the tabs of the E-Bilanz, not those of its content, which come after them. +function getTabs(root: HTMLElement): HTMLElement[] { + return [...getElement(root, '[role="tablist"]').querySelectorAll('[role="tab"]')]; +} + +function getTab(root: HTMLElement): string { + return getTabs(root).find(tab => tab.getAttribute('aria-selected') === 'true')?.textContent.trim() ?? ''; +} + +async function openTab(fixture: ComponentFixture, root: HTMLElement, label: string): Promise { + const tab: HTMLElement | undefined = getTabs(root).find(candidate => candidate.textContent.trim() === label); + if (tab == undefined) { + throw new Error(`There is no tab "${label}".`); + } + tab.click(); + await BookkeepingTestingUtilities.renderAnswered(fixture); +} + +function getTabPanel(root: HTMLElement, label: string): HTMLElement { + const tab: HTMLElement | undefined = getTabs(root).find(candidate => candidate.textContent.trim() === label); + return getElement(document, `#${CSS.escape(tab?.getAttribute('aria-controls') ?? '')}`); +} + +// the name of the current step, or an empty string once every step is done. +function getStep(root: HTMLElement): string { + const step: Element | null = root.querySelector('ui-stepper li[aria-current="step"]'); + return BookkeepingTestingUtilities.getText(step).replace(/^\d+ /, ''); +} + +function getDoneSteps(root: HTMLElement): string[] { + return [...root.querySelectorAll('ui-stepper li')] + .map(step => BookkeepingTestingUtilities.getText(step)) + .filter(text => text.endsWith(' completed')) + .map(text => text.replace(' completed', '')); +} + +// the content of the current step, which is its form. +function getShownStep(root: HTMLElement): HTMLElement { + return getElement(root, 'ui-stepper ui-form:not([hidden])'); +} + +// goes on with the button of the current step until the step shows, or back to it by its name once it is done. +async function goToStep(fixture: ComponentFixture, root: HTMLElement, label: string): Promise { + const done: HTMLButtonElement | undefined = [...root.querySelectorAll('ui-stepper li button')] + .find(button => BookkeepingTestingUtilities.getText(button) === `${label} completed`); + done?.click(); + await BookkeepingTestingUtilities.renderAnswered(fixture); + for (let attempt: number = 0; attempt < STEPS.length && getStep(root) !== label; attempt++) { + await click(fixture, getShownStep(root), 'Next'); + } + expect(getStep(root)).toBe(label); +} + +// what the E-Bilanz says above its steps once a request was answered, which takes the focus. +function getMessage(root: HTMLElement): HTMLElement { + return getElement(getTabPanel(root, 'Filing'), 'div[tabindex="-1"]'); +} + +// previews the E-Bilanz with the balance sheet that is the tax balance sheet as well. +async function preview(fixture: ComponentFixture, root: HTMLElement): Promise { + const preparation: HTMLElement = getElement(root, 'ngx-e-bilanz-preparation'); + await BookkeepingTestingUtilities.select(fixture, preparation, 'Balance sheet', UNIFIED); + await click(fixture, preparation, 'Preview'); +} + +async function findDialog(): Promise { + return await vi.waitFor(() => { + TestBed.tick(); + const opened: HTMLDialogElement | undefined = [...document.querySelectorAll('dialog[open]')].at(-1); + if (opened == undefined) { + throw new Error('No dialog is open.'); + } + return opened; + }); +} + +function getFindings(root: HTMLElement): string[] { + return [...getShownStep(root).querySelectorAll('ngx-e-bilanz-findings li')].map(item => BookkeepingTestingUtilities.getText(item)); +} + +function findFindingLink(root: HTMLElement, subject: string): HTMLAnchorElement { + const link: HTMLAnchorElement | undefined = [...getShownStep(root).querySelectorAll('ngx-e-bilanz-findings a')] + .find(candidate => candidate.textContent.trim() === subject); + if (link == undefined) { + throw new Error(`There is no finding linked to "${subject}".`); + } + return link; +} + +async function attachFile(fixture: ComponentFixture, root: ParentNode, file: File): Promise { + const input: HTMLInputElement | null = root.querySelector('input[type="file"]'); + Object.defineProperty(input, 'files', { value: [file], configurable: true }); + input?.dispatchEvent(new Event('change')); + await BookkeepingTestingUtilities.renderAnswered(fixture); +} + +// the api sends in the background, and the fake answers after a few seconds, like the polling of the E-Bilanz. Timers +// are faked and run on with the real time, so rendering waits as it does without them. +function useFakeTimers(): void { + vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['setTimeout', 'clearTimeout'] }); +} + +// lets the time pass, like while the user waits for the result of a transmission. +async function wait(fixture: ComponentFixture, milliseconds: number): Promise { + await vi.advanceTimersByTimeAsync(milliseconds); + await BookkeepingTestingUtilities.renderAnswered(fixture); +} + +// the requests that loaded the E-Bilanz of the fiscal year. +function findStateRequests(): HttpRequest[] { + return backend.requests.filter(request => request.method === 'GET' && request.url === STATE_URL); +} + +describe('EBilanzComponent', () => { + let removeModalDialogs: () => void; + + beforeEach(() => { + removeModalDialogs = DialogTestingUtilities.addModalDialogs(); + }); + + afterEach(() => { + removeModalDialogs(); + for (const element of document.querySelectorAll('ui-dialog, ngx-host, ngx-configured-host')) { + element.remove(); + } + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); + + test('shows the latest closed fiscal year, which is not prepared, with its deadline, its tabs and the step that prepares it', async () => { + const [, root] = await render(); + + expect(root.querySelector('ui-heading.text-headline')?.textContent.trim()).toBe('E-Bilanz 2025'); + expect(root.querySelector('ui-badge')?.textContent.trim()).toBe('Not prepared'); + expect(BookkeepingTestingUtilities.getText(root.querySelector('ui-data-list'))).toBe('To be filed by 07/31/2026'); + expect(getTabs(root).map(tab => tab.textContent.trim())).toEqual(['Filing', 'Records', 'Account mappings', 'ELSTER certificate']); + expect(getTab(root)).toBe('Filing'); + expect([...root.querySelectorAll('ui-stepper li')].map(step => BookkeepingTestingUtilities.getText(step))) + .toEqual(['1 Prepare', '2 Review', '3 Test', '4 Send or file by hand']); + expect(getStep(root)).toBe('Prepare'); + expect(getShownStep(root).querySelector('h3')?.textContent.trim()).toBe('Prepare'); + expect(BookkeepingTestingUtilities.getText(getTabPanel(root, 'Records'))).toContain('Nothing was prepared or filed yet.'); + }); + + test('has no default balance sheet: the preview waits until the user chose one', async () => { + const [fixture, root] = await render(); + const preview: HTMLButtonElement = findButton(getShownStep(root), 'Preview'); + + expect(preview.disabled).toBe(true); + expect(getDescription(preview)).toBe('Choose the balance sheet first.'); + // the button that goes on asks for it as well, and stays on the step + await click(fixture, getShownStep(root), 'Next'); + + expect(findRequests('POST', 'preview')).toEqual([]); + expect(BookkeepingTestingUtilities.getText(getShownStep(root))).toContain('This field is required.'); + expect(getStep(root)).toBe('Prepare'); + }); + + test('shows the findings of the preview, each naming its position and linking to it', async () => { + const [fixture, root] = await render(); + + await preview(fixture, root); + + expect(findRequests('POST', 'preview').map(request => request.body)).toEqual([{ accountingStandard: 'unified', fixedAssets: [] }]); + expect(getFindings(root)).toEqual([ + '1360 The account 1360 Money in transit has a balance and needs a position of the taxonomy 6.9 of the E-Bilanz: a mapping of its ' + + 'own, or a statement position the taxonomy maps.', + 'Bilanzsumme, Summe Aktiva (bs.ass) The balance sheet needs to balance: bs.ass states 13200 and bs.eqLiab states 13450.', + `Büroeinrichtung (${OFFICE_EQUIPMENT_POSITION}) The statement of changes in fixed assets of ${OFFICE_EQUIPMENT_POSITION} states the ` + + 'book value 2000 at the end of the year, all, and needs to equal the balance sheet, 1800: name the figures the books do not hold, ' + + 'such as the depreciation of the year.', + 'Anlagevermögen (bs.ass.fixAss) The statement of changes in fixed assets of bs.ass.fixAss states the book value 2000 at the end of ' + + 'the year, all, and needs to equal the balance sheet, 1800: name the figures the books do not hold of the positions below it.' + ]); + // each links to what lets the user change it: the account to map, the row of a position, the figures of a row + const targets: (HTMLElement | null)[] = [...getShownStep(root).querySelectorAll('ngx-e-bilanz-findings a')] + .map(link => document.getElementById(decodeURIComponent(link.hash.slice(1)))); + expect(targets.map(target => target?.closest('ngx-e-bilanz-account-mappings, ngx-e-bilanz-content, ngx-e-bilanz-preparation')?.localName)) + .toEqual(['ngx-e-bilanz-account-mappings', 'ngx-e-bilanz-content', 'ngx-e-bilanz-preparation', 'ngx-e-bilanz-content']); + expect(BookkeepingTestingUtilities.getText(targets[0])).toContain('1360 Money in transit €250.00'); + expect(targets[2]?.localName).toBe('fieldset'); + // a preview with findings can't be prepared + const prepare: HTMLButtonElement = findButton(getShownStep(root), 'Prepare'); + expect(prepare.disabled).toBe(true); + expect(getDescription(prepare)).toBe('It can be prepared once it needs nothing more.'); + }); + + test('opens the step or the tab of the element a finding links to, and moves the focus to it', async () => { + const [fixture, root] = await render(); + await preview(fixture, root); + + // the account to map is in its tab + await click(fixture, getShownStep(root), '1360'); + expect(getTab(root)).toBe('Account mappings'); + expect(document.activeElement?.textContent).toContain('1360 Money in transit'); + expect(getTabPanel(root, 'Account mappings').contains(document.activeElement)).toBe(true); + + // the row of a position is in its tab of the content of the review + await openTab(fixture, root, 'Filing'); + findFindingLink(root, 'Bilanzsumme, Summe Aktiva').click(); + await BookkeepingTestingUtilities.renderAnswered(fixture); + expect(getTab(root)).toBe('Filing'); + expect(getStep(root)).toBe('Review'); + expect(root.querySelector('ngx-e-bilanz-content [role="tab"][aria-selected="true"]')?.textContent.trim()).toBe('Balance sheet'); + expect(document.activeElement?.localName).toBe('tr'); + expect(document.activeElement?.textContent).toContain('bs.ass'); + + // the figures of a row are in the step that prepares it, whatever tab of the content shows + await click(fixture, getElement(root, 'ngx-e-bilanz-content'), 'Statement of changes in fixed assets'); + findFindingLink(root, 'Büroeinrichtung').click(); + await BookkeepingTestingUtilities.renderAnswered(fixture); + expect(getStep(root)).toBe('Prepare'); + expect(document.activeElement?.localName).toBe('fieldset'); + expect(getShownStep(root).contains(document.activeElement)).toBe(true); + + // following a link sends nothing + expect(findSent()).toEqual([`POST ${STATE_URL}/preview`]); + }); + + test('shows the positions with their accounts, and NIL for those the books don\'t state', async () => { + const [fixture, root] = await render(); + + await preview(fixture, root); + + const rows: string[] = [...root.querySelectorAll('ngx-e-bilanz-content table')[0]?.querySelectorAll('tbody tr') ?? []] + .map(row => BookkeepingTestingUtilities.getText(row)); + expect(rows.slice(0, 7)).toEqual([ + 'Bilanzsumme, Summe Aktiva bs.ass €13,200.00', + 'Anlagevermögen bs.ass.fixAss €1,800.00', + 'Immaterielle Vermögensgegenstände bs.ass.fixAss.intan NIL', + 'Sachanlagen bs.ass.fixAss.tan €1,800.00', + 'andere Anlagen, Betriebs- und Geschäftsausstattung bs.ass.fixAss.tan.otherEquipm €1,800.00', + `Büroeinrichtung ${OFFICE_EQUIPMENT_POSITION} €1,800.00`, + '0420 Office equipment €1,800.00' + ]); + const content: HTMLElement = getElement(root, 'ngx-e-bilanz-content'); + expect(BookkeepingTestingUtilities.getText(content)).toContain('A preview, as the books state it now. It isn\'t prepared.'); + expect(BookkeepingTestingUtilities.getText(content)).toContain('NIL marks a position the tax administration'); + expect([...content.querySelectorAll('[role="tab"]')].map(tab => tab.textContent.trim())) + .toEqual(['Balance sheet', 'Income statement', 'Statement of changes in fixed assets']); + expect([...content.querySelectorAll('caption')].map(caption => caption.textContent.trim())) + .toEqual(['Balance sheet', 'Income statement', 'Statement of changes in fixed assets']); + }); + + test('indents the statement of changes in fixed assets by the row each is summed into', async () => { + const [fixture, root] = await render(); + + await preview(fixture, root); + + const table: Element | undefined = [...root.querySelectorAll('ngx-e-bilanz-content table')].at(-1); + const headers: HTMLTableCellElement[] = [...table?.querySelectorAll('tbody th') ?? []]; + expect(headers.map(header => [header.childNodes[0]?.textContent?.trim(), [...header.classList].find(name => name.startsWith('ps-'))])).toEqual([ + ['Anlagevermögen', 'ps-3'], + ['Sachanlagen', 'ps-7'], + ['andere Anlagen, Betriebs- und Geschäftsausstattung', 'ps-11'], + ['Büroeinrichtung', 'ps-15'] + ]); + expect(BookkeepingTestingUtilities.getText(table?.querySelector('tbody tr:last-child'))) + .toBe(`Büroeinrichtung ${OFFICE_EQUIPMENT_POSITION} €0.00 €2,000.00 NIL €2,000.00 €0.00 NIL €0.00 NIL €2,000.00`); + }); + + test('asks for the figures the findings name, prepares exactly what was previewed once it needs nothing more, and opens the review', async () => { + const [fixture, root] = await render(); + await preview(fixture, root); + + // the account money in transit is mapped to a position of its own + await openTab(fixture, root, 'Account mappings'); + const mappings: HTMLElement = getElement(root, 'ngx-e-bilanz-account-mappings'); + await click(fixture, mappings, 'Map'); + expect(document.activeElement).toBe(FormTestingUtilities.findInput(mappings, 'position')); + await BookkeepingTestingUtilities.type(fixture, FormTestingUtilities.findInput(mappings, 'position'), TRANSIT_POSITION); + await click(fixture, mappings, 'Save the mapping'); + expect(backend.requests.find(request => request.method === 'PUT')?.body).toEqual({ position: TRANSIT_POSITION, creditPosition: null }); + expect(mappings.querySelector('p[role="status"]')?.textContent.trim()) + .toBe('1360 Money in transit was mapped. Preview the E-Bilanz again to see what it states now.'); + + // the figures of the row the findings name are those the books don't state + await openTab(fixture, root, 'Filing'); + await click(fixture, getShownStep(root), 'Preview'); + const preparation: HTMLElement = getElement(root, 'ngx-e-bilanz-preparation'); + expect([...preparation.querySelectorAll('fieldset label')].map(label => label.textContent.replace('*', '').trim())).toEqual([ + 'Anschaffungs- und Herstellungskosten, Abgänge', + 'Abschreibungen, Sonderabschreibungen und sonstige Abzüge der Periode, planmäßige Abschreibung', + 'Zuschreibungen' + ]); + await BookkeepingTestingUtilities.type(fixture, FormTestingUtilities.findInput(preparation, `${OFFICE_EQUIPMENT_POSITION}:${DEPRECIATION_COLUMN}`), '200'); + // a figure changed since the preview, so it is previewed again before it is prepared + expect(getDescription(findButton(preparation, 'Prepare'))).toBe('Preview it first, with the balance sheet and the figures above.'); + await click(fixture, preparation, 'Preview'); + expect(getFindings(root)).toEqual([]); + + await click(fixture, preparation, 'Prepare'); + + const figures: unknown = { accountingStandard: 'unified', fixedAssets: [{ position: OFFICE_EQUIPMENT_POSITION, values: [{ column: DEPRECIATION_COLUMN, amount: '200.00' }] }] }; + expect(findRequests('POST', 'preview').at(-1)?.body).toEqual(figures); + expect(findRequests('POST', 'preparation').map(request => request.body)).toEqual([figures]); + const message: HTMLElement = getMessage(root); + expect(BookkeepingTestingUtilities.getText(message)).toBe('The E-Bilanz was prepared. Review it, then send it as a test or file it by hand.'); + expect(document.activeElement).toBe(message); + expect(root.querySelector('ui-badge')?.textContent.trim()).toBe('Prepared'); + expect(getStep(root)).toBe('Review'); + expect(BookkeepingTestingUtilities.getText(getShownStep(root))).toContain('As prepared on 03/02/2026'); + expect(BookkeepingTestingUtilities.getText(getTabPanel(root, 'Records').querySelector('tbody'))).toContain('Prepared'); + }); + + test('opens a step once the one before is done: the review only once the E-Bilanz is prepared', async () => { + const [fixture, root] = await render(); + await preview(fixture, root); + + await click(fixture, getShownStep(root), 'Next'); + + expect(getStep(root)).toBe('Prepare'); + expect(BookkeepingTestingUtilities.getText(getMessage(root))).toBe('Prepare the E-Bilanz first.'); + expect(findSent()).toEqual([`POST ${STATE_URL}/preview`]); + }); + + test.each<[string, FakeEBilanzBackendOptions, string]>([ + ['not prepared, at preparing it', {}, 'Prepare'], + ['prepared, at reviewing it', { stage: 'prepared', transmitter: 'configured' }, 'Review'], + ['tested, at sending it', { stage: 'tested', transmitter: 'configured' }, 'Send or file by hand'], + ['prepared before the books changed, at preparing it again', { stage: 'tested', transmitter: 'configured', booksChanged: true }, 'Prepare'] + ])('opens the E-Bilanz %s', async (_, options, step) => { + const [, root] = await render(options); + + expect(getStep(root)).toBe(step); + expect(getDoneSteps(root)).toEqual(STEPS.slice(0, STEPS.indexOf(step))); + }); + + test('shows every step as done once the E-Bilanz is filed, with how it was filed', async () => { + const [, root] = await render({ stage: 'transmitted', transmitter: 'configured' }); + + expect(getStep(root)).toBe(''); + expect(getDoneSteps(root)).toEqual(STEPS); + expect(root.querySelector('ui-stepper ui-form:not([hidden])')).toBeNull(); + const summary: string = BookkeepingTestingUtilities.getText(getTabPanel(root, 'Filing').querySelector('ui-callout')); + expect(summary).toContain('The E-Bilanz was sent to the tax administration on 03/02/2026'); + expect(summary).toContain('and accepted, with the ticket ET-2025-0005.'); + expect(summary).toContain('To correct it, reopen the fiscal year, post the corrections and close it again.'); + }); + + test('disables sending and sending as a test with plain words while no transmitter is configured', async () => { + const [fixture, root] = await render({ stage: 'prepared', transmitter: 'missing' }, {}, HostComponent); + const host: HostComponent | undefined = fixture.componentInstance instanceof HostComponent ? fixture.componentInstance : undefined; + // to a user who doesn't upload the certificate, sending isn't set up, whatever it lacks + host?.canManage.set(false); + await BookkeepingTestingUtilities.renderAnswered(fixture); + + await goToStep(fixture, root, 'Test'); + const test: HTMLButtonElement = findButton(getShownStep(root), 'Send as a test'); + expect(test.disabled).toBe(true); + expect(getDescription(test)).toBe(NO_TRANSMITTER); + await goToStep(fixture, root, 'Send or file by hand'); + const transmit: HTMLButtonElement = findButton(getShownStep(root), 'Send to the tax administration'); + expect(transmit.disabled).toBe(true); + expect(getDescription(transmit)).toBe(NO_TRANSMITTER); + for (const reason of TECHNICAL_REASONS) { + expect(BookkeepingTestingUtilities.getText(root)).not.toContain(reason); + } + // filing by hand works without one + expect(findButton(getShownStep(root), 'Mark as filed by hand').disabled).toBe(false); + expect(findButton(getShownStep(root), 'Download XBRL (.xbrl)').disabled).toBe(false); + }); + + test('says that sending needs the certificate as well, to a user who uploads it, without the reason of the api', async () => { + const [fixture, root] = await render({ stage: 'prepared', transmitter: 'no-certificate' }); + + await goToStep(fixture, root, 'Test'); + + expect(getDescription(findButton(getShownStep(root), 'Send as a test'))).toBe(`${NO_TRANSMITTER} ${CERTIFICATE_MISSING}`); + for (const reason of TECHNICAL_REASONS) { + expect(BookkeepingTestingUtilities.getText(root)).not.toContain(reason); + } + }); + + test('files it by hand without a test and without a transmitter: downloads it and marks it as filed', async () => { + vi.stubGlobal('URL', Object.assign(URL, { createObjectURL: vi.fn(() => 'blob:export'), revokeObjectURL: vi.fn() })); + vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => undefined); + const [fixture, root] = await render({ stage: 'prepared', transmitter: 'missing' }); + + // the test is left out, its button disabled + await goToStep(fixture, root, 'Test'); + await click(fixture, getShownStep(root), 'Next'); + expect(getStep(root)).toBe('Send or file by hand'); + await click(fixture, getShownStep(root), 'Download XBRL (.xbrl)'); + findButton(getShownStep(root), 'Mark as filed by hand').click(); + const dialog: HTMLDialogElement = await findDialog(); + await attachFile(fixture, dialog, new File(['%PDF-1.7'], 'protocol-2025.pdf', { type: 'application/pdf' })); + FormTestingUtilities.click(dialog, 'Mark as filed'); + await BookkeepingTestingUtilities.renderAnswered(fixture); + + expect(findSent()).toEqual([`POST ${STATE_URL}/manual-filing`]); + expect(backend.requests.filter(request => request.url.endsWith('/export'))).toHaveLength(1); + expect(backend.getFilings().map(record => record.kind)).toEqual([EBilanzFilingKind.PREPARED, EBilanzFilingKind.MANUAL_FILING]); + expect(root.querySelector('ui-badge')?.textContent.trim()).toBe('Filed'); + expect(getDoneSteps(root)).toEqual(STEPS); + expect(BookkeepingTestingUtilities.getText(getTabPanel(root, 'Filing').querySelector('ui-callout'))) + .toContain('The E-Bilanz was marked as filed by hand on 03/02/2026'); + }); + + test('sends nothing by itself: not when it loads, also once it could be sent for real, and not when going to a step or a tab', async () => { + const [fixture, root] = await render({ stage: 'tested', transmitter: 'configured' }); + await new Promise(resolve => setTimeout(resolve, 50)); + await BookkeepingTestingUtilities.renderAnswered(fixture); + expect(findSent()).toEqual([]); + + for (const step of ['Prepare', 'Review', 'Test', 'Send or file by hand', 'Review']) { + await goToStep(fixture, root, step); + } + await click(fixture, getElement(root, 'ngx-e-bilanz-content'), 'Income statement'); + for (const tab of ['Records', 'Account mappings', 'ELSTER certificate', 'Filing']) { + await openTab(fixture, root, tab); + expect(getTab(root)).toBe(tab); + } + // the button of the last step shows the records + await goToStep(fixture, root, 'Send or file by hand'); + await click(fixture, getShownStep(root), 'Show the records'); + expect(getTab(root)).toBe('Records'); + expect(document.activeElement?.textContent.trim()).toBe('Records'); + + expect(findSent()).toEqual([]); + }); + + test('disables sending for real until a test of the same content was accepted, which opens the last step', async () => { + const [fixture, root] = await render({ stage: 'prepared', transmitter: 'configured' }); + const transmit: HTMLButtonElement = findButton(getElement(root, 'ngx-e-bilanz-filing'), 'Send to the tax administration'); + expect(transmit.disabled).toBe(true); + expect(getDescription(transmit)).toBe('Send it as a test first: it can be sent for real once a test of the same content was accepted.'); + + useFakeTimers(); + await goToStep(fixture, root, 'Test'); + await click(fixture, getShownStep(root), 'Send as a test'); + expect(findRequests('POST', 'test-transmission')).toHaveLength(1); + await wait(fixture, 6000); + + const message: HTMLElement = getMessage(root); + expect(BookkeepingTestingUtilities.getText(message)).toBe('The test was accepted. The E-Bilanz can be sent for real now.'); + expect(document.activeElement).toBe(message); + expect(getStep(root)).toBe('Send or file by hand'); + expect(findButton(getShownStep(root), 'Send to the tax administration').disabled).toBe(false); + // the test sent nothing for real + expect(findRequests('POST', 'transmission')).toEqual([]); + }); + + test('shows what the tax administration answered when it refuses a test, and keeps sending for real disabled', async () => { + const [fixture, root] = await render({ stage: 'prepared', transmitter: 'configured', transmissionOutcome: 'refused' }); + + useFakeTimers(); + await goToStep(fixture, root, 'Test'); + await click(fixture, getShownStep(root), 'Send as a test'); + await wait(fixture, 6000); + + expect(BookkeepingTestingUtilities.getText(getMessage(root).querySelector('[role="alert"]'))) + .toBe('Error The test was refused. The tax administration answered: Die Steuernummer 1121081508150 ist für das Finanzamt 1121 ungültig.'); + expect(getStep(root)).toBe('Test'); + expect(findButton(getElement(root, 'ngx-e-bilanz-filing'), 'Send to the tax administration').disabled).toBe(true); + }); + + test('asks before sending for real, saying what is sent and that it is final, and sends nothing when the user cancels', async () => { + const [fixture, root] = await render({ stage: 'tested', transmitter: 'configured' }); + + findButton(getShownStep(root), 'Send to the tax administration').click(); + const dialog: HTMLDialogElement = await findDialog(); + const text: string = BookkeepingTestingUtilities.getText(dialog); + expect(text).toContain('Send the E-Bilanz 2025 to the tax administration?'); + expect(text).toContain('This sends the E-Bilanz of Acme Software UG (haftungsbeschränkt), tax number 1121081508150, for the fiscal year ' + + '01/01/2025 – 12/31/2025, as it was prepared on 03/02/2026'); + expect(text).toContain('It states 20 positions in the version 6.9 of the taxonomy, with the accounts of each position and the statement ' + + 'of changes in fixed assets. Its balance sheet: The commercial balance sheet, which is the tax balance sheet as well (Einheitsbilanz).'); + expect(text).toContain('with the ticket TT-2025-0003.'); + expect(text).toContain('This is final: the tax administration keeps what it receives, and it can\'t be taken back.'); + FormTestingUtilities.click(dialog, 'Cancel'); + await BookkeepingTestingUtilities.renderAnswered(fixture); + + expect(findRequests('POST', 'transmission')).toEqual([]); + expect(backend.getFilings().map(record => record.kind)) + .toEqual([EBilanzFilingKind.PREPARED, EBilanzFilingKind.TEST_TRANSMISSION, EBilanzFilingKind.TEST_TRANSMISSION]); + }); + + test('sends for real once the user confirmed, and shows the transmission with its ticket and protocol', async () => { + const [fixture, root] = await render({ stage: 'tested', transmitter: 'configured' }); + + useFakeTimers(); + findButton(getShownStep(root), 'Send to the tax administration').click(); + FormTestingUtilities.click(await findDialog(), 'Send for real'); + await BookkeepingTestingUtilities.renderAnswered(fixture); + expect(findRequests('POST', 'transmission')).toHaveLength(1); + await wait(fixture, 6000); + + expect(BookkeepingTestingUtilities.getText(getMessage(root))).toBe('The E-Bilanz was sent and accepted, with the ticket ET-2025-0005.'); + expect(root.querySelector('ui-badge')?.textContent.trim()).toBe('Filed'); + expect(getDoneSteps(root)).toEqual(STEPS); + const rows: string[] = [...getTabPanel(root, 'Records').querySelectorAll('tbody tr')].map(row => BookkeepingTestingUtilities.getText(row)); + // the record each transmission started with, and the one of its result + expect(rows.map(row => row.split(' ')[0])).toEqual(['Prepared', 'Test', 'Test', 'Transmission', 'Transmission']); + expect(rows[3]).toContain('Started'); + expect(rows[4]).toContain('ET-2025-0005 Accepted'); + expect(rows[4]).toContain('Download transmission-protocol-2025.pdf'); + // once it is filed, it isn't sent or filed again + await goToStep(fixture, root, 'Send or file by hand'); + expect(getDescription(findButton(getShownStep(root), 'Send to the tax administration'))).toBe('The E-Bilanz is filed as it was prepared.'); + expect(findButton(getShownStep(root), 'Mark as filed by hand').disabled).toBe(true); + }); + + test('downloads the export of each exporter under the name the api gives it', async () => { + // jsdom has no object urls, which saving a file in the browser takes, and doesn't follow links. + vi.stubGlobal('URL', Object.assign(URL, { createObjectURL: vi.fn(() => 'blob:export'), revokeObjectURL: vi.fn() })); + const saved: string[] = []; + vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function(this: HTMLAnchorElement) { + saved.push(this.download); + }); + const [fixture, root] = await render({ stage: 'prepared' }); + + await goToStep(fixture, root, 'Send or file by hand'); + await click(fixture, getShownStep(root), 'Download XBRL (.xbrl)'); + + expect(backend.requests.filter(request => request.url.endsWith('/export')).map(request => request.params.get('exporter'))).toEqual(['xbrl']); + expect(saved).toEqual(['e-bilanz-2025-01-01-2025-12-31.xbrl']); + }); + + test('disables the download with plain words while the app can\'t write the E-Bilanz as a file', async () => { + const [fixture, root] = await render({ stage: 'prepared', exporters: [] }); + + await goToStep(fixture, root, 'Send or file by hand'); + + const button: HTMLButtonElement = findButton(getShownStep(root), 'Download the E-Bilanz'); + expect(button.disabled).toBe(true); + expect(getDescription(button)).toBe('It can\'t be downloaded: this app can\'t write the E-Bilanz as a file. To download it, ask your administrator ' + + 'to set up the download.'); + }); + + test('marks it as filed by hand only with the protocol', async () => { + const [fixture, root] = await render({ stage: 'prepared' }); + await goToStep(fixture, root, 'Send or file by hand'); + + findButton(getShownStep(root), 'Mark as filed by hand').click(); + const dialog: HTMLDialogElement = await findDialog(); + FormTestingUtilities.click(dialog, 'Mark as filed'); + await BookkeepingTestingUtilities.renderAnswered(fixture); + expect(findRequests('POST', 'manual-filing')).toEqual([]); + expect(BookkeepingTestingUtilities.getText(dialog)).toContain('This field is required.'); + + const protocol: File = new File(['%PDF-1.7'], 'protocol-2025.pdf', { type: 'application/pdf' }); + await attachFile(fixture, dialog, protocol); + FormTestingUtilities.click(dialog, 'Mark as filed'); + await BookkeepingTestingUtilities.renderAnswered(fixture); + + const sent: unknown = findRequests('POST', 'manual-filing')[0]?.body; + expect(sent instanceof FormData && sent.get('protocol')).toEqual(protocol); + expect(BookkeepingTestingUtilities.getText(getMessage(root))).toBe('The E-Bilanz was marked as filed by hand.'); + expect(root.querySelector('ui-badge')?.textContent.trim()).toBe('Filed'); + expect(BookkeepingTestingUtilities.getText(getTabPanel(root, 'Records').querySelector('tbody tr:last-child'))).toContain('Filed by hand'); + }); + + test('uploads the certificate with its PIN, which it never shows again, and can send then', async () => { + const [fixture, root] = await render({ stage: 'prepared', transmitter: 'no-certificate' }); + await openTab(fixture, root, 'ELSTER certificate'); + const certificate: HTMLElement = getElement(root, 'ngx-e-bilanz-certificate'); + expect(BookkeepingTestingUtilities.getText(certificate)).toContain('No certificate is uploaded.'); + + const file: File = new File(['pfx'], 'acme.pfx', { type: 'application/x-pkcs12' }); + await attachFile(fixture, certificate, file); + await BookkeepingTestingUtilities.type(fixture, FormTestingUtilities.findInput(certificate, 'pin'), '123456'); + await click(fixture, certificate, 'Upload the certificate'); + + const sent: unknown = backend.requests.find(request => request.method === 'PUT')?.body; + expect(sent instanceof FormData && [sent.get('certificate'), sent.get('pin')]).toEqual([file, '123456']); + expect(FormTestingUtilities.findInput(certificate, 'pin')?.value).toBe(''); + expect(BookkeepingTestingUtilities.getText(certificate)).not.toContain('123456'); + expect(BookkeepingTestingUtilities.getText(certificate)).toContain('A certificate was uploaded on 03/02/2026'); + expect(findButton(getElement(root, 'ngx-e-bilanz-test'), 'Send as a test').disabled).toBe(false); + }); + + test('hides what the user may not do, and still previews', async () => { + const [fixture, root] = await render({ stage: 'prepared', transmitter: 'configured' }); + const host: HostComponent | undefined = fixture.componentInstance instanceof HostComponent ? fixture.componentInstance : undefined; + host?.canPrepare.set(false); + host?.canTransmit.set(false); + host?.canManage.set(false); + await BookkeepingTestingUtilities.renderAnswered(fixture); + + expect(getTabs(root).map(tab => tab.textContent.trim())).toEqual(['Filing', 'Records']); + expect(root.querySelector('ngx-e-bilanz-account-mappings, ngx-e-bilanz-certificate, ngx-e-bilanz-test, ngx-e-bilanz-filing')).toBeNull(); + expect(findButtonTexts(root)).not.toContain('Prepare'); + for (const step of ['Test', 'Send or file by hand']) { + await goToStep(fixture, root, step); + expect(BookkeepingTestingUtilities.getText(getShownStep(root))) + .toContain('You may read the E-Bilanz, but not send it, download it or mark it as filed.'); + } + + await goToStep(fixture, root, 'Prepare'); + await preview(fixture, root); + expect(findRequests('POST', 'preview')).toHaveLength(1); + expect(BookkeepingTestingUtilities.getText(getElement(root, 'ngx-e-bilanz-content'))).toContain('A preview, as the books state it now. It isn\'t prepared.'); + // a finding about an account has no link while the account mappings don't show + expect(root.querySelectorAll('ngx-e-bilanz-findings a')).toHaveLength(0); + }); + + test('takes the permissions from the config of the E-Bilanz while the inputs aren\'t set', async () => { + const [fixture, root] = await render({ stage: 'prepared' }, { canTransmit: true }, ConfiguredHostComponent); + + expect(findButton(getElement(root, 'ngx-e-bilanz-test'), 'Send as a test')).toBeDefined(); + await goToStep(fixture, root, 'Send or file by hand'); + expect(findButtonTexts(getShownStep(root))).not.toContain('Download XBRL (.xbrl)'); + expect(findButtonTexts(getShownStep(root))).toContain('Mark as filed by hand'); + expect(getTabs(root).map(tab => tab.textContent.trim())).toEqual(['Filing', 'Records']); + }); + + test('goes back to preparing it, saying why, once the books changed since it was prepared', async () => { + const [, root] = await render({ stage: 'tested', transmitter: 'configured', booksChanged: true }); + + expect(root.querySelector('ui-badge')?.textContent.trim()).toBe('Prepared before the books changed'); + expect(getStep(root)).toBe('Prepare'); + expect(BookkeepingTestingUtilities.getText(getTabPanel(root, 'Filing').querySelector('ui-callout'))) + .toContain('The books changed since the E-Bilanz was prepared. Prepare it again.'); + expect(getDescription(findButton(getElement(root, 'ngx-e-bilanz-filing'), 'Send to the tax administration'))) + .toBe('The books changed since the E-Bilanz was prepared. Prepare it again.'); + }); + + describe('sending in the background', () => { + test('says that it is being sent, disables sending, and loads again less and less often until the result is there', async () => { + useFakeTimers(); + const [fixture, root] = await render({ stage: 'tested', transmitter: 'configured', transmissionDurationInMs: 30_000 }); + + findButton(getShownStep(root), 'Send to the tax administration').click(); + FormTestingUtilities.click(await findDialog(), 'Send for real'); + await BookkeepingTestingUtilities.renderAnswered(fixture); + const loadedBefore: number = findStateRequests().length; + + const transmission: string = BookkeepingTestingUtilities.getText(getElement(root, 'ngx-e-bilanz-transmission')); + expect(transmission).toContain('Sending to ELSTER…'); + expect(transmission).toContain('This can take several minutes. You can leave this page; the result is recorded.'); + const transmit: HTMLButtonElement = findButton(getShownStep(root), 'Send to the tax administration'); + expect(transmit.disabled).toBe(true); + expect(getDescription(transmit)).toBe('It is being sent to ELSTER right now. Wait for the result, which shows above.'); + expect(findButton(getShownStep(root), 'Mark as filed by hand').disabled).toBe(true); + expect(findButton(getElement(root, 'ngx-e-bilanz-test'), 'Send as a test').disabled).toBe(true); + + // after 2, 3, 4.5, 6.75 and 10.125 seconds: 26.375 seconds + await wait(fixture, 27_000); + expect(findStateRequests().length - loadedBefore).toBe(5); + expect(getElement(root, 'ngx-e-bilanz-transmission').textContent).toContain('Sending to ELSTER…'); + + // the result is there after 30 seconds, and loaded with the next poll after 41.6 seconds + await wait(fixture, 15_000); + expect(BookkeepingTestingUtilities.getText(getMessage(root))).toContain('The E-Bilanz was sent and accepted, with the ticket ET-2025-0005.'); + expect(getElement(root, 'ngx-e-bilanz-transmission').textContent).not.toContain('Sending to ELSTER'); + expect(root.querySelector('ui-badge')?.textContent.trim()).toBe('Filed'); + + // and it stops then, sending nothing by itself + const loadedAfter: number = findStateRequests().length; + await wait(fixture, 120_000); + expect(findStateRequests()).toHaveLength(loadedAfter); + expect(findSent()).toEqual([`POST ${STATE_URL}/transmission`]); + }); + + test('goes on waiting for a transmission that was being sent when it opened', async () => { + useFakeTimers(); + const [fixture, root] = await render({ stage: 'sending', transmitter: 'configured' }); + + expect(getElement(root, 'ngx-e-bilanz-transmission').textContent).toContain('Sending to ELSTER…'); + await wait(fixture, 6000); + + expect(BookkeepingTestingUtilities.getText(getMessage(root))).toContain('The E-Bilanz was sent and accepted, with the ticket ET-2025-0005.'); + expect(findSent()).toEqual([]); + }); + + test('stops loading again once it is destroyed', async () => { + useFakeTimers(); + const [fixture] = await render({ stage: 'sending', transmitter: 'configured', transmissionDurationInMs: 600_000 }); + await wait(fixture, 2500); + const loaded: number = findStateRequests().length; + + fixture.destroy(); + await vi.advanceTimersByTimeAsync(120_000); + + expect(findStateRequests()).toHaveLength(loaded); + }); + + test('says what failed when nothing was sent, which can be sent again', async () => { + useFakeTimers(); + const [fixture, root] = await render({ stage: 'sending', transmitter: 'configured', transmissionOutcome: 'not-sent' }); + + await wait(fixture, 6000); + + expect(BookkeepingTestingUtilities.getText(getMessage(root).querySelector('[role="alert"]'))) + .toBe('Error Sending failed, and nothing reached the tax administration, so it can be sent again. What failed: ' + + 'The ELSTER certificate could not be read: its PIN is wrong.'); + expect(getElement(root, 'ngx-e-bilanz-transmission').textContent).toBe(''); + expect(findButton(getShownStep(root), 'Send to the tax administration').disabled).toBe(false); + }); + + test('warns that a failed transmission may have been sent, with what failed', async () => { + useFakeTimers(); + const [fixture, root] = await render({ stage: 'sending', transmitter: 'configured', transmissionOutcome: 'failed' }); + + await wait(fixture, 6000); + + const warning: string = BookkeepingTestingUtilities.getText(getElement(root, 'ngx-e-bilanz-transmission [role="alert"]')); + expect(warning).toContain('It may have been sent. Check in ELSTER whether it arrived before you do anything else.'); + expect(warning).toContain('The transmission started on 03/02/2026'); + expect(warning).toContain('The connection to ELSTER was reset while the E-Bilanz was sent. read ECONNRESET'); + expect(getDescription(findButton(getShownStep(root), 'Send to the tax administration'))) + .toBe('It may have been sent already. Check in ELSTER whether it arrived, then mark it as filed by hand or say that ELSTER didn\'t receive it.'); + }); + }); + + describe('a transmission whose result is not known', () => { + test('keeps one for real from being sent, and is settled by marking it as filed by hand', async () => { + const [fixture, root] = await render({ stage: 'unknown', transmitter: 'configured' }); + const warning: HTMLElement = getElement(root, 'ngx-e-bilanz-transmission [role="alert"]'); + + expect(BookkeepingTestingUtilities.getText(warning)).toContain('The result isn\'t known'); + expect(BookkeepingTestingUtilities.getText(warning)).toContain('It may have been sent. Check in ELSTER whether it arrived before you do anything else.'); + expect(BookkeepingTestingUtilities.getText(warning)).toContain('The transmitter did not answer in time.'); + expect(findButton(getShownStep(root), 'Send to the tax administration').disabled).toBe(true); + // a test is another kind, which it doesn't keep from being sent + expect(findButton(getElement(root, 'ngx-e-bilanz-test'), 'Send as a test').disabled).toBe(false); + + findButton(warning, 'Mark as filed by hand').click(); + const dialog: HTMLDialogElement = await findDialog(); + await attachFile(fixture, dialog, new File(['%PDF-1.7'], 'elster-2025.pdf', { type: 'application/pdf' })); + FormTestingUtilities.click(dialog, 'Mark as filed'); + await BookkeepingTestingUtilities.renderAnswered(fixture); + + expect(findSent()).toEqual([`POST ${STATE_URL}/manual-filing`]); + expect(root.querySelector('ngx-e-bilanz-transmission [role="alert"]')).toBeNull(); + expect(root.querySelector('ui-badge')?.textContent.trim()).toBe('Filed'); + }); + + test('asks what confirming that ELSTER didn\'t receive it means, sends nothing when cancelled, and can be sent again once confirmed', async () => { + const [fixture, root] = await render({ stage: 'unknown', transmitter: 'configured' }); + + findButton(getElement(root, 'ngx-e-bilanz-transmission'), 'ELSTER did not receive it').click(); + let dialog: HTMLDialogElement = await findDialog(); + const text: string = BookkeepingTestingUtilities.getText(dialog); + expect(text).toContain('ELSTER did not receive it?'); + expect(text).toContain('Only confirm this once you checked in ELSTER that it did not arrive.'); + expect(text).toContain('If it did arrive, sending it again files it twice.'); + FormTestingUtilities.click(dialog, 'Cancel'); + await BookkeepingTestingUtilities.renderAnswered(fixture); + expect(findSent()).toEqual([]); + + findButton(getElement(root, 'ngx-e-bilanz-transmission'), 'ELSTER did not receive it').click(); + dialog = await findDialog(); + FormTestingUtilities.click(dialog, 'It did not arrive'); + await BookkeepingTestingUtilities.renderAnswered(fixture); + + expect(findSent()).toEqual([`POST ${STATE_URL}/transmission-not-received`]); + expect(BookkeepingTestingUtilities.getText(getMessage(root))).toContain('Recorded that ELSTER did not receive it. It can be sent again.'); + expect(root.querySelector('ngx-e-bilanz-transmission [role="alert"]')).toBeNull(); + expect(findButton(getShownStep(root), 'Send to the tax administration').disabled).toBe(false); + expect(backend.getFilings().at(-1)?.status).toBe('not-received'); + }); + + test('shows the refusal of the api, like a second factor the user didn\'t give', async () => { + const [fixture, root] = await render({ stage: 'unknown', transmitter: 'configured' }); + vi.spyOn(backend, 'findAnswer').mockImplementationOnce(() => ({ + status: 403, + body: { status: 403, name: 'SecondFactorRequiredError', message: 'The request needs a second factor.', paragraphs: ['The request needs a second factor.'] } + })); + + findButton(getElement(root, 'ngx-e-bilanz-transmission'), 'ELSTER did not receive it').click(); + FormTestingUtilities.click(await findDialog(), 'It did not arrive'); + await BookkeepingTestingUtilities.renderAnswered(fixture); + + expect(BookkeepingTestingUtilities.getText(getMessage(root).querySelector(':scope > [role="alert"]'))).toBe('Error The request needs a second factor.'); + expect(root.querySelector('ngx-e-bilanz-transmission [role="alert"]')).not.toBeNull(); + }); + }); + + describe('correcting a filed E-Bilanz', () => { + test('asks what the correction corrects once the books changed since it was filed, and prepares it with that', async () => { + const [fixture, root] = await render({ stage: 'transmitted', transmitter: 'configured', booksChanged: true }); + const preparation: HTMLElement = getElement(root, 'ngx-e-bilanz-preparation'); + + expect(root.querySelector('ui-badge')?.textContent.trim()).toBe('Filed, being corrected'); + expect(getStep(root)).toBe('Prepare'); + expect(BookkeepingTestingUtilities.getText(getTabPanel(root, 'Filing').querySelector('ui-callout'))) + .toContain('The books, or what the E-Bilanz states beside them, changed since it was filed. Prepare a correction'); + const choice: string = BookkeepingTestingUtilities.getText(preparation.querySelector('ui-input-cards')); + expect(choice).toContain('What the correction corrects'); + for (const option of ['Errors corrected', 'A choice changed', 'Both', 'Only more detail', 'Another correction']) { + expect(choice).toContain(option); + } + expect(choice).toContain('Nothing was wrong, but a choice the law allows is made differently now'); + // there is no default: it is required, and the preview waits for it + const previewButton: HTMLButtonElement = findButton(preparation, 'Preview'); + expect(previewButton.disabled).toBe(true); + expect(getDescription(previewButton)).toBe('Choose what the correction corrects first.'); + await click(fixture, getShownStep(root), 'Next'); + expect(getStep(root)).toBe('Prepare'); + + const errors: HTMLInputElement | null | undefined = [...preparation.querySelectorAll('label')] + .find(label => label.textContent.includes('Errors corrected')) + ?.querySelector('input[type="radio"]'); + errors?.click(); + await BookkeepingTestingUtilities.renderAnswered(fixture); + await click(fixture, preparation, 'Preview'); + await click(fixture, preparation, 'Prepare'); + + const input: unknown = { + accountingStandard: 'unified', + fixedAssets: [{ position: OFFICE_EQUIPMENT_POSITION, values: [{ column: DEPRECIATION_COLUMN, amount: '200.00' }] }], + revisionStatus: 'corrected' + }; + expect(findRequests('POST', 'preview').map(request => request.body)).toEqual([input]); + expect(findRequests('POST', 'preparation').map(request => request.body)).toEqual([input]); + expect(getStep(root)).toBe('Review'); + const records: string[] = [...getTabPanel(root, 'Records').querySelectorAll('tbody tr')].map(row => BookkeepingTestingUtilities.getText(row)); + expect(records.at(-1)).toContain('Prepared Corrects the record "Transmission" of 03/02/2026'); + expect(records.at(-1)).toContain(': Errors corrected'); + }); + + test('shows the records of a correction with the filing they correct', async () => { + const [fixture, root] = await render({ stage: 'correcting', transmitter: 'configured' }); + + expect(getStep(root)).toBe('Review'); + await openTab(fixture, root, 'Records'); + + const filing: string | undefined = backend.getFilings().find(record => record.correctsFilingId != undefined)?.correctsFilingId ?? undefined; + expect(backend.getFilings().find(record => record.id === filing)?.status).toBe('accepted'); + const records: string[] = [...getTabPanel(root, 'Records').querySelectorAll('tbody tr')].map(row => BookkeepingTestingUtilities.getText(row)); + expect(records.at(-1)).toContain('Prepared Corrects the record "Transmission" of 03/02/2026'); + expect(records.at(-1)).toContain(': Errors corrected'); + }); + + test('doesn\'t ask what a preparation corrects before the E-Bilanz is filed', async () => { + const [, root] = await render({ stage: 'tested', transmitter: 'configured', booksChanged: true }); + + expect(root.querySelector('ngx-e-bilanz-preparation ui-input-cards')).toBeNull(); + }); + }); +}); diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz.component.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz.component.ts new file mode 100644 index 0000000..f70c7bb --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz.component.ts @@ -0,0 +1,704 @@ +import { DOCUMENT } from '@angular/common'; +import { HttpErrorResponse } from '@angular/common/http'; +import { + afterNextRender, + booleanAttribute, + Component, + computed, + DestroyRef, + effect, + ElementRef, + inject, + Injector, + input, + InputSignalWithTransform, + linkedSignal, + resource, + ResourceRef, + Signal, + signal, + untracked, + viewChild, + WritableSignal +} from '@angular/core'; +import { + BookkeepingDayUtilities, + BookkeepingFiscalYearUtilities, + BookkeepingViewDirective, + E_BILANZ_CONFIG, + EBilanzConfig, + EBilanzLabels, + EBilanzService +} from '@service-soft/ngx-bookkeeping/api'; +import { BadgeColor, BadgeComponent } from '@service-soft/ui/badge'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { DataListComponent, DataListItem } from '@service-soft/ui/data-list'; +import { EmptyStateComponent } from '@service-soft/ui/empty-state'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { InputOption } from '@service-soft/ui/input'; +import { InputSelectComponent } from '@service-soft/ui/input-select'; +import { LoadingDirective } from '@service-soft/ui/loading'; +import { STEPPER_CONFIG, StepComponent, StepperBeforeNext, StepperComponent, StepperConfig } from '@service-soft/ui/stepper'; +import { TabComponent, TabsComponent } from '@service-soft/ui/tabs'; +import { + BookkeepingAccountModel, + EBilanzCertificateSettingsModel, + EBilanzContentModel, + EBilanzFilingKind, + EBilanzFilingModel, + EBilanzFindingModel, + EBilanzPreviewModel, + EBilanzStateModel, + EBilanzTransmissionModel, + EBilanzTransmissionStatus, + FiscalYearModel +} from 'zibri-contract'; + +import { EBilanzAccountMappingsComponent } from './e-bilanz-account-mappings.component'; +import { EBilanzCertificateComponent } from './e-bilanz-certificate.component'; +import { EBilanzContentTab } from './e-bilanz-content-tab.type'; +import { EBilanzContentComponent } from './e-bilanz-content.component'; +import { EBilanzFilingComponent } from './e-bilanz-filing.component'; +import { EBilanzFilingsComponent } from './e-bilanz-filings.component'; +import { EBilanzFindingTarget } from './e-bilanz-finding-target.model'; +import { EBilanzFindingsComponent } from './e-bilanz-findings.component'; +import { EBilanzOutcome } from './e-bilanz-outcome.model'; +import { EBilanzPhase } from './e-bilanz-phase.type'; +import { EBilanzPreparationComponent } from './e-bilanz-preparation.component'; +import { EBilanzTab } from './e-bilanz-tab.type'; +import { EBilanzTestComponent } from './e-bilanz-test.component'; +import { EBilanzTransmissionComponent } from './e-bilanz-transmission.component'; +import { EBilanzViewUtilities } from './e-bilanz-view.utilities'; + +// the parts of the E-Bilanz of a fiscal year are headed one level below it, and a heading of level 6 has no level +// below. +const SECTION_LEVELS: Record = { 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 6 }; + +// the step filing opens at, by how far it is filed: preparing, reviewing what was prepared, or sending it once a test of +// it was accepted. Filed, every step is done, which the stepper shows by a step after the last. +const STEP_OF_PHASE: Record = { unprepared: 0, outdated: 0, prepared: 1, tested: 3, filed: 4 }; + +// the steps after the review need what was reviewed to be prepared, as the books state it now. +const PREPARED_PHASES: Set = new Set(['prepared', 'tested', 'filed']); + +const TABS: EBilanzTab[] = ['filing', 'records', 'accountMappings', 'certificate']; + +// how long the E-Bilanz waits before it loads again while a transmission runs: every few seconds at first, then less +// often, as a transmission can take many minutes. Loading it again only reads, it never sends. +const POLL_DELAY_IN_MS: number = 2000; +const POLL_BACKOFF: number = 1.5; +const MAX_POLL_DELAY_IN_MS: number = 20_000; + +let nextId: number = 0; + +/** + * What the status badge of the E-Bilanz says. + */ +type EBilanzStatusView = { + /** + * The status. + */ + label: string, + /** + * The color of the badge. + */ + color: BadgeColor +}; + +/** + * The config of the steppers of the E-Bilanz: the one of the app, whose "Step 5 of 4" of a filed E-Bilanz, whose + * every step is done, says "Step 4 of 4". + * @returns The config of the parent injector, with the progress at most at the last step. + */ +function resolveStepperConfig(): StepperConfig { + const parent: StepperConfig = inject(STEPPER_CONFIG, { skipSelf: true }); + return { ...parent, progressLabel: (current, total) => parent.progressLabel(Math.min(current, total), total) }; +} + +/** + * The E-Bilanz of the books of provideBookkeepingConfig, by the routes at the baseUrl of provideEBilanzConfig: + * ``. It shows the E-Bilanz of a closed fiscal year, the latest at + * first, with its status and its deadline, and the tabs of filing it, its records, and with `canManage` the account + * mappings and the ELSTER certificate. + * + * Filing it takes four steps: preparing it with the balance sheet the user chooses, of which there is no default, and + * the figures the findings ask for; reviewing what it needs and its content; sending it as a test; and sending it for + * real, or downloading it and marking it as filed by hand. A step opens once the one before is done, and the test is + * left out by whoever files it by hand. It opens at the step of how far it is filed. + * + * Nothing is ever sent by itself, also not by going to a step or a tab. With `canPrepare` it downloads with each + * exporter of the api, and with `canTransmit` it is sent as a test, sent for real once a test of the same content was + * accepted and the user confirmed what is sent, and marked as filed by hand with its protocol. A button that can't be + * used is disabled with why and how to enable it, like while the app can't send it. The defaults of the three come + * from the config. + * + * The api sends in the background, which can take minutes: while a transmission runs, the E-Bilanz says so and loads + * again every few seconds, then less often, until it has its result, also when it was opened while one ran, and stops + * once it is destroyed. A transmission whose result is not known may have reached the tax administration: a warning + * asks the user to check that in ELSTER, and then to mark it as filed by hand or to confirm that ELSTER didn't receive + * it. Nothing of its kind is sent until then. Once filed, it is corrected by preparing it again, which says what the + * correction corrects. + */ +@Component({ + selector: 'ngx-e-bilanz', + templateUrl: './e-bilanz.component.html', + imports: [ + BadgeComponent, + CalloutComponent, + DataListComponent, + EBilanzAccountMappingsComponent, + EBilanzCertificateComponent, + EBilanzContentComponent, + EBilanzFilingComponent, + EBilanzFilingsComponent, + EBilanzFindingsComponent, + EBilanzPreparationComponent, + EBilanzTestComponent, + EBilanzTransmissionComponent, + EmptyStateComponent, + HeadingComponent, + InputSelectComponent, + LoadingDirective, + StepComponent, + StepperComponent, + TabComponent, + TabsComponent + ], + providers: [{ provide: STEPPER_CONFIG, useFactory: resolveStepperConfig }], + host: { class: 'block' } +}) +export class EBilanzComponent extends BookkeepingViewDirective { + private readonly eBilanzService: EBilanzService = inject(EBilanzService); + + private readonly eBilanzConfig: EBilanzConfig = inject(E_BILANZ_CONFIG); + + private readonly document: Document = inject(DOCUMENT); + + private readonly injector: Injector = inject(Injector); + + private readonly destroyRef: DestroyRef = inject(DestroyRef); + + private readonly message: Signal | undefined> = viewChild>('message'); + + // the next time the E-Bilanz loads again while a transmission runs, and how often it did since that one started + private pollTimer: ReturnType | undefined = undefined; + + private pollCount: number = 0; + + private destroyed: boolean = false; + + // the transmissions seen running, whose result the E-Bilanz says once it has one + private readonly watchedTransmissionIds: Set = new Set(); + + private readonly records: Signal = viewChild(EBilanzFilingsComponent); + + /** + * Whether the user may prepare and download the E-Bilanz, like with `bookkeeping.e-bilanz.prepare`. + */ + readonly canPrepare: InputSignalWithTransform = input(this.eBilanzConfig.canPrepare, { transform: booleanAttribute }); + + /** + * Whether the user may send the E-Bilanz and mark it as filed by hand, like with `bookkeeping.e-bilanz.transmit`. + */ + readonly canTransmit: InputSignalWithTransform = input(this.eBilanzConfig.canTransmit, { transform: booleanAttribute }); + + /** + * Whether the user may map accounts and upload the certificate, like with `bookkeeping.e-bilanz.manage`, which + * shows their tabs. + */ + readonly canManage: InputSignalWithTransform = input(this.eBilanzConfig.canManage, { transform: booleanAttribute }); + + /** + * The texts of the E-Bilanz. + */ + protected readonly labels: EBilanzLabels = this.eBilanzConfig.labels; + + /** + * The level of the heading of the E-Bilanz of a fiscal year. + */ + protected readonly headingLevel: HeadingLevel = this.config.headingLevel; + + /** + * The level of the headings of its parts, like a step or a tab, one below. + */ + protected readonly sectionLevel: HeadingLevel = SECTION_LEVELS[this.config.headingLevel]; + + /** + * The level of the headings inside a step, one below the step. + */ + protected readonly stepContentLevel: HeadingLevel = SECTION_LEVELS[SECTION_LEVELS[this.config.headingLevel]]; + + /** + * What the ids of its elements start with, unique on the page. + */ + protected readonly idPrefix: string = `ngx-e-bilanz-${nextId++}`; + + private readonly accounts: ResourceRef = resource({ + loader: async () => await this.bookkeepingService.resolveAccounts() + }); + + /** + * The accounts of the books, which the findings and the mappings name. + */ + protected readonly accountList: Signal = computed(() => this.accounts.hasValue() ? this.accounts.value() ?? [] : []); + + /** + * The numbers of the accounts a finding about an account links to: none while the user may not map them, as the + * tab of the account mappings doesn't show then. + */ + protected readonly accountNumbers: Signal> = computed(() => { + return this.canManage() ? new Set(this.accountList().map(account => account.number)) : new Set(); + }); + + // the E-Bilanz states a closed fiscal year only, the latest first + private readonly closedFiscalYears: Signal = computed(() => { + return [...this.getFiscalYears()].reverse().filter(fiscalYear => fiscalYear.closedAt != undefined); + }); + + /** + * The closed fiscal years to choose from, the latest first. + */ + protected readonly closedFiscalYearOptions: Signal[]> = computed(() => { + return BookkeepingFiscalYearUtilities.resolveOptions(this.closedFiscalYears(), this.config.dateFormat, this.locale); + }); + + /** + * Whether the books have fiscal years, but none of them is closed. + */ + protected readonly hasNoClosedFiscalYears: Signal = computed(() => { + return this.fiscalYears.hasValue() && !this.hasNoFiscalYears() && !this.closedFiscalYears().length; + }); + + /** + * The id of the fiscal year whose E-Bilanz shows: the latest closed one at first. It stays while it is one of them. + */ + protected readonly eBilanzFiscalYearId: WritableSignal = linkedSignal({ + source: this.closedFiscalYears, + computation: (fiscalYears, previous) => { + if (previous?.value != undefined && fiscalYears.some(fiscalYear => fiscalYear.id === previous.value)) { + return previous.value; + } + return fiscalYears[0]?.id; + } + }); + + /** + * The fiscal year whose E-Bilanz shows. + */ + protected readonly eBilanzFiscalYear: Signal = computed(() => { + return this.closedFiscalYears().find(fiscalYear => fiscalYear.id === this.eBilanzFiscalYearId()); + }); + + // counts what changed the E-Bilanz, after each of which the preview is dropped + private readonly revision: WritableSignal = signal(0); + + // loaded again with reload, which keeps what shows while it loads, so the steps keep what they said + private readonly state: ResourceRef = resource({ + params: () => this.eBilanzFiscalYearId(), + loader: async ({ params }) => await this.eBilanzService.resolveState(params) + }); + + /** + * The E-Bilanz of the fiscal year, kept while it loads again, undefined while it loads for another fiscal year. + */ + protected readonly stateValue: Signal = computed(() => { + const state: EBilanzStateModel | undefined = this.state.hasValue() ? this.state.value() : undefined; + return state?.fiscalYearId === this.eBilanzFiscalYearId() ? state : undefined; + }); + + // the id of the transmission being sent right now, which the E-Bilanz loads again for until it has a result + private readonly runningTransmissionId: Signal = computed(() => { + const state: EBilanzStateModel | undefined = this.stateValue(); + return state == undefined ? undefined : EBilanzViewUtilities.findRunningTransmission(state)?.id; + }); + + // only loaded for a user who uploads the certificate, the only one its tab and what sending needs show to + private readonly certificateSettings: ResourceRef = resource({ + params: () => this.canManage() ? true : undefined, + loader: async () => await this.eBilanzService.resolveCertificateSettings() + }); + + /** + * Whether a certificate is uploaded, undefined while that loads. + */ + protected readonly certificateSettingsValue: Signal = computed(() => { + return this.certificateSettings.hasValue() ? this.certificateSettings.value() : undefined; + }); + + /** + * Whether it couldn't be loaded whether a certificate is uploaded. + */ + protected readonly certificateFailed: Signal = computed(() => this.certificateSettings.error() != undefined); + + /** + * Whether to say that sending needs the certificate as well: to a user who uploads it, while none is uploaded. + */ + protected readonly certificateMissing: Signal = computed(() => { + const settings: EBilanzCertificateSettingsModel | undefined = this.certificateSettingsValue(); + return this.canManage() && settings != undefined && settings.certificateUploadedAt == undefined; + }); + + /** + * How far the E-Bilanz is filed, undefined while it loads. + */ + protected readonly phase: Signal = computed(() => { + const state: EBilanzStateModel | undefined = this.stateValue(); + return state == undefined ? undefined : EBilanzViewUtilities.resolvePhase(state); + }); + + /** + * The index of the step of filing that shows: the one of how far the E-Bilanz is filed, again once that changes. + * Going to a step sends nothing. + */ + protected readonly step: WritableSignal = linkedSignal({ + source: this.phase, + computation: phase => phase == undefined ? 0 : STEP_OF_PHASE[phase] + }); + + /** + * Why the step after the review didn't open, or an empty string. It starts over at every step. + */ + protected readonly stepReason: WritableSignal = linkedSignal({ source: this.step, computation: () => '' }); + + /** + * The tab that shows. + */ + protected readonly tab: WritableSignal = signal('filing'); + + /** + * The tab of the content that shows. + */ + protected readonly contentTab: WritableSignal = signal('balanceSheet'); + + /** + * What a step last said about a request the user sent, undefined for nothing. It starts over with another fiscal + * year. + */ + protected readonly outcome: WritableSignal = linkedSignal({ + source: this.eBilanzFiscalYearId, + computation: () => undefined + }); + + /** + * What the steps last announced, or an empty string, in a live region that always exists. + */ + protected readonly announcement: Signal = computed(() => { + const outcome: EBilanzOutcome | undefined = this.outcome(); + return outcome?.kind === 'announcement' ? outcome.message : ''; + }); + + /** + * Whether the user may neither download nor send the E-Bilanz, which the last step says. + */ + protected readonly mayNotFile: Signal = computed(() => !this.canPrepare() && !this.canTransmit()); + + /** + * The last preview, which shows in place of the latest preparation. It starts over with another fiscal year, and + * once something changed the E-Bilanz. + */ + protected readonly preview: WritableSignal = linkedSignal({ + source: computed(() => `${this.eBilanzFiscalYearId() ?? ''} ${this.revision()}`), + computation: () => undefined + }); + + /** + * The content that shows: of the preview, or of the latest preparation. + */ + protected readonly content: Signal = computed(() => { + return this.preview()?.content ?? this.stateValue()?.content ?? undefined; + }); + + /** + * What the E-Bilanz needs: as the preview states it, or as the books state it with what the latest preparation took. + */ + protected readonly findings: Signal = computed(() => this.preview()?.findings ?? this.stateValue()?.findings ?? []); + + /** + * What the content that shows is: a preview, or the latest preparation and when it was prepared. + */ + protected readonly contentNote: Signal = computed(() => { + if (this.preview() != undefined) { + return this.labels.review.previewNote; + } + const state: EBilanzStateModel | undefined = this.stateValue(); + const preparation: EBilanzFilingModel | undefined = state == undefined ? undefined : EBilanzViewUtilities.findPreparation(state); + return preparation == undefined ? this.labels.review.noContent : this.labels.review.preparationNote(this.formatMoment(preparation.createdAt)); + }); + + /** + * How the E-Bilanz was filed, or undefined while it isn't. + */ + protected readonly filedSummary: Signal = computed(() => { + const state: EBilanzStateModel | undefined = this.stateValue(); + const filing: EBilanzFilingModel | undefined = state == undefined ? undefined : EBilanzViewUtilities.findFiling(state); + if (filing == undefined) { + return undefined; + } + const moment: string = this.formatMoment(filing.createdAt); + return filing.kind === EBilanzFilingKind.TRANSMISSION + ? this.labels.common.transmittedSummary(moment, filing.ticket ?? '') + : this.labels.common.manuallyFiledSummary(moment); + }); + + /** + * The heading of the E-Bilanz of the fiscal year. + */ + protected readonly title: Signal = computed(() => { + const fiscalYear: FiscalYearModel | undefined = this.eBilanzFiscalYear(); + return fiscalYear == undefined ? '' : this.labels.common.eBilanz(this.resolveFiscalYearLabel(fiscalYear)); + }); + + /** + * What the fiscal year is called. + */ + protected readonly fiscalYearLabel: Signal = computed(() => { + const fiscalYear: FiscalYearModel | undefined = this.eBilanzFiscalYear(); + return fiscalYear == undefined ? '' : this.resolveFiscalYearLabel(fiscalYear); + }); + + /** + * The first and the last day of the fiscal year. + */ + protected readonly period: Signal = computed(() => { + const fiscalYear: FiscalYearModel | undefined = this.eBilanzFiscalYear(); + return fiscalYear == undefined ? '' : `${this.formatDay(fiscalYear.start)} – ${this.formatDay(fiscalYear.end)}`; + }); + + /** + * The status of the E-Bilanz: filed, filed while it is being corrected, prepared, prepared before the books changed, + * or not prepared. + */ + protected readonly status: Signal = computed(() => { + const phase: EBilanzPhase | undefined = this.phase(); + if (phase !== 'filed' && this.stateValue()?.filed === true) { + return { label: this.labels.common.correcting, color: 'secondary' }; + } + switch (phase) { + case undefined: { + return undefined; + } + case 'filed': { + return { label: this.labels.common.filed, color: 'success' }; + } + case 'unprepared': { + return { label: this.labels.common.notPrepared, color: 'neutral' }; + } + case 'outdated': { + return { label: this.labels.common.outdated, color: 'error' }; + } + case 'prepared': + case 'tested': { + return { label: this.labels.common.prepared, color: 'primary' }; + } + } + }); + + /** + * The deadline of the E-Bilanz. + */ + protected readonly summary: Signal = computed(() => { + const state: EBilanzStateModel | undefined = this.stateValue(); + return state == undefined ? [] : [{ label: this.labels.common.deadline, value: this.formatDay(new Date(state.deadline)) }]; + }); + + /** + * Whether the books or the E-Bilanz are loading. + */ + protected readonly isLoading: Signal = computed(() => { + // not while the E-Bilanz loads again, which keeps what shows: the indicator makes its content inert, which would + // take the focus from the message a request moved it to + return this.fiscalYears.isLoading() || this.settings.isLoading() || this.accounts.isLoading() || this.state.status() === 'loading'; + }); + + constructor() { + super(); + // the E-Bilanz loads again while a transmission runs, also one that ran when it opened, until it has a result + effect(() => { + const fiscalYearId: string | undefined = this.eBilanzFiscalYearId(); + const running: string | undefined = this.runningTransmissionId(); + untracked(() => { + this.stopPolling(); + if (running != undefined && fiscalYearId != undefined) { + this.pollCount = 0; + this.schedulePoll(fiscalYearId); + } + }); + }); + // says the result of each transmission it saw running, once the E-Bilanz has it + effect(() => { + const state: EBilanzStateModel | undefined = this.stateValue(); + if (state != undefined) { + untracked(() => this.takeTransmissions(state.transmissions)); + } + }); + this.destroyRef.onDestroy(() => { + this.destroyed = true; + this.stopPolling(); + }); + } + + /** + * Whether the books couldn't be loaded. + */ + protected readonly loadingFailed: Signal = computed(() => { + return [this.fiscalYears, this.settings, this.accounts].some(loaded => loaded.error() != undefined); + }); + + /** + * Whether the E-Bilanz of the fiscal year couldn't be loaded. + */ + protected readonly stateFailed: Signal = computed(() => this.state.error() != undefined); + + /** + * Opens the step after the preparation and the review only once the E-Bilanz is prepared as the books state it, + * and says why otherwise. The test opens the last step without being sent, for whoever files it by hand. + * @param index - The index of the current step. + * @returns Whether the stepper goes on. + */ + protected readonly beforeNext: StepperBeforeNext = index => { + const phase: EBilanzPhase | undefined = this.phase(); + if (index > 1 || (phase != undefined && PREPARED_PHASES.has(phase))) { + return true; + } + this.stepReason.set(phase === 'outdated' ? this.labels.common.outdatedReason : this.labels.common.notPreparedReason); + return false; + }; + + /** + * Shows a tab, which ui-tabs names by its value. + * @param tab - The value of the tab. + */ + protected selectTab(tab: string | undefined): void { + const found: EBilanzTab | undefined = TABS.find(candidate => candidate === tab); + if (found != undefined) { + this.tab.set(found); + } + } + + /** + * Opens the step or the tab the element of a finding is in, and moves the focus to the element once it shows. + * @param target - The element. + */ + protected goToTarget(target: EBilanzFindingTarget): void { + switch (target.place) { + case 'figures': { + this.tab.set('filing'); + this.step.set(0); + break; + } + case 'account': { + this.tab.set('accountMappings'); + break; + } + case 'balanceSheet': + case 'incomeStatement': + case 'fixedAssets': { + this.tab.set('filing'); + this.step.set(1); + this.contentTab.set(target.place); + break; + } + } + // hidden, a tab or a step is inert, so the element takes the focus once it shows + afterNextRender(() => this.document.getElementById(target.id)?.focus(), { injector: this.injector }); + } + + /** + * Shows the records, from the button of the last step, and moves the focus to their heading. + */ + protected showRecords(): void { + this.tab.set('records'); + afterNextRender(() => this.records()?.focusHeading(), { injector: this.injector }); + } + + /** + * Says what a step was answered with, above the steps, where the focus moves: the step can change once the + * E-Bilanz loaded again, like to the next one after an accepted test. A record loads the E-Bilanz again. + * @param outcome - What the step was answered with. + */ + protected takeOutcome(outcome: EBilanzOutcome): void { + this.outcome.set(outcome); + if (outcome.recorded) { + this.reload(); + } + afterNextRender(() => this.message()?.nativeElement.focus(), { injector: this.injector }); + } + + /** + * Says that the E-Bilanz was prepared, which opens the review once it loaded again. + */ + protected takePreparation(): void { + this.takeOutcome({ kind: 'announcement', message: this.labels.preparation.preparedAnnouncement, messages: [], recorded: true }); + } + + /** + * Takes whether a certificate is uploaded after an upload, and loads the E-Bilanz again, which can be sent then. + * @param settings - Whether a certificate is uploaded. + */ + protected takeCertificate(settings: EBilanzCertificateSettingsModel): void { + this.certificateSettings.set(settings); + this.reload(); + } + + /** + * Loads the E-Bilanz again after something changed it, like a preparation, a transmission or a mapping, and drops + * the preview, which may state it otherwise now. + */ + protected reload(): void { + this.revision.update(revision => revision + 1); + this.state.reload(); + } + + private schedulePoll(fiscalYearId: string): void { + const delay: number = Math.min(POLL_DELAY_IN_MS * POLL_BACKOFF ** this.pollCount, MAX_POLL_DELAY_IN_MS); + this.pollTimer = setTimeout(() => void this.poll(fiscalYearId), delay); + } + + private stopPolling(): void { + clearTimeout(this.pollTimer); + this.pollTimer = undefined; + } + + // set, not reloaded: a reload shows the loading indicator every few seconds, and drops the preview. + private async poll(fiscalYearId: string): Promise { + this.pollTimer = undefined; + this.pollCount++; + try { + const state: EBilanzStateModel = await this.eBilanzService.resolveState(fiscalYearId); + if (this.destroyed || fiscalYearId !== this.eBilanzFiscalYearId()) { + return; + } + this.state.set(state); + } + catch (error) { + // a request that failed is tried again the next time, as it only reads. Anything else is a mistake. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + } + // the effect only starts polling for another transmission, so the same one is polled on from here + if (!this.destroyed && this.pollTimer == undefined && this.runningTransmissionId() != undefined && fiscalYearId === this.eBilanzFiscalYearId()) { + this.schedulePoll(fiscalYearId); + } + } + + private takeTransmissions(transmissions: EBilanzTransmissionModel[]): void { + for (const transmission of transmissions) { + if (transmission.status === EBilanzTransmissionStatus.TRANSMITTING) { + this.watchedTransmissionIds.add(transmission.id); + } + else if (this.watchedTransmissionIds.delete(transmission.id)) { + // a result that is not known says nothing here: its warning shows until it is settled + this.outcome.set(EBilanzViewUtilities.resolveTransmissionOutcome(transmission, this.labels)); + } + } + } + + private resolveFiscalYearLabel(fiscalYear: FiscalYearModel): string { + return BookkeepingFiscalYearUtilities.resolveLabel(fiscalYear, this.config.dateFormat, this.locale); + } + + private formatMoment(moment: string): string { + return BookkeepingDayUtilities.formatMoment(new Date(moment), this.config.dateFormat, this.locale); + } +} diff --git a/projects/ngx-bookkeeping/e-bilanz/e-bilanz.stories.ts b/projects/ngx-bookkeeping/e-bilanz/e-bilanz.stories.ts new file mode 100644 index 0000000..c132adc --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/e-bilanz.stories.ts @@ -0,0 +1,165 @@ +import { LOCALE_ID } from '@angular/core'; +import { Meta, StoryObj } from '@storybook/angular'; + +import { BookkeepingStoryUtilities } from '../fixtures/bookkeeping-story.utilities'; +import { EBilanzComponent } from './e-bilanz.component'; + +// previews the E-Bilanz not prepared yet with the balance sheet that is the tax balance sheet as well. +async function preview(canvasElement: HTMLElement): Promise { + const preparation: HTMLElement = await BookkeepingStoryUtilities.waitForElement(canvasElement, 'ngx-e-bilanz-preparation'); + (await BookkeepingStoryUtilities.waitForElement(preparation, '[role="combobox"]')).click(); + (await BookkeepingStoryUtilities.waitForElement(document, '[role="option"]')).click(); + await new Promise(resolve => setTimeout(resolve, 50)); + (await BookkeepingStoryUtilities.waitForElement(preparation, 'button', 'Preview')).click(); + await BookkeepingStoryUtilities.waitForElement(canvasElement, 'ngx-e-bilanz-findings'); +} + +// opens a tab of the E-Bilanz by its label. +async function openTab(canvasElement: HTMLElement, label: string): Promise { + (await BookkeepingStoryUtilities.waitForElement(canvasElement, '[role="tab"]', label)).click(); + await new Promise(resolve => setTimeout(resolve, 50)); +} + +const meta: Meta = { + title: 'Bookkeeping/E-Bilanz', + component: EBilanzComponent, + render: () => ({ template: '' }) +}; +export default meta; + +type Story = StoryObj; + +// prepared, but the app can't send it: the test is disabled with plain words on how to file it by hand instead, and +// the last step still downloads it and marks it as filed. +export const NoTransmitter: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'prepared', transmitter: 'missing' })], + play: async ({ canvasElement }) => { + const step: HTMLElement = await BookkeepingStoryUtilities.waitForElement(canvasElement, 'ui-stepper ui-form:not([hidden])'); + (await BookkeepingStoryUtilities.waitForElement(step, 'button', 'Next')).click(); + await BookkeepingStoryUtilities.waitForElement(canvasElement, 'ui-stepper li[aria-current="step"]', '3 Test'); + } +}; + +// prepared with a transmitter: it opens at the review, and is sent for real once a test of the same content was +// accepted. +export const BeforeTest: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'prepared', transmitter: 'configured' })] +}; + +// the test was accepted: it opens at the last step, where it is sent for real or filed by hand. +export const AfterAcceptedTest: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'tested', transmitter: 'configured' })] +}; + +// sent and accepted: every step is done, with how it was filed, and nothing is sent again. +export const Filed: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'transmitted', transmitter: 'configured' })] +}; + +// the preview of an E-Bilanz not prepared yet: the account without a position, the balance sheet that doesn't +// balance, and the figures of the statement of changes in fixed assets the books don't hold. +export const Findings: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend()], + play: async ({ canvasElement }) => { + await preview(canvasElement); + } +}; + +// the books changed since the preparation: back at preparing it, with why. +export const BooksChanged: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'tested', transmitter: 'configured', booksChanged: true })] +}; + +// a user who only reads: no buttons that prepare, file or change anything, and no tabs of the mappings and the +// certificate. +export const ReadOnly: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'tested', transmitter: 'configured' })], + render: () => ({ template: '' }) +}; + +// amounts and days in the format of the language of the app. The texts are German once the app merged the +// translations of the package. +export const German: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'tested', transmitter: 'configured' }, {}, [{ provide: LOCALE_ID, useValue: 'de' }])] +}; + +// the records of an E-Bilanz sent for real: its preparation, its test and its transmission with the protocol. +export const Records: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'transmitted', transmitter: 'configured' })], + play: async ({ canvasElement }) => { + await openTab(canvasElement, 'Records'); + } +}; + +// the account a preview says needs a position, and the form that maps it. +export const AccountMappings: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend()], + play: async ({ canvasElement }) => { + await preview(canvasElement); + await openTab(canvasElement, 'Account mappings'); + } +}; + +// no certificate is uploaded yet, which sending needs. +export const Certificate: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'prepared', transmitter: 'no-certificate' })], + play: async ({ canvasElement }) => { + await openTab(canvasElement, 'ELSTER certificate'); + } +}; + +// being sent in the background, which takes long here: it says so, and every button that sends waits. +export const Sending: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'sending', transmitter: 'configured', transmissionDurationInMs: 60 * 60 * 1000 })] +}; + +// being sent when it opened: it loads again until the result is there, after a few seconds. +export const SendingEnds: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'sending', transmitter: 'configured' })] +}; + +// the transmitter didn't answer in time, so it may have reached the tax administration: check ELSTER first, then mark +// it as filed by hand or say that ELSTER didn't receive it. Until then, it isn't sent again. +export const UnknownResult: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'unknown', transmitter: 'configured' })] +}; + +// the question before saying that ELSTER didn't receive it, and what that means. +export const ConfirmNotReceived: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'unknown', transmitter: 'configured' })], + play: async ({ canvasElement }) => { + const transmission: HTMLElement = await BookkeepingStoryUtilities.waitForElement(canvasElement, 'ngx-e-bilanz-transmission'); + (await BookkeepingStoryUtilities.waitForElement(transmission, 'button', 'ELSTER did not receive it')).click(); + await BookkeepingStoryUtilities.waitForElement(document, 'dialog[open]'); + } +}; + +// failed while it may have been sent, with what failed: the same warning as for a result that is not known. +export const FailedMayHaveBeenSent: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'sending', transmitter: 'configured', transmissionOutcome: 'failed', transmissionDurationInMs: 500 })], + play: async ({ canvasElement }) => { + await BookkeepingStoryUtilities.waitForElement(canvasElement, 'ngx-e-bilanz-transmission [role="alert"]'); + } +}; + +// failed before anything was sent, with what failed: it can be sent again. +export const FailedNotSent: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'sending', transmitter: 'configured', transmissionOutcome: 'not-sent', transmissionDurationInMs: 500 })], + play: async ({ canvasElement }) => { + await BookkeepingStoryUtilities.waitForElement(canvasElement, 'div[tabindex="-1"] > [role="alert"]'); + } +}; + +// filed, and the books changed since, like after reopening the fiscal year: it is prepared again as a correction, +// which says what it corrects. +export const Correction: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'transmitted', transmitter: 'configured', booksChanged: true })] +}; + +// the records of a correction, which name the filing they correct. +export const CorrectionRecords: Story = { + decorators: [BookkeepingStoryUtilities.provideEBilanzBackend({ stage: 'correcting', transmitter: 'configured' })], + play: async ({ canvasElement }) => { + await openTab(canvasElement, 'Records'); + } +}; diff --git a/projects/ngx-bookkeeping/e-bilanz/ng-package.json b/projects/ngx-bookkeeping/e-bilanz/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-bookkeeping/e-bilanz/public-api.ts b/projects/ngx-bookkeeping/e-bilanz/public-api.ts new file mode 100644 index 0000000..f706fda --- /dev/null +++ b/projects/ngx-bookkeeping/e-bilanz/public-api.ts @@ -0,0 +1 @@ +export * from './e-bilanz.component'; diff --git a/projects/ngx-bookkeeping/fiscal-years/closing-proposal-line-view.model.ts b/projects/ngx-bookkeeping/fiscal-years/closing-proposal-line-view.model.ts new file mode 100644 index 0000000..a4f308e --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/closing-proposal-line-view.model.ts @@ -0,0 +1,17 @@ +/** + * A line of an entry proposed before closing, as it shows. + */ +export type ClosingProposalLineView = { + /** + * The account booked on, its number and name. + */ + account: string, + /** + * The amount on the debit side formatted, or an empty string. + */ + debit: string, + /** + * The amount on the credit side formatted, or an empty string. + */ + credit: string +}; diff --git a/projects/ngx-bookkeeping/fiscal-years/closing-proposal-view.model.ts b/projects/ngx-bookkeeping/fiscal-years/closing-proposal-view.model.ts new file mode 100644 index 0000000..4827637 --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/closing-proposal-view.model.ts @@ -0,0 +1,37 @@ +import { BookkeepingClosingProposalModel } from 'zibri-contract'; + +import { ClosingProposalLineView } from './closing-proposal-line-view.model'; + +/** + * An entry proposed before closing, as it shows. + */ +export type ClosingProposalView = { + /** + * The proposal, to post its entry. + */ + proposal: BookkeepingClosingProposalModel, + /** + * What the entry books. + */ + text: string, + /** + * Who proposes it. + */ + proposedBy: string, + /** + * The day it is booked on, formatted. + */ + postingDate: string, + /** + * What screen readers call the button that posts it. + */ + postLabel: string, + /** + * What screen readers call the table of its lines. + */ + linesLabel: string, + /** + * Its lines. + */ + lines: ClosingProposalLineView[] +}; diff --git a/projects/ngx-bookkeeping/fiscal-years/closing-proposal.component.html b/projects/ngx-bookkeeping/fiscal-years/closing-proposal.component.html new file mode 100644 index 0000000..25e5682 --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/closing-proposal.component.html @@ -0,0 +1,35 @@ +
+ {{ proposal().text }} + {{ proposal().proposedBy }} · {{ proposal().postingDate }} + +
+
+ + + + + + + + + + @for (line of proposal().lines; track $index) { + + + + + + } + +
{{ commonLabels.account }}{{ commonLabels.debit }}{{ commonLabels.credit }}
{{ line.account }}{{ line.debit }}{{ line.credit }}
+
diff --git a/projects/ngx-bookkeeping/fiscal-years/closing-proposal.component.ts b/projects/ngx-bookkeeping/fiscal-years/closing-proposal.component.ts new file mode 100644 index 0000000..2f10a77 --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/closing-proposal.component.ts @@ -0,0 +1,44 @@ +import { Component, inject, input, InputSignal, output, OutputEmitterRef } from '@angular/core'; +import { BOOKKEEPING_CONFIG, BookkeepingCommonLabels, BookkeepingConfig, BookkeepingFiscalYearsLabels } from '@service-soft/ngx-bookkeeping/api'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { ScrollRegionDirective } from '@service-soft/ui/scroll-region'; + +import { ClosingProposalView } from './closing-proposal-view.model'; + +/** + * An entry proposed before closing, with its lines and the button that posts it. Only used by the closing. + */ +@Component({ + selector: 'ngx-closing-proposal', + templateUrl: './closing-proposal.component.html', + imports: [ButtonComponent, ScrollRegionDirective], + host: { class: 'grid gap-2 rounded-table border border-outline-variant px-4 py-3' } +}) +export class ClosingProposalComponent { + private readonly config: BookkeepingConfig = inject(BOOKKEEPING_CONFIG); + + /** + * The proposal. + */ + readonly proposal: InputSignal = input.required(); + + /** + * Whether a posting or the closing is being sent, which the button waits for. + */ + readonly disabled: InputSignal = input.required(); + + /** + * Emits when the user wants to post the proposal. + */ + readonly posting: OutputEmitterRef = output(); + + /** + * The texts of the fiscal years. + */ + protected readonly labels: BookkeepingFiscalYearsLabels = this.config.labels.fiscalYears; + + /** + * The texts several views show. + */ + protected readonly commonLabels: BookkeepingCommonLabels = this.config.labels.common; +} diff --git a/projects/ngx-bookkeeping/fiscal-years/fiscal-year-closing.component.html b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-closing.component.html new file mode 100644 index 0000000..4fe69d8 --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-closing.component.html @@ -0,0 +1,39 @@ +{{ labels.closing }} + +

{{ announcement() }}

+@if (isOpen()) { +

{{ labels.proposalsText }}

+
+ @if (proposalsNote(); as note) { +

{{ note }}

+ } + @for (view of proposalViews(); track $index) { + + } +
+ + + @if (error(); as message) { +
+ +

{{ message }}

+
+ } +
+ +
+
+} @else { +

{{ closedNote() }}

+ @if (canReopen()) { +
+ +
+ } +} diff --git a/projects/ngx-bookkeeping/fiscal-years/fiscal-year-closing.component.ts b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-closing.component.ts new file mode 100644 index 0000000..a7cefeb --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-closing.component.ts @@ -0,0 +1,324 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { afterNextRender, Component, computed, ElementRef, inject, Injector, input, InputSignal, linkedSignal, LOCALE_ID, output, OutputEmitterRef, resource, ResourceRef, Signal, signal, viewChild, WritableSignal } from '@angular/core'; +import { BOOKKEEPING_CONFIG, BookkeepingAmountUtilities, BookkeepingCommonLabels, BookkeepingConfig, BookkeepingDayUtilities, BookkeepingFiscalYearsLabels, BookkeepingFiscalYearUtilities, BookkeepingService } from '@service-soft/ngx-bookkeeping/api'; +import { ErrorResponseUtilities } from '@service-soft/ngx-error-handling/error-response'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { ConfirmDialogComponent, ConfirmDialogData, DialogService } from '@service-soft/ui/dialog'; +import { FormComponent } from '@service-soft/ui/form'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { InputOption } from '@service-soft/ui/input'; +import { InputSelectComponent } from '@service-soft/ui/input-select'; +import { LoadingDirective } from '@service-soft/ui/loading'; +import { + BookkeepingAccountModel, + BookkeepingAccountType, + BookkeepingClosingProposalModel, + FiscalYearClosingResultModel, + FiscalYearModel, + FiscalYearReopeningResultModel, + JournalEntryDetailsModel, + NewJournalEntryLineModel +} from 'zibri-contract'; + +import { ClosingProposalLineView } from './closing-proposal-line-view.model'; +import { ClosingProposalView } from './closing-proposal-view.model'; +import { ClosingProposalComponent } from './closing-proposal.component'; +import { FiscalYearReopeningDialogData } from './fiscal-year-reopening-dialog-data.model'; +import { FiscalYearReopeningDialogComponent } from './fiscal-year-reopening-dialog.component'; + +// what the view says about the proposals: that they couldn't be loaded, or that there are none. +const NOTE_CLASSES: Record<'failed' | 'none', string> = { failed: 'text-body text-error', none: 'text-body text-on-surface-variant' }; + +/** + * What the proposals of a fiscal year are loaded for: the fiscal year, and the last posting of the app, after which + * they load again, as a posted proposal is proposed no more. + */ +type ProposalsParams = { + /** + * The id of the fiscal year. + */ + fiscalYearId: string, + /** + * The last entry the app posted, undefined before the first. + */ + lastPosting: JournalEntryDetailsModel | undefined +}; + +/** + * Closes a fiscal year: shows the entries its conformances propose before, which the user posts after confirming each, + * and closes it into the equity account the user chooses for its result, after confirming that as well. A refusal of + * the api, like while a proposal isn't posted, shows its message. With `canReopen`, a closed fiscal year is reopened + * in a dialog. Only used by the fiscal years. + */ +@Component({ + selector: 'ngx-fiscal-year-closing', + templateUrl: './fiscal-year-closing.component.html', + imports: [ + ButtonComponent, + CalloutComponent, + ClosingProposalComponent, + FormComponent, + HeadingComponent, + InputSelectComponent, + LoadingDirective + ], + host: { class: 'grid gap-3' } +}) +export class FiscalYearClosingComponent { + private readonly config: BookkeepingConfig = inject(BOOKKEEPING_CONFIG); + + private readonly bookkeepingService: BookkeepingService = inject(BookkeepingService); + + private readonly dialogService: DialogService = inject(DialogService); + + private readonly locale: string = inject(LOCALE_ID); + + private readonly injector: Injector = inject(Injector); + + private readonly message: Signal | undefined> = viewChild>('message'); + + /** + * The fiscal year to close. + */ + readonly fiscalYear: InputSignal = input.required(); + + /** + * The accounts of the books, which the proposals book on and the result is carried into. + */ + readonly accounts: InputSignal = input.required(); + + /** + * How amounts are written, in the currency of the books. + */ + readonly format: InputSignal = input.required(); + + /** + * The level of its heading. + */ + readonly headingLevel: InputSignal = input.required(); + + /** + * Whether the user may reopen the fiscal year once it is closed. + */ + readonly canReopen: InputSignal = input.required(); + + /** + * Emits what closing the fiscal year posted, with it and the next. + */ + readonly closed: OutputEmitterRef = output(); + + /** + * Emits what reopening the fiscal year posted, with it and the next. + */ + readonly reopened: OutputEmitterRef = output(); + + /** + * The texts of the fiscal years. + */ + protected readonly labels: BookkeepingFiscalYearsLabels = this.config.labels.fiscalYears; + + /** + * The texts several views show. + */ + protected readonly commonLabels: BookkeepingCommonLabels = this.config.labels.common; + + // what starts over with another fiscal year: the year changes when it is saved or closed, its id doesn't. + private readonly fiscalYearId: Signal = computed(() => this.fiscalYear().id); + + /** + * Whether the fiscal year is open, and can be closed. + */ + protected readonly isOpen: Signal = computed(() => this.fiscalYear().closedAt == undefined); + + /** + * What the view says about a closed fiscal year. + */ + protected readonly closedNote: Signal = computed(() => { + const closedAt: Date | null | undefined = this.fiscalYear().closedAt; + if (closedAt == undefined) { + return ''; + } + return this.labels.closedNote(BookkeepingDayUtilities.format(closedAt, this.config.dateFormat, this.locale)); + }); + + private readonly proposals: ResourceRef = resource({ + params: (): ProposalsParams | undefined => this.isOpen() + ? { fiscalYearId: this.fiscalYear().id, lastPosting: this.bookkeepingService.lastPosting() } + : undefined, + loader: async ({ params }) => await this.bookkeepingService.resolveClosingProposals(params.fiscalYearId) + }); + + /** + * Whether the proposals are loading. + */ + protected readonly isLoading: Signal = computed(() => this.proposals.isLoading()); + + /** + * Whether the proposals couldn't be loaded, like without the permission to close a fiscal year. + */ + protected readonly proposalsFailed: Signal = computed(() => this.proposals.error() != undefined); + + private readonly accountNames: Signal> = computed(() => { + return new Map(this.accounts().map(account => [account.id, `${account.number} ${account.name}`])); + }); + + /** + * The proposals as they show. + */ + protected readonly proposalViews: Signal = computed(() => { + const proposals: BookkeepingClosingProposalModel[] = this.proposals.hasValue() ? this.proposals.value() ?? [] : []; + return proposals.map(proposal => this.toView(proposal)); + }); + + /** + * What the view says about the proposals: that they couldn't be loaded, or that there are none once they are. + * Undefined while there are some, or they load. + */ + protected readonly proposalsNote: Signal = computed(() => { + if (this.proposalsFailed()) { + return this.labels.proposalsFailed; + } + return this.proposals.hasValue() && !this.proposalViews().length ? this.labels.noProposals : undefined; + }); + + /** + * The classes of that note. + */ + protected readonly proposalsNoteClasses: Signal = computed(() => NOTE_CLASSES[this.proposalsFailed() ? 'failed' : 'none']); + + /** + * The open equity accounts the result can be carried into. + */ + protected readonly resultAccountOptions: Signal[]> = computed(() => this.accounts() + .filter(account => account.type === BookkeepingAccountType.EQUITY && account.closedAt == undefined) + .map(account => ({ label: `${account.number} ${account.name}`, value: account.id }))); + + /** + * The id of the account the result is carried into. It starts over with another fiscal year. + */ + protected readonly resultAccountId: WritableSignal = linkedSignal({ + source: this.fiscalYearId, + computation: () => undefined + }); + + /** + * Whether a proposal is being posted or the fiscal year closed. + */ + protected readonly sending: WritableSignal = signal(false); + + /** + * What the view last said about a posting or the closing, or an empty string. It starts over with another fiscal + * year. + */ + protected readonly announcement: WritableSignal = linkedSignal({ source: this.fiscalYearId, computation: () => '' }); + + /** + * Why the api refused a posting or the closing, or undefined while it refused none. It starts over with another + * fiscal year. + */ + protected readonly error: WritableSignal = linkedSignal({ + source: this.fiscalYearId, + computation: () => undefined + }); + + /** + * Posts a proposed entry, after the user confirmed it. + * @param view - The proposal. + */ + protected async post(view: ClosingProposalView): Promise { + await this.send(this.config.postProposalConfirmDialogData, async () => { + const posted: JournalEntryDetailsModel = await this.bookkeepingService.postEntry(view.proposal.entry); + // the proposals load again with the lastPosting of the service, without the one posted. + this.announcement.set(this.labels.proposalPosted(posted.entry.sequence)); + }); + } + + /** + * Closes the fiscal year into the result account, after the user confirmed it, which the form only submits with + * one. + */ + protected async close(): Promise { + const resultAccountId: string | undefined = this.resultAccountId(); + if (resultAccountId == undefined) { + return; + } + await this.send(this.config.closeConfirmDialogData, async () => { + const result: FiscalYearClosingResultModel = await this.bookkeepingService.closeFiscalYear( + this.fiscalYear().id, + { resultAccountId } + ); + this.announcement.set(this.labels.closedResult(this.resolveLabel(result.fiscalYear), this.resolveLabel(result.nextFiscalYear))); + this.closed.emit(result); + // the form that had the focus is gone with the open fiscal year, and the message says what happened. + afterNextRender(() => this.message()?.nativeElement.focus(), { injector: this.injector }); + }); + } + + /** + * Opens the dialog that reopens the fiscal year, which asks why, and says once it did. + */ + protected async reopen(): Promise { + const data: FiscalYearReopeningDialogData = { fiscalYear: this.fiscalYear(), fiscalYearLabel: this.resolveLabel(this.fiscalYear()) }; + const result: FiscalYearReopeningResultModel | undefined = await this.dialogService + .open(FiscalYearReopeningDialogComponent, data) + .closed; + if (result == undefined) { + return; + } + this.error.set(undefined); + this.announcement.set(this.labels.reopened(this.resolveLabel(result.fiscalYear))); + this.reopened.emit(result); + // the button that had the focus is gone with the closed fiscal year, and the message says what happened. + afterNextRender(() => this.message()?.nativeElement.focus(), { injector: this.injector }); + } + + private async send(question: ConfirmDialogData, request: () => Promise): Promise { + const confirmed: boolean | undefined = await this.dialogService.open(ConfirmDialogComponent, question).closed; + if (confirmed !== true) { + return; + } + this.sending.set(true); + this.announcement.set(''); + this.error.set(undefined); + try { + await request(); + } + catch (error) { + // a refusal of the api is the answer, like a proposal not posted yet. Anything else is a mistake, which goes + // on to the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.error.set(ErrorResponseUtilities.findMessage(error) ?? this.commonLabels.requestFailed); + } + finally { + this.sending.set(false); + } + } + + private toView(proposal: BookkeepingClosingProposalModel): ClosingProposalView { + const conformance: string = this.config.conformances[proposal.conformance] ?? proposal.conformance; + return { + proposal, + text: proposal.entry.text, + proposedBy: this.labels.proposedBy(conformance), + postingDate: BookkeepingDayUtilities.format(proposal.entry.postingDate, this.config.dateFormat, this.locale), + postLabel: this.labels.postProposalOf(proposal.entry.text), + linesLabel: this.labels.proposalLines(proposal.entry.text), + lines: proposal.entry.lines.map(line => this.toLineView(line)) + }; + } + + private toLineView(line: NewJournalEntryLineModel): ClosingProposalLineView { + return { + account: this.accountNames().get(line.accountId) ?? line.accountId, + debit: line.debit == undefined ? '' : BookkeepingAmountUtilities.format(line.debit, this.format()), + credit: line.credit == undefined ? '' : BookkeepingAmountUtilities.format(line.credit, this.format()) + }; + } + + private resolveLabel(fiscalYear: FiscalYearModel): string { + return BookkeepingFiscalYearUtilities.resolveLabel(fiscalYear, this.config.dateFormat, this.locale); + } +} diff --git a/projects/ngx-bookkeeping/fiscal-years/fiscal-year-details.component.html b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-details.component.html new file mode 100644 index 0000000..b67cd6e --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-details.component.html @@ -0,0 +1,37 @@ +{{ labels.details }} +@if (isOpen()) { + + + + @if (isFirst()) { + + } + @if (error(); as message) { +
+ +

{{ message }}

+
+ } +
+ + +

{{ savedLabel() }}

+
+
+} @else if (items().length) { + +} diff --git a/projects/ngx-bookkeeping/fiscal-years/fiscal-year-details.component.ts b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-details.component.ts new file mode 100644 index 0000000..1855217 --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-details.component.ts @@ -0,0 +1,182 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { Component, computed, inject, input, InputSignal, linkedSignal, output, OutputEmitterRef, Signal, signal, WritableSignal } from '@angular/core'; +import { BOOKKEEPING_CONFIG, BookkeepingCommonLabels, BookkeepingConfig, BookkeepingFiscalYearsLabels, BookkeepingService } from '@service-soft/ngx-bookkeeping/api'; +import { ErrorResponseUtilities } from '@service-soft/ngx-error-handling/error-response'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { DataListComponent, DataListItem } from '@service-soft/ui/data-list'; +import { FormComponent } from '@service-soft/ui/form'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { InputOption } from '@service-soft/ui/input'; +import { InputNumberComponent } from '@service-soft/ui/input-number'; +import { InputSelectComponent } from '@service-soft/ui/input-select'; +import { InputTextareaComponent } from '@service-soft/ui/input-textarea'; +import { FiscalYearChangeModel, FiscalYearModel } from 'zibri-contract'; + +// the option of a company founded in the fiscal year, beside the size classes it can have had before. +const FOUNDED: string = 'founded'; + +/** + * What a fiscal year holds for its statements beside the books: the average number of employees, the note below the + * balance sheet and, for the first fiscal year of the books, what the company was before it. Changed while the fiscal + * year is open, and shown as it was closed with afterwards. Only used by the fiscal years. + */ +@Component({ + selector: 'ngx-fiscal-year-details', + templateUrl: './fiscal-year-details.component.html', + imports: [ + ButtonComponent, + CalloutComponent, + DataListComponent, + FormComponent, + HeadingComponent, + InputNumberComponent, + InputSelectComponent, + InputTextareaComponent + ], + host: { class: 'grid gap-3' } +}) +export class FiscalYearDetailsComponent { + private readonly config: BookkeepingConfig = inject(BOOKKEEPING_CONFIG); + + private readonly bookkeepingService: BookkeepingService = inject(BookkeepingService); + + /** + * The fiscal year. + */ + readonly fiscalYear: InputSignal = input.required(); + + /** + * Whether it is the first fiscal year of the books, which says what the company was before it. + */ + readonly isFirst: InputSignal = input.required(); + + /** + * The level of its heading. + */ + readonly headingLevel: InputSignal = input.required(); + + /** + * Emits the fiscal year once its changes are saved. + */ + readonly saved: OutputEmitterRef = output(); + + /** + * The texts of the fiscal years. + */ + protected readonly labels: BookkeepingFiscalYearsLabels = this.config.labels.fiscalYears; + + /** + * The texts several views show. + */ + protected readonly commonLabels: BookkeepingCommonLabels = this.config.labels.common; + + /** + * What the company can have been before the first fiscal year of the books. + */ + protected readonly beforeOptions: InputOption[] = [ + { label: this.labels.founded, value: FOUNDED }, + ...Object.entries(this.config.sizeClasses).map(([value, label]) => ({ label, value })) + ]; + + // what starts over with another fiscal year: the year changes when it is saved, its id doesn't. + private readonly fiscalYearId: Signal = computed(() => this.fiscalYear().id); + + /** + * Whether the fiscal year is open, and can be changed. + */ + protected readonly isOpen: Signal = computed(() => this.fiscalYear().closedAt == undefined); + + /** + * The average number of employees, as the fiscal year holds it. + */ + protected readonly averageEmployees: WritableSignal = linkedSignal(() => { + return this.fiscalYear().averageEmployees ?? undefined; + }); + + /** + * The note below the balance sheet, as the fiscal year holds it. + */ + protected readonly balanceSheetNote: WritableSignal = linkedSignal(() => this.fiscalYear().balanceSheetNote ?? ''); + + /** + * What the company was before the first fiscal year of the books, as the fiscal year holds it. + */ + protected readonly before: WritableSignal = linkedSignal(() => this.getBefore(this.fiscalYear())); + + /** + * Whether the changes are being sent. + */ + protected readonly saving: WritableSignal = signal(false); + + /** + * What the view says once the changes are saved, or an empty string. It starts over with another fiscal year. + */ + protected readonly savedLabel: WritableSignal = linkedSignal({ source: this.fiscalYearId, computation: () => '' }); + + /** + * Why the api refused the changes, or undefined while it refused none. It starts over with another fiscal year. + */ + protected readonly error: WritableSignal = linkedSignal({ + source: this.fiscalYearId, + computation: () => undefined + }); + + /** + * What a closed fiscal year holds, as it was closed with. + */ + protected readonly items: Signal = computed(() => { + const fiscalYear: FiscalYearModel = this.fiscalYear(); + const before: string | undefined = this.getBefore(fiscalYear); + return [ + { label: this.labels.averageEmployees, value: fiscalYear.averageEmployees ?? undefined }, + { label: this.labels.balanceSheetNote, value: fiscalYear.balanceSheetNote ?? undefined }, + { label: this.labels.before, value: this.beforeOptions.find(option => option.value === before)?.label ?? before } + ].filter(item => item.value != undefined); + }); + + /** + * Saves the changes. + */ + protected async save(): Promise { + this.saving.set(true); + this.savedLabel.set(''); + this.error.set(undefined); + try { + const saved: FiscalYearModel = await this.bookkeepingService.updateFiscalYear(this.fiscalYear().id, this.resolveChange()); + this.savedLabel.set(this.labels.saved); + this.saved.emit(saved); + } + catch (error) { + // a refusal of the api is the answer to the changes, anything else a mistake for the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.error.set(ErrorResponseUtilities.findMessage(error) ?? this.commonLabels.requestFailed); + } + finally { + this.saving.set(false); + } + } + + /* eslint-disable unicorn/no-null -- the api takes null for a value the fiscal year no longer has */ + private resolveChange(): FiscalYearChangeModel { + const note: string = this.balanceSheetNote().trim(); + const change: FiscalYearChangeModel = { averageEmployees: this.averageEmployees() ?? null, balanceSheetNote: note || null }; + if (!this.isFirst()) { + return change; + } + const before: string | undefined = this.before(); + if (before == undefined) { + return { ...change, founded: null, previousSizeClass: null }; + } + return before === FOUNDED + ? { ...change, founded: true, previousSizeClass: null } + : { ...change, founded: false, previousSizeClass: before }; + } + /* eslint-enable unicorn/no-null */ + + private getBefore(fiscalYear: FiscalYearModel): string | undefined { + return fiscalYear.founded === true ? FOUNDED : fiscalYear.previousSizeClass ?? undefined; + } +} diff --git a/projects/ngx-bookkeeping/fiscal-years/fiscal-year-export.component.html b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-export.component.html new file mode 100644 index 0000000..58bec3e --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-export.component.html @@ -0,0 +1,14 @@ +{{ labels.export }} +

{{ labels.exportText }}

+@if (isOpen()) { +

{{ labels.exportOpenHint }}

+} + +@if (downloadFailed()) { + +} +
+ +
diff --git a/projects/ngx-bookkeeping/fiscal-years/fiscal-year-export.component.ts b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-export.component.ts new file mode 100644 index 0000000..e3a8440 --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-export.component.ts @@ -0,0 +1,84 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { Component, computed, inject, input, InputSignal, Signal, signal, WritableSignal } from '@angular/core'; +import { BOOKKEEPING_CONFIG, BookkeepingCommonLabels, BookkeepingConfig, BookkeepingFileUtilities, BookkeepingFiscalYearsLabels, BookkeepingService } from '@service-soft/ngx-bookkeeping/api'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { InputBooleanComponent } from '@service-soft/ui/input-boolean'; +import { FiscalYearModel } from 'zibri-contract'; + +/** + * Downloads the export of a fiscal year for a tax audit, with its documents or without. Only used by the fiscal years. + */ +@Component({ + selector: 'ngx-fiscal-year-export', + templateUrl: './fiscal-year-export.component.html', + imports: [ButtonComponent, HeadingComponent, InputBooleanComponent], + host: { class: 'grid gap-3' } +}) +export class FiscalYearExportComponent { + private readonly config: BookkeepingConfig = inject(BOOKKEEPING_CONFIG); + + private readonly bookkeepingService: BookkeepingService = inject(BookkeepingService); + + /** + * The fiscal year to export. + */ + readonly fiscalYear: InputSignal = input.required(); + + /** + * The level of its heading. + */ + readonly headingLevel: InputSignal = input.required(); + + /** + * The texts of the fiscal years. + */ + protected readonly labels: BookkeepingFiscalYearsLabels = this.config.labels.fiscalYears; + + /** + * The texts several views show. + */ + protected readonly commonLabels: BookkeepingCommonLabels = this.config.labels.common; + + /** + * Whether the export holds the documents behind the entries. + */ + protected readonly withDocuments: WritableSignal = signal(true); + + /** + * Whether the export is downloading, which can take a while for the documents of a year. + */ + protected readonly exporting: WritableSignal = signal(false); + + /** + * Whether the export couldn't be downloaded. + */ + protected readonly downloadFailed: WritableSignal = signal(false); + + /** + * Whether the fiscal year is open, whose export can still change. + */ + protected readonly isOpen: Signal = computed(() => this.fiscalYear().closedAt == undefined); + + /** + * Downloads the export and saves it. + */ + protected async downloadExport(): Promise { + this.exporting.set(true); + this.downloadFailed.set(false); + try { + const documents: boolean = this.withDocuments(); + BookkeepingFileUtilities.save(await this.bookkeepingService.resolveExport(this.fiscalYear().id, { documents })); + } + catch (error) { + // a failed request is the answer to the download, anything else a mistake for the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.downloadFailed.set(true); + } + finally { + this.exporting.set(false); + } + } +} diff --git a/projects/ngx-bookkeeping/fiscal-years/fiscal-year-reopening-dialog-data.model.ts b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-reopening-dialog-data.model.ts new file mode 100644 index 0000000..cd1972b --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-reopening-dialog-data.model.ts @@ -0,0 +1,15 @@ +import { FiscalYearModel } from 'zibri-contract'; + +/** + * The fiscal year the dialog reopens. + */ +export type FiscalYearReopeningDialogData = { + /** + * The fiscal year, which is closed. + */ + fiscalYear: FiscalYearModel, + /** + * What it is called, like '2025'. + */ + fiscalYearLabel: string +}; diff --git a/projects/ngx-bookkeeping/fiscal-years/fiscal-year-reopening-dialog.component.html b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-reopening-dialog.component.html new file mode 100644 index 0000000..f98faf7 --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-reopening-dialog.component.html @@ -0,0 +1,34 @@ + +

{{ labels.reopenTitle(data.fiscalYearLabel) }}

+

{{ labels.reopenText }}

+

{{ labels.reopenKeptText }}

+ + @if (filed() !== false) { +
+ @if (filed() === true) { +

{{ labels.reopenFiledNote }}

+ + } @else if (!loadingFiled()) { + + } +
+ } + + @if (error(); as message) { +
+ +

{{ message }}

+
+ } + +
+ + +
+
diff --git a/projects/ngx-bookkeeping/fiscal-years/fiscal-year-reopening-dialog.component.spec.ts b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-reopening-dialog.component.spec.ts new file mode 100644 index 0000000..e9329ea --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-reopening-dialog.component.spec.ts @@ -0,0 +1,205 @@ +import { Component } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { EBilanzService, provideBookkeepingConfig, provideFiscalYearFilingResolver } from '@service-soft/ngx-bookkeeping/api'; +import { DialogTestingUtilities } from 'testing/dialog'; +import { FormTestingUtilities } from 'testing/form'; +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; + +import { BookkeepingTestingUtilities } from '../fixtures/bookkeeping-testing.utilities'; +import { BOOKKEEPING_BASE_URL, FISCAL_YEAR_IDS } from '../fixtures/bookkeeping.fixtures'; +import { FakeEBilanzBackendOptions } from '../fixtures/fake-e-bilanz-backend-options.model'; +import { FakeEBilanzBackend } from '../fixtures/fake-e-bilanz-backend.model'; +import { FiscalYearsComponent } from './fiscal-years.component'; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [FiscalYearsComponent] +}) +class HostComponent {} + +const REOPENING_URL: string = `${BOOKKEEPING_BASE_URL}/fiscal-years/${FISCAL_YEAR_IDS.year2025}/reopening`; +const REASON: string = 'Depreciation of the office equipment missing'; + +let backend: FakeEBilanzBackend; + +/** + * Renders the fiscal years against the fake backend of the E-Bilanz, which knows whether its E-Bilanz is filed, and + * opens the fiscal year 2025, which is closed. + * @param options - How the backend answers. + * @param withResolver - Whether the dialog asks the E-Bilanz whether it is filed. + * @param canReopen - Whether the user may reopen it. + * @returns The fixture and its element. + */ +async function render(options: FakeEBilanzBackendOptions = {}, withResolver: boolean = true, canReopen: boolean = true): Promise<[ComponentFixture, HTMLElement]> { + backend = new FakeEBilanzBackend(options); + TestBed.configureTestingModule({ + providers: [ + ...BookkeepingTestingUtilities.getEBilanzProviders(backend), + provideBookkeepingConfig({ baseUrl: BOOKKEEPING_BASE_URL, canReopen }), + ...withResolver ? [provideFiscalYearFilingResolver(EBilanzService)] : [] + ] + }); + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + document.body.append(fixture.nativeElement as HTMLElement); + await BookkeepingTestingUtilities.renderAnswered(fixture); + const root: HTMLElement = fixture.nativeElement as HTMLElement; + FormTestingUtilities.click(root.querySelector('ui-local-table') ?? root, '2025'); + await BookkeepingTestingUtilities.renderAnswered(fixture); + return [fixture, root]; +} + +async function openDialog(fixture: ComponentFixture, root: HTMLElement): Promise { + FormTestingUtilities.click(getClosing(root), 'Reopen fiscal year'); + const dialog: HTMLDialogElement = await vi.waitFor(() => { + TestBed.tick(); + const opened: HTMLDialogElement | undefined = [...document.querySelectorAll('dialog[open]')].at(-1); + if (opened == undefined) { + throw new Error('No dialog is open.'); + } + return opened; + }); + await BookkeepingTestingUtilities.renderAnswered(fixture); + return dialog; +} + +function findReason(dialog: HTMLDialogElement): HTMLTextAreaElement | null { + return dialog.querySelector('textarea[name="reason"]'); +} + +function getClosing(root: HTMLElement): HTMLElement { + const closing: HTMLElement | null = root.querySelector('ngx-fiscal-year-closing'); + if (closing == undefined) { + throw new Error('There is no closing.'); + } + return closing; +} + +async function submit(fixture: ComponentFixture, dialog: HTMLDialogElement): Promise { + FormTestingUtilities.click(dialog, 'Reopen fiscal year'); + await BookkeepingTestingUtilities.renderAnswered(fixture); +} + +function findReopenings(): unknown[] { + return backend.requests.filter(request => request.method === 'POST' && request.url === REOPENING_URL).map(request => request.body); +} + +describe('FiscalYearReopeningDialogComponent', () => { + let removeModalDialogs: () => void; + + beforeEach(() => { + removeModalDialogs = DialogTestingUtilities.addModalDialogs(); + }); + + afterEach(() => { + removeModalDialogs(); + for (const element of document.querySelectorAll('ui-dialog, ngx-host')) { + element.remove(); + } + }); + + test('offers to reopen a closed fiscal year only to a user who may', async () => { + const [, root] = await render({}, true, false); + + expect(BookkeepingTestingUtilities.getText(getClosing(root))).toContain('The fiscal year was closed on 02/15/2026.'); + expect(getClosing(root).querySelector('button')).toBeNull(); + }); + + test('says what reopening does, requires the reason, and reopens the fiscal year with it', async () => { + const [fixture, root] = await render({ stage: 'prepared' }); + const dialog: HTMLDialogElement = await openDialog(fixture, root); + + const text: string = BookkeepingTestingUtilities.getText(dialog); + expect(text).toContain('Reopen the fiscal year 2025?'); + expect(text).toContain('Reopening reverses its closing: the fiscal year is open again, you can post corrections into it, and then close it again.'); + expect(text).toContain('the statements archived at the closing stay archived.'); + // its E-Bilanz isn't filed, so it isn't reopened to correct it + expect(dialog.querySelector('input[type="checkbox"]')).toBeNull(); + expect(findReason(dialog)?.getAttribute('maxlength')).toBe('500'); + + await submit(fixture, dialog); + expect(findReopenings()).toEqual([]); + expect(BookkeepingTestingUtilities.getText(dialog)).toContain('This field is required.'); + + await BookkeepingTestingUtilities.type(fixture, findReason(dialog), REASON); + await submit(fixture, dialog); + + expect(findReopenings()).toEqual([{ reason: REASON, forCorrection: false }]); + expect(document.querySelector('dialog[open]')).toBeNull(); + const message: HTMLElement | null = getClosing(root).querySelector('p[role="status"]'); + expect(message?.textContent.trim()).toBe('The fiscal year 2025 was reopened. Post the corrections, then close it again.'); + expect(document.activeElement).toBe(message); + expect(BookkeepingTestingUtilities.getText(root.querySelector('ui-local-table'))).toContain('Fiscal year 2025 Start 01/01/2025 End 12/31/2025 Status Open'); + expect(backend.getFiscalYears()[0]?.reopenings).toBe(1); + }); + + test('reopens a fiscal year whose E-Bilanz is filed only once the user confirms that it is to correct it', async () => { + const [fixture, root] = await render({ stage: 'transmitted', transmitter: 'configured' }); + const dialog: HTMLDialogElement = await openDialog(fixture, root); + + expect(BookkeepingTestingUtilities.getText(dialog)).toContain('The E-Bilanz of this fiscal year is filed with the tax administration. The year may ' + + 'only be reopened to correct it'); + const checkbox: HTMLInputElement | null = dialog.querySelector('input[type="checkbox"]'); + expect(checkbox?.required).toBe(true); + expect(BookkeepingTestingUtilities.getText(checkbox?.closest('ui-input-boolean'))).toContain('This reopening is to correct the filed E-Bilanz'); + await BookkeepingTestingUtilities.type(fixture, findReason(dialog), REASON); + await submit(fixture, dialog); + expect(findReopenings()).toEqual([]); + + checkbox?.click(); + await BookkeepingTestingUtilities.renderAnswered(fixture); + await submit(fixture, dialog); + + expect(findReopenings()).toEqual([{ reason: REASON, forCorrection: true }]); + expect(document.querySelector('dialog[open]')).toBeNull(); + }); + + test('lets the user say whether it corrects filed accounts while the app can\'t tell, and shows the refusal of the api in plain text', async () => { + const [fixture, root] = await render({ stage: 'transmitted', transmitter: 'configured' }, false); + const dialog: HTMLDialogElement = await openDialog(fixture, root); + const checkbox: HTMLInputElement | null = dialog.querySelector('input[type="checkbox"]'); + expect(checkbox?.required).toBe(false); + expect(BookkeepingTestingUtilities.getText(checkbox?.closest('ui-input-boolean'))) + .toContain('The accounts of this year are filed already, like an E-Bilanz, and this reopening is to correct them'); + + await BookkeepingTestingUtilities.type(fixture, findReason(dialog), REASON); + await submit(fixture, dialog); + + expect(findReopenings()).toEqual([{ reason: REASON, forCorrection: false }]); + expect(BookkeepingTestingUtilities.getText(dialog.querySelector('[role="alert"]'))) + .toBe('Error The E-Bilanz of the fiscal year is filed, and the fiscal year is reopened only to correct it, with forCorrection.'); + expect(dialog.open).toBe(true); + }); + + test.each<[string, FakeEBilanzBackendOptions, string]>([ + [ + 'a later fiscal year is closed', + { laterYearClosed: true }, + 'The fiscal year from 2026-01-01 to 2026-12-31 needs to be reopened before the fiscal year before it, as it opened with its closing.' + ], + [ + 'a transmission of its E-Bilanz has a result that is not known', + { stage: 'unknown', transmitter: 'configured' }, + 'A transmission of the E-Bilanz of the fiscal year may have reached the tax administration, and its result is not known. Settle it ' + + 'before the fiscal year is reopened.' + ], + [ + 'a transmission of its E-Bilanz is running', + { stage: 'sending', transmitter: 'configured', transmissionDurationInMs: 600_000 }, + 'The E-Bilanz of the fiscal year is being sent, or filed by hand, right now.' + ] + ])('shows why the api refuses it while %s, and stays open', async (_, options, refusal) => { + const [fixture, root] = await render(options); + const dialog: HTMLDialogElement = await openDialog(fixture, root); + + await BookkeepingTestingUtilities.type(fixture, findReason(dialog), REASON); + dialog.querySelector('input[type="checkbox"]')?.click(); + await BookkeepingTestingUtilities.renderAnswered(fixture); + await submit(fixture, dialog); + + expect(findReopenings()).toHaveLength(1); + expect(BookkeepingTestingUtilities.getText(dialog.querySelector('[role="alert"]'))).toBe(`Error ${refusal}`); + expect(dialog.open).toBe(true); + expect(backend.getFiscalYears()[0]?.closedAt).not.toBeNull(); + }); +}); diff --git a/projects/ngx-bookkeeping/fiscal-years/fiscal-year-reopening-dialog.component.ts b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-reopening-dialog.component.ts new file mode 100644 index 0000000..ec43078 --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-reopening-dialog.component.ts @@ -0,0 +1,132 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { Component, computed, inject, resource, ResourceRef, Signal, signal, WritableSignal } from '@angular/core'; +import { + BOOKKEEPING_CONFIG, + BookkeepingCommonLabels, + BookkeepingFiscalYearsLabels, + BookkeepingService, + FISCAL_YEAR_FILING_RESOLVER, + FiscalYearFilingResolver +} from '@service-soft/ngx-bookkeeping/api'; +import { ErrorResponseUtilities } from '@service-soft/ngx-error-handling/error-response'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { DIALOG_DATA, DialogRef } from '@service-soft/ui/dialog'; +import { FormComponent } from '@service-soft/ui/form'; +import { InputBooleanComponent } from '@service-soft/ui/input-boolean'; +import { InputTextareaComponent } from '@service-soft/ui/input-textarea'; +import { LoadingDirective } from '@service-soft/ui/loading'; +import { FiscalYearReopeningResultModel } from 'zibri-contract'; + +import { FiscalYearReopeningDialogData } from './fiscal-year-reopening-dialog-data.model'; + +// the longest reason the api takes +const MAX_REASON_LENGTH: number = 500; + +/** + * Reopens a closed fiscal year once the user gave the reason, which is required, after saying what reopening does and + * keeps. Whether its accounts are filed comes from the FiscalYearFilingResolver provided, like the E-Bilanz: a filed + * fiscal year is reopened only to correct them, which the user confirms with a checkbox that is required then. Without + * a resolver, the user says it. The api asks for a second factor. A refusal of the api, like while the next fiscal + * year is closed, shows its message in the dialog, which closes with what reopening posted once it did. Only used by + * the fiscal years. + */ +@Component({ + selector: 'ngx-fiscal-year-reopening-dialog', + templateUrl: './fiscal-year-reopening-dialog.component.html', + imports: [ButtonComponent, CalloutComponent, FormComponent, InputBooleanComponent, InputTextareaComponent, LoadingDirective] +}) +export class FiscalYearReopeningDialogComponent { + private readonly bookkeepingService: BookkeepingService = inject(BookkeepingService); + + private readonly filingResolver: FiscalYearFilingResolver | undefined = inject(FISCAL_YEAR_FILING_RESOLVER); + + /** + * The fiscal year to reopen. + */ + protected readonly data: FiscalYearReopeningDialogData = inject(DIALOG_DATA); + + /** + * The dialog, to close it with what reopening posted. + */ + protected readonly dialogRef: DialogRef = inject>(DialogRef); + + /** + * The texts of the fiscal years. + */ + protected readonly labels: BookkeepingFiscalYearsLabels = inject(BOOKKEEPING_CONFIG).labels.fiscalYears; + + /** + * The texts several views show. + */ + protected readonly commonLabels: BookkeepingCommonLabels = inject(BOOKKEEPING_CONFIG).labels.common; + + /** + * The longest reason the api takes. + */ + protected readonly maxReasonLength: number = MAX_REASON_LENGTH; + + // undefined without a resolver, and while it couldn't tell, which the user then says + private readonly filing: ResourceRef = resource({ + loader: async () => await this.filingResolver?.resolveFiled(this.data.fiscalYear.id) + }); + + /** + * Whether the accounts of the fiscal year are filed, undefined while that isn't known. + */ + protected readonly filed: Signal = computed(() => this.filing.hasValue() ? this.filing.value() : undefined); + + /** + * Whether it is loading whether they are filed. + */ + protected readonly loadingFiled: Signal = computed(() => this.filing.isLoading()); + + /** + * Why it is reopened. + */ + protected readonly reason: WritableSignal = signal(''); + + /** + * Whether the reopening corrects accounts already filed. + */ + protected readonly forCorrection: WritableSignal = signal(false); + + /** + * Whether the fiscal year is being reopened. + */ + protected readonly reopening: WritableSignal = signal(false); + + /** + * Why the api refused it, its paragraphs one per line, or undefined while it refused none. + */ + protected readonly error: WritableSignal = signal(undefined); + + /** + * Reopens the fiscal year, which the form only submits with a reason, and for filed accounts with the checkbox. + */ + protected async reopen(): Promise { + // while it isn't known whether its accounts are filed, it isn't known whether the reopening corrects them + if (this.loadingFiled()) { + return; + } + this.reopening.set(true); + this.error.set(undefined); + try { + // the api asks for the second factor of the user, which the interceptor of the auth of the app asks for. + // Not filed, it is reopened without forCorrection, which the api refuses then. + const forCorrection: boolean = this.filed() === false ? false : this.forCorrection(); + this.dialogRef.close(await this.bookkeepingService.reopenFiscalYear(this.data.fiscalYear.id, { reason: this.reason().trim(), forCorrection })); + } + catch (error) { + // a refusal of the api is the answer, like while a later fiscal year is closed. Anything else is a mistake, + // which goes on to the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.error.set(ErrorResponseUtilities.findMessage(error) ?? this.commonLabels.requestFailed); + } + finally { + this.reopening.set(false); + } + } +} diff --git a/projects/ngx-bookkeeping/fiscal-years/fiscal-year-row-view.model.ts b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-row-view.model.ts new file mode 100644 index 0000000..1caaa33 --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/fiscal-year-row-view.model.ts @@ -0,0 +1,25 @@ +/** + * A fiscal year as the table of the fiscal years shows it. + */ +export type FiscalYearRowView = { + /** + * The id of the fiscal year. + */ + id: string, + /** + * What it is called, like '2026'. + */ + label: string, + /** + * Its first day, formatted. + */ + start: string, + /** + * Its last day, formatted. + */ + end: string, + /** + * Whether it is open, or when it was closed. + */ + status: string +}; diff --git a/projects/ngx-bookkeeping/fiscal-years/fiscal-years.component.html b/projects/ngx-bookkeeping/fiscal-years/fiscal-years.component.html new file mode 100644 index 0000000..e3bc4f0 --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/fiscal-years.component.html @@ -0,0 +1,55 @@ +
+ @if (loadingFailed()) { + + } + + +
+ {{ labels.add }} + + @if (nextStart(); as nextStart) { +

{{ nextStart }}

+ } @else { + + } + + @if (addError(); as message) { + + } +
+ + +

{{ addedLabel() }}

+
+
+
+ + @if (fiscalYear(); as fiscalYear) { +
+ + {{ fiscalYearTitle() }} + + @if (format(); as format) { + + } + +
+ } +
diff --git a/projects/ngx-bookkeeping/fiscal-years/fiscal-years.component.spec.ts b/projects/ngx-bookkeeping/fiscal-years/fiscal-years.component.spec.ts new file mode 100644 index 0000000..22776b9 --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/fiscal-years.component.spec.ts @@ -0,0 +1,225 @@ +import { HttpHeaders, provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideBookkeepingConfig } from '@service-soft/ngx-bookkeeping/api'; +import { DialogTestingUtilities } from 'testing/dialog'; +import { FormTestingUtilities } from 'testing/form'; +import { FakeAnswer } from 'testing/http'; +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; +import { FiscalYearClosingResultModel, FiscalYearModel } from 'zibri-contract'; + +import { BookkeepingTestingUtilities } from '../fixtures/bookkeeping-testing.utilities'; +import { ACCOUNT_IDS, BOOKKEEPING_BASE_URL, FISCAL_YEAR_2026, FISCAL_YEAR_IDS, FISCAL_YEARS, INVOICE_REVERSAL, LEGAL_RESERVE_PROPOSAL, toJson } from '../fixtures/bookkeeping.fixtures'; +import { FiscalYearsComponent } from './fiscal-years.component'; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [FiscalYearsComponent] +}) +class HostComponent {} + +const PROPOSALS_PATH: string = `GET ${BOOKKEEPING_BASE_URL}/fiscal-years/${FISCAL_YEAR_IDS.year2026}/closing-proposals`; + +const FISCAL_YEAR_2027: FiscalYearModel = { + ...FISCAL_YEAR_2026, + id: '2f8e6d5c-4b32-4031-8c7b-9e5f4d2c8b63', + start: new Date('2027-01-01T00:00:00.000Z'), + end: new Date('2027-12-31T00:00:00.000Z'), + lastSequence: 1 +}; + +function getAnswers(fiscalYears: FiscalYearModel[] = FISCAL_YEARS, proposals: unknown[] = [LEGAL_RESERVE_PROPOSAL]): Record { + return { + ...BookkeepingTestingUtilities.getBookAnswers(), + [`GET ${BOOKKEEPING_BASE_URL}/fiscal-years`]: { status: 200, body: toJson(fiscalYears) }, + [PROPOSALS_PATH]: { status: 200, body: toJson(proposals) }, + [`GET ${BOOKKEEPING_BASE_URL}/fiscal-years/${FISCAL_YEAR_2027.id}/closing-proposals`]: { status: 200, body: [] } + }; +} + +async function render(fiscalYears?: FiscalYearModel[]): Promise<[ComponentFixture, HTMLElement]> { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + await BookkeepingTestingUtilities.settle(fixture, getAnswers(fiscalYears)); + return [fixture, fixture.nativeElement as HTMLElement]; +} + +function getSection(root: HTMLElement, selector: string): HTMLElement { + const section: HTMLElement | null = root.querySelector(selector); + if (section == undefined) { + throw new Error(`There is no ${selector}.`); + } + return section; +} + +// answers the question of a dialog the view asked. +async function answer(fixture: ComponentFixture, button: string): Promise { + const dialog: HTMLDialogElement = await vi.waitFor(() => { + TestBed.tick(); + const opened: HTMLDialogElement | undefined = [...document.querySelectorAll('dialog[open]')].at(-1); + if (opened == undefined) { + throw new Error('No question was asked.'); + } + return opened; + }); + FormTestingUtilities.click(dialog, button); + await BookkeepingTestingUtilities.render(fixture); +} + +describe('FiscalYearsComponent', () => { + let removeModalDialogs: () => void; + + beforeEach(() => { + removeModalDialogs = DialogTestingUtilities.addModalDialogs(); + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + provideBookkeepingConfig({ baseUrl: BOOKKEEPING_BASE_URL, conformances: { 'ug-legal-reserve': 'Legal reserve of a UG' } }) + ] + }); + }); + + afterEach(() => { + removeModalDialogs(); + for (const dialog of document.querySelectorAll('ui-dialog')) { + dialog.remove(); + } + }); + + test('lists the fiscal years, the latest first, and shows the one opened from the table', async () => { + const [fixture, root] = await render(); + + expect([...root.querySelectorAll('ui-local-table tbody tr')].map(row => BookkeepingTestingUtilities.getText(row))).toEqual([ + // each value after its column, which a phone shows as a card of the row + 'Fiscal year 2026 Start 01/01/2026 End 12/31/2026 Status Open', + 'Fiscal year 2025 Start 01/01/2025 End 12/31/2025 Status Closed on 02/15/2026' + ]); + expect(root.querySelector('h2.text-headline, ui-heading.text-headline')?.textContent.trim()).toBe('Fiscal year 2026'); + + FormTestingUtilities.click(root.querySelector('ui-local-table') ?? root, '2025'); + await BookkeepingTestingUtilities.settle(fixture, getAnswers()); + + const heading: HTMLElement = getSection(root, 'ui-heading.text-headline'); + expect(heading.textContent.trim()).toBe('Fiscal year 2025'); + expect(document.activeElement).toBe(heading); + // a closed fiscal year shows what it was closed with, and can't be changed + expect(BookkeepingTestingUtilities.getText(root.querySelector('ngx-fiscal-year-details ui-data-list'))).toBe( + 'Average number of employees 1 Note below the balance sheet Haftungsverhältnisse nach § 268 Abs. 7 HGB bestehen nicht. ' + + 'Before this fiscal year Founded in this fiscal year' + ); + expect(root.querySelector('ngx-fiscal-year-details form')).toBeNull(); + expect(BookkeepingTestingUtilities.getText(root.querySelector('ngx-fiscal-year-closing'))).toContain('The fiscal year was closed on 02/15/2026.'); + }); + + test('saves what the statements of an open fiscal year need, and for the first of the books what the company was before', async () => { + const [fixture, root] = await render([FISCAL_YEAR_2026]); + const details: HTMLElement = getSection(root, 'ngx-fiscal-year-details'); + + await BookkeepingTestingUtilities.type(fixture, FormTestingUtilities.findInput(details, 'averageEmployees'), '2.5'); + await BookkeepingTestingUtilities.select(fixture, details, 'Before this fiscal year', 'Existed before as a small corporation'); + FormTestingUtilities.click(details, 'Save'); + await BookkeepingTestingUtilities.render(fixture); + const request: TestRequest = TestBed.inject(HttpTestingController) + .expectOne({ method: 'PATCH', url: `${BOOKKEEPING_BASE_URL}/fiscal-years/${FISCAL_YEAR_IDS.year2026}` }); + // eslint-disable-next-line unicorn/no-null -- the api takes null for a value the fiscal year doesn't have + expect(request.request.body).toEqual({ averageEmployees: 2.5, balanceSheetNote: null, founded: false, previousSizeClass: 'SMALL' }); + request.flush(toJson({ ...FISCAL_YEAR_2026, averageEmployees: 2.5, founded: false, previousSizeClass: 'SMALL' })); + await BookkeepingTestingUtilities.settle(fixture, getAnswers([FISCAL_YEAR_2026])); + + expect(details.querySelector('p[role="status"]')?.textContent.trim()).toBe('The fiscal year was saved.'); + }); + + test('posts a proposed entry after confirming it, and proposes it no more', async () => { + const [fixture, root] = await render(); + const closing: HTMLElement = getSection(root, 'ngx-fiscal-year-closing'); + expect(BookkeepingTestingUtilities.getText(closing.querySelector('ngx-closing-proposal'))).toBe( + 'Allocation to the legal reserve § 5a (3) GmbHG Proposed by Legal reserve of a UG · 12/31/2026 Post ' + + 'Account Debit Credit 2496 Allocation to the legal reserve €250.00 2930 Legal reserve €250.00' + ); + + closing.querySelector('button[aria-label="Post "Allocation to the legal reserve § 5a (3) GmbHG""], ngx-closing-proposal button') + ?.click(); + await answer(fixture, 'Post'); + const request: TestRequest = TestBed.inject(HttpTestingController).expectOne({ method: 'POST', url: `${BOOKKEEPING_BASE_URL}/entries` }); + expect(toJson(request.request.body)).toEqual(toJson(LEGAL_RESERVE_PROPOSAL.entry)); + request.flush(toJson(INVOICE_REVERSAL)); + await BookkeepingTestingUtilities.settle(fixture, getAnswers(FISCAL_YEARS, [])); + + expect(closing.querySelector('p[role="status"]')?.textContent.trim()).toBe('The proposed entry was posted as entry 5.'); + expect(BookkeepingTestingUtilities.getText(closing)).toContain('No entry is proposed before closing.'); + }); + + test('closes the fiscal year into the result account after confirming it, and shows the next one in the table', async () => { + const [fixture, root] = await render(); + const closing: HTMLElement = getSection(root, 'ngx-fiscal-year-closing'); + + await BookkeepingTestingUtilities.select(fixture, closing, 'Result account', '2970 Profit carried forward'); + FormTestingUtilities.click(closing, 'Close fiscal year'); + await answer(fixture, 'Close fiscal year'); + const request: TestRequest = TestBed.inject(HttpTestingController) + .expectOne({ method: 'POST', url: `${BOOKKEEPING_BASE_URL}/fiscal-years/${FISCAL_YEAR_IDS.year2026}/closing` }); + expect(request.request.body).toEqual({ resultAccountId: ACCOUNT_IDS.carriedForward }); + const result: FiscalYearClosingResultModel = { + fiscalYear: { ...FISCAL_YEAR_2026, closedAt: new Date('2027-02-01T10:00:00.000Z') }, + nextFiscalYear: FISCAL_YEAR_2027, + closingEntry: INVOICE_REVERSAL, + openingEntry: INVOICE_REVERSAL + }; + request.flush(toJson(result)); + await BookkeepingTestingUtilities.settle(fixture, getAnswers()); + + expect(closing.querySelector('p[role="status"]')?.textContent.trim()) + .toBe('The fiscal year 2026 was closed, and the fiscal year 2027 opened with its balances.'); + expect([...root.querySelectorAll('ui-local-table tbody tr')].map(row => BookkeepingTestingUtilities.getText(row).split(' Start')[0])) + .toEqual(['Fiscal year 2027', 'Fiscal year 2026', 'Fiscal year 2025']); + expect(closing.querySelector('form')).toBeNull(); + }); + + test('adds the fiscal year after the last, and shows it', async () => { + const [fixture, root] = await render(); + const add: HTMLElement = getSection(root, 'section'); + expect(BookkeepingTestingUtilities.getText(add)).toContain('It starts on 01/01/2027, the day after the last fiscal year.'); + // the empty end says the day the api ends the year on, and holds no example date that reads as one + expect(BookkeepingTestingUtilities.getText(add)).toContain('It ends on 12/31/2027, a year after its start, when empty'); + expect(FormTestingUtilities.findInput(add, 'end')?.placeholder).toBe('MM/DD/YYYY'); + + FormTestingUtilities.click(add, 'Add a fiscal year'); + await BookkeepingTestingUtilities.render(fixture); + const request: TestRequest = TestBed.inject(HttpTestingController).expectOne({ method: 'POST', url: `${BOOKKEEPING_BASE_URL}/fiscal-years` }); + expect(request.request.body).toEqual({}); + request.flush(toJson(FISCAL_YEAR_2027)); + await BookkeepingTestingUtilities.settle(fixture, getAnswers()); + + expect(add.querySelector('p[role="status"]')?.textContent.trim()).toBe('The fiscal year 2027 was added.'); + expect(getSection(root, 'ui-heading.text-headline').textContent.trim()).toBe('Fiscal year 2027'); + }); + + test('downloads the export for a tax audit without the documents, under the name the api gives it', async () => { + // jsdom has no object urls, which saving a file in the browser takes, and doesn't follow links. + const createObjectUrl: ReturnType = vi.fn(() => 'blob:export'); + vi.stubGlobal('URL', Object.assign(URL, { createObjectURL: createObjectUrl, revokeObjectURL: vi.fn() })); + const saved: string[] = []; + vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function(this: HTMLAnchorElement) { + saved.push(this.download); + }); + const [fixture, root] = await render(); + const exportSection: HTMLElement = getSection(root, 'ngx-fiscal-year-export'); + + exportSection.querySelector('input[type="checkbox"]')?.click(); + await BookkeepingTestingUtilities.render(fixture); + FormTestingUtilities.click(exportSection, 'Download the export'); + await BookkeepingTestingUtilities.render(fixture); + const request: TestRequest = TestBed.inject(HttpTestingController) + .expectOne(({ url }) => url === `${BOOKKEEPING_BASE_URL}/fiscal-years/${FISCAL_YEAR_IDS.year2026}/export`); + expect(request.request.params.toString()).toBe('documents=false'); + request.flush(new Blob(['PK']), { headers: new HttpHeaders({ 'content-disposition': 'attachment; filename="tax-audit-2026.zip"' }) }); + await BookkeepingTestingUtilities.settle(fixture, getAnswers()); + + expect(saved).toEqual(['tax-audit-2026.zip']); + expect(createObjectUrl).toHaveBeenCalledOnce(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); +}); diff --git a/projects/ngx-bookkeeping/fiscal-years/fiscal-years.component.ts b/projects/ngx-bookkeeping/fiscal-years/fiscal-years.component.ts new file mode 100644 index 0000000..bc9492f --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/fiscal-years.component.ts @@ -0,0 +1,282 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { + afterNextRender, + booleanAttribute, + Component, + computed, + ElementRef, + inject, + Injector, + input, + InputSignalWithTransform, + resource, + ResourceRef, + Signal, + signal, + viewChild, + WritableSignal +} from '@angular/core'; +import { BookkeepingDayUtilities, BookkeepingFiscalYearsLabels, BookkeepingFiscalYearUtilities, BookkeepingViewDirective } from '@service-soft/ngx-bookkeeping/api'; +import { ErrorResponseUtilities } from '@service-soft/ngx-error-handling/error-response'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { FormComponent } from '@service-soft/ui/form'; +import { HeadingComponent, HeadingLevel } from '@service-soft/ui/heading'; +import { InputDateComponent } from '@service-soft/ui/input-date'; +import { LoadingDirective } from '@service-soft/ui/loading'; +import { LocalTableColumn, LocalTableComponent } from '@service-soft/ui/local-table'; +import { BookkeepingAccountModel, FiscalYearClosingResultModel, FiscalYearModel, FiscalYearReopeningResultModel, NewFiscalYearModel } from 'zibri-contract'; + +import { FiscalYearClosingComponent } from './fiscal-year-closing.component'; +import { FiscalYearDetailsComponent } from './fiscal-year-details.component'; +import { FiscalYearExportComponent } from './fiscal-year-export.component'; +import { FiscalYearRowView } from './fiscal-year-row-view.model'; + +// the sections of a fiscal year are headed one level below it, and a heading of level 6 has no level below. +const SECTION_LEVELS: Record = { 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 6 }; + +/** + * The fiscal years of the books of provideBookkeepingConfig: ``. A table lists them, and adds + * one: the first from the day the books start on, every later one from the day after the last. The fiscal year opened + * from the table, the one of today at first, shows what its statements need beside the books, which the user changes + * while it is open, its closing with the entries proposed before, and its export for a tax audit. + * + * With `canReopen`, like with `bookkeeping.reopen-fiscal-year`, a closed fiscal year is reopened to correct its books, + * with a reason, in a dialog. Whether its E-Bilanz is filed, which it then is reopened only to correct, the dialog + * asks the FiscalYearFilingResolver provided, like `provideFiscalYearFilingResolver(EBilanzService)`. Its default + * comes from the config. + */ +@Component({ + selector: 'ngx-fiscal-years', + templateUrl: './fiscal-years.component.html', + imports: [ + ButtonComponent, + CalloutComponent, + FiscalYearClosingComponent, + FiscalYearDetailsComponent, + FiscalYearExportComponent, + FormComponent, + HeadingComponent, + InputDateComponent, + LoadingDirective, + LocalTableComponent + ], + host: { class: 'block' } +}) +export class FiscalYearsComponent extends BookkeepingViewDirective { + private readonly injector: Injector = inject(Injector); + + private readonly fiscalYearHeading: Signal | undefined> = viewChild('fiscalYearHeading', { read: ElementRef }); + + /** + * Whether the user may reopen a closed fiscal year, like with `bookkeeping.reopen-fiscal-year`. + */ + readonly canReopen: InputSignalWithTransform = input(this.config.canReopen, { transform: booleanAttribute }); + + /** + * The texts of the fiscal years. + */ + protected readonly labels: BookkeepingFiscalYearsLabels = this.config.labels.fiscalYears; + + /** + * The level of the headings of the sections of the view. + */ + protected readonly headingLevel: HeadingLevel = this.config.headingLevel; + + /** + * The level of the headings of the sections of a fiscal year, one below. + */ + protected readonly sectionLevel: HeadingLevel = SECTION_LEVELS[this.config.headingLevel]; + + private readonly accounts: ResourceRef = resource({ + loader: async () => await this.bookkeepingService.resolveAccounts() + }); + + /** + * The accounts of the books, which the closing books on. + */ + protected readonly accountList: Signal = computed(() => { + return this.accounts.hasValue() ? this.accounts.value() ?? [] : []; + }); + + /** + * Whether the books are loading. + */ + protected readonly isLoading: Signal = computed(() => { + return this.fiscalYears.isLoading() || this.settings.isLoading() || this.accounts.isLoading(); + }); + + /** + * Whether the books couldn't be loaded. + */ + protected readonly loadingFailed: Signal = computed(() => { + return [this.fiscalYears, this.settings, this.accounts].some(loaded => loaded.error() != undefined); + }); + + /** + * The columns of the table. + */ + protected readonly columns: LocalTableColumn[] = [ + { key: 'label', label: this.commonLabels.fiscalYear, value: row => row.label }, + { key: 'start', label: this.labels.start, value: row => row.start }, + { key: 'end', label: this.labels.end, value: row => row.end }, + { key: 'status', label: this.labels.status, value: row => row.status } + ]; + + /** + * The fiscal years as the table shows them, the latest first. + */ + protected readonly rows: Signal = computed(() => [...this.getFiscalYears()].reverse().map(fiscalYear => ({ + id: fiscalYear.id, + label: this.resolveLabel(fiscalYear), + start: this.formatDay(fiscalYear.start), + end: this.formatDay(fiscalYear.end), + status: fiscalYear.closedAt == undefined ? this.labels.open : this.labels.closedOn(this.formatDay(fiscalYear.closedAt)) + }))); + + /** + * The heading of the fiscal year that shows. + */ + protected readonly fiscalYearTitle: Signal = computed(() => { + const fiscalYear: FiscalYearModel | undefined = this.fiscalYear(); + return fiscalYear == undefined ? '' : this.labels.fiscalYear(this.resolveLabel(fiscalYear)); + }); + + /** + * Whether the fiscal year that shows is the first of the books. + */ + protected readonly isFirst: Signal = computed(() => this.getFiscalYears()[0]?.id === this.fiscalYearId()); + + private readonly lastFiscalYear: Signal = computed(() => this.getFiscalYears().at(-1)); + + /** + * What adding says about the first day of a fiscal year after the last, or undefined for the first of the books, + * which the user gives. + */ + protected readonly nextStart: Signal = computed(() => { + const last: FiscalYearModel | undefined = this.lastFiscalYear(); + return last == undefined ? undefined : this.labels.nextStart(this.formatDay(BookkeepingDayUtilities.resolveNextDay(last.end))); + }); + + /** + * The hint below the last day of the fiscal year to add. One after another names the day the api ends it on when + * the input stays empty. + */ + protected readonly endHint: Signal = computed(() => { + const last: FiscalYearModel | undefined = this.lastFiscalYear(); + if (last == undefined) { + return this.labels.firstEndHint; + } + return this.labels.nextEndHint(this.formatDay(BookkeepingDayUtilities.resolveYearEnd(BookkeepingDayUtilities.resolveNextDay(last.end)))); + }); + + /** + * The first day of the fiscal year to add, the first of the books. + */ + protected readonly newStart: WritableSignal = signal(undefined); + + /** + * The last day of the fiscal year to add, undefined for the default of the api. + */ + protected readonly newEnd: WritableSignal = signal(undefined); + + /** + * Whether a fiscal year is being added. + */ + protected readonly adding: WritableSignal = signal(false); + + /** + * What the view last said about adding, or an empty string. + */ + protected readonly addedLabel: WritableSignal = signal(''); + + /** + * Why the api refused to add the fiscal year, or undefined while it refused none. + */ + protected readonly addError: WritableSignal = signal(undefined); + + /** + * What identifies a row of the table, its fiscal year. + * @param row - The row. + * @returns The id of its fiscal year. + */ + protected readonly getRowKey: (row: FiscalYearRowView) => string = row => row.id; + + /** + * Shows a fiscal year of the table, and moves the focus to its heading, where its sections start. + * @param row - The fiscal year. + */ + protected open(row: FiscalYearRowView): void { + this.fiscalYearId.set(row.id); + afterNextRender(() => this.fiscalYearHeading()?.nativeElement.focus(), { injector: this.injector }); + } + + /** + * Adds a fiscal year: the first from the day the user gives, every later one from the day after the last, and + * shows it. + */ + protected async add(): Promise { + const start: Date | undefined = this.newStart(); + const end: Date | undefined = this.newEnd(); + const isFirst: boolean = this.lastFiscalYear() == undefined; + const fiscalYear: NewFiscalYearModel = { + ...isFirst && start != undefined ? { start: BookkeepingDayUtilities.resolveDay(start) } : {}, + ...end == undefined ? {} : { end: BookkeepingDayUtilities.resolveDay(end) } + }; + this.adding.set(true); + this.addedLabel.set(''); + this.addError.set(undefined); + try { + const created: FiscalYearModel = await this.bookkeepingService.createFiscalYear(fiscalYear); + this.fiscalYears.update(fiscalYears => [...fiscalYears ?? [], created]); + this.fiscalYearId.set(created.id); + this.newStart.set(undefined); + this.newEnd.set(undefined); + this.addedLabel.set(this.labels.added(this.resolveLabel(created))); + } + catch (error) { + // a refusal of the api is the answer, like for a first day that doesn't follow the last fiscal year. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.addError.set(ErrorResponseUtilities.findMessage(error) ?? this.commonLabels.requestFailed); + } + finally { + this.adding.set(false); + } + } + + /** + * Takes a fiscal year whose details were saved into the table. + * @param saved - The fiscal year, as the api answered saving it. + */ + protected replace(saved: FiscalYearModel): void { + this.fiscalYears.update(fiscalYears => (fiscalYears ?? []).map(fiscalYear => fiscalYear.id === saved.id ? saved : fiscalYear)); + } + + /** + * Takes a closed fiscal year, and the next one it opened, into the table. + * @param result - What closing answered. + */ + protected takeClosing(result: FiscalYearClosingResultModel): void { + this.fiscalYears.update(fiscalYears => { + const others: FiscalYearModel[] = (fiscalYears ?? []) + .filter(fiscalYear => fiscalYear.id !== result.fiscalYear.id && fiscalYear.id !== result.nextFiscalYear.id); + return [...others, result.fiscalYear, result.nextFiscalYear].sort((a, b) => a.start.getTime() - b.start.getTime()); + }); + } + + /** + * Takes a reopened fiscal year, and the next one whose opening balances were reversed, into the table. + * @param result - What reopening answered. + */ + protected takeReopening(result: FiscalYearReopeningResultModel): void { + const changed: FiscalYearModel[] = result.nextFiscalYear == undefined ? [result.fiscalYear] : [result.fiscalYear, result.nextFiscalYear]; + this.fiscalYears.update(fiscalYears => (fiscalYears ?? []) + .map(fiscalYear => changed.find(candidate => candidate.id === fiscalYear.id) ?? fiscalYear)); + } + + private resolveLabel(fiscalYear: FiscalYearModel): string { + return BookkeepingFiscalYearUtilities.resolveLabel(fiscalYear, this.config.dateFormat, this.locale); + } +} diff --git a/projects/ngx-bookkeeping/fiscal-years/fiscal-years.stories.ts b/projects/ngx-bookkeeping/fiscal-years/fiscal-years.stories.ts new file mode 100644 index 0000000..89b8f06 --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/fiscal-years.stories.ts @@ -0,0 +1,101 @@ +import { EBilanzService, provideBookkeepingConfig, provideFiscalYearFilingResolver } from '@service-soft/ngx-bookkeeping/api'; +import { Meta, StoryObj } from '@storybook/angular'; + +import { BookkeepingStoryUtilities } from '../fixtures/bookkeeping-story.utilities'; +import { BOOKKEEPING_BASE_URL, FISCAL_YEAR_2026, FISCAL_YEAR_IDS, LEGAL_RESERVE_PROPOSAL, toJson } from '../fixtures/bookkeeping.fixtures'; +import { FakeEBilanzBackendOptions } from '../fixtures/fake-e-bilanz-backend-options.model'; +import { FiscalYearsComponent } from './fiscal-years.component'; + +// the books and the E-Bilanz of the fixtures, whose fiscal year 2025 is closed, for a user who may reopen it. The +// dialog knows from the E-Bilanz whether it is filed. +function provideReopening(options: FakeEBilanzBackendOptions): ReturnType { + return BookkeepingStoryUtilities.provideEBilanzBackend(options, {}, [ + provideBookkeepingConfig({ baseUrl: BOOKKEEPING_BASE_URL, canReopen: true }), + provideFiscalYearFilingResolver(EBilanzService) + ]); +} + +// opens the fiscal year 2025 from the table, and the dialog that reopens it. +async function openReopening(canvasElement: HTMLElement): Promise { + const table: HTMLElement = await BookkeepingStoryUtilities.waitForElement(canvasElement, 'ui-local-table'); + (await BookkeepingStoryUtilities.waitForElement(table, 'button', '2025')).click(); + // the fiscal year of today shows first, which can be closed as well + await BookkeepingStoryUtilities.waitForElement(canvasElement, 'ui-heading', 'Fiscal year 2025'); + (await BookkeepingStoryUtilities.waitForElement(canvasElement, 'ngx-fiscal-year-closing button', 'Reopen fiscal year')).click(); + const dialog: HTMLDialogElement = await BookkeepingStoryUtilities.waitForElement(document, 'dialog[open]'); + await BookkeepingStoryUtilities.waitForElement(dialog, 'textarea'); + return dialog; +} + +const PROPOSALS: string = `GET fiscal-years/${FISCAL_YEAR_IDS.year2026}/closing-proposals`; + +const meta: Meta = { + title: 'Bookkeeping/Fiscal years', + component: FiscalYearsComponent, + render: () => ({ template: '' }) +}; +export default meta; + +type Story = StoryObj; + +// the open fiscal year with the reserve of a UG to post before closing it. +export const Default: Story = { + decorators: [ + BookkeepingStoryUtilities.provideBackend( + { [PROPOSALS]: { status: 200, body: toJson([LEGAL_RESERVE_PROPOSAL]) } }, + { conformances: { 'ug-legal-reserve': 'Legal reserve of a UG' } } + ) + ] +}; + +// the first fiscal year of the books says what the company was before it. +export const FirstFiscalYear: Story = { + decorators: [ + BookkeepingStoryUtilities.provideBackend({ + 'GET fiscal-years': { status: 200, body: toJson([FISCAL_YEAR_2026]) }, + [PROPOSALS]: { status: 200, body: [] } + }) + ] +}; + +export const NoFiscalYears: Story = { + decorators: [BookkeepingStoryUtilities.provideBackend({ 'GET fiscal-years': { status: 200, body: [] } })] +}; + +// a user without the permission to close a fiscal year. +export const ProposalsFailed: Story = { + decorators: [BookkeepingStoryUtilities.provideBackend({ [PROPOSALS]: { status: 403 } })] +}; + +// the dialog that reopens the closed fiscal year 2025, whose E-Bilanz isn't filed: what reopening does, and its reason. +export const Reopen: Story = { + decorators: [provideReopening({ stage: 'prepared' })], + play: async ({ canvasElement }) => { + await openReopening(canvasElement); + } +}; + +// reopening a fiscal year whose E-Bilanz is filed, which is only reopened to correct it. +export const ReopenFiled: Story = { + decorators: [provideReopening({ stage: 'transmitted', transmitter: 'configured' })], + play: async ({ canvasElement }) => { + const dialog: HTMLDialogElement = await openReopening(canvasElement); + await BookkeepingStoryUtilities.waitForElement(dialog, 'input[type="checkbox"]'); + } +}; + +// the api refuses it while the fiscal year after it is closed, which is reopened first. +export const ReopenRefused: Story = { + decorators: [provideReopening({ laterYearClosed: true })], + play: async ({ canvasElement }) => { + const dialog: HTMLDialogElement = await openReopening(canvasElement); + const reason: HTMLTextAreaElement = await BookkeepingStoryUtilities.waitForElement(dialog, 'textarea'); + reason.value = 'Depreciation of the office equipment missing'; + reason.dispatchEvent(new InputEvent('input', { inputType: 'insertText' })); + await new Promise(resolve => setTimeout(resolve, 50)); + (await BookkeepingStoryUtilities.waitForElement(dialog, 'button[type="submit"]')).click(); + await BookkeepingStoryUtilities.waitForElement(dialog, '[role="alert"]'); + // the button is enabled again, whose color fades back + await new Promise(resolve => setTimeout(resolve, 300)); + } +}; diff --git a/projects/ngx-bookkeeping/fiscal-years/ng-package.json b/projects/ngx-bookkeeping/fiscal-years/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-bookkeeping/fiscal-years/public-api.ts b/projects/ngx-bookkeeping/fiscal-years/public-api.ts new file mode 100644 index 0000000..2ea8f60 --- /dev/null +++ b/projects/ngx-bookkeeping/fiscal-years/public-api.ts @@ -0,0 +1 @@ +export * from './fiscal-years.component'; diff --git a/projects/ngx-bookkeeping/fixtures/bookkeeping-story.utilities.ts b/projects/ngx-bookkeeping/fixtures/bookkeeping-story.utilities.ts new file mode 100644 index 0000000..51134a7 --- /dev/null +++ b/projects/ngx-bookkeeping/fixtures/bookkeeping-story.utilities.ts @@ -0,0 +1,98 @@ +import { HttpBackend, provideHttpClient } from '@angular/common/http'; +import { Provider } from '@angular/core'; +import { BookkeepingConfigChanges, EBilanzConfigChanges, provideBookkeepingConfig, provideEBilanzConfig } from '@service-soft/ngx-bookkeeping/api'; +import { applicationConfig } from '@storybook/angular'; +import { FakeAnswer, HttpTestingUtilities } from 'testing/http'; + +import { ACCOUNTS, BOOKKEEPING_BASE_URL, FISCAL_YEARS, SETTINGS, toJson } from './bookkeeping.fixtures'; +import { E_BILANZ_BASE_URL } from './e-bilanz.fixtures'; +import { FakeEBilanzBackendOptions } from './fake-e-bilanz-backend-options.model'; +import { FakeEBilanzBackend } from './fake-e-bilanz-backend.model'; + +/** + * Utilities for the stories of the views of the books, which render them against the answers of the fixtures. + */ +export abstract class BookkeepingStoryUtilities { + /** + * Provides a backend answering like the E-Bilanz routes and the bookkeeping routes would, the config of the books + * with their url, and the config of the E-Bilanz with its url. Each render of the story gets a backend of its own, + * so a transmission starts when it renders, not when the stories load. + * @param options - How the fake backend answers. + * @param config - The config of the E-Bilanz of the story beside its url. + * @param providers - Further providers of the story, like the LOCALE_ID. + * @returns The decorator of the story. + */ + static provideEBilanzBackend( + options: FakeEBilanzBackendOptions = {}, + config: EBilanzConfigChanges = {}, + providers: Provider[] = [] + ): ReturnType { + return applicationConfig({ + providers: [ + provideHttpClient(), + { provide: HttpBackend, useFactory: () => new FakeEBilanzBackend(options).createBackend() }, + provideBookkeepingConfig({ baseUrl: BOOKKEEPING_BASE_URL }), + provideEBilanzConfig({ baseUrl: E_BILANZ_BASE_URL, ...config }), + ...providers + ] + }); + } + + /** + * Waits for an element the view renders once it is clicked or once the api answered, like the result of a + * transmission the E-Bilanz loads again for after 2 seconds. Gives up after 5 seconds. + * @param root - The element or document to look in. + * @param selector - The selector of the element. + * @param text - The text the element has, without the whitespace around it. Any text when left out. + * @returns The first element that matches. + */ + static async waitForElement(root: ParentNode, selector: string, text?: string): Promise { + for (let attempt: number = 0; attempt < 250; attempt++) { + const found: T | undefined = [...root.querySelectorAll(selector)].find(element => text == undefined || element.textContent.trim() === text); + if (found != undefined) { + return found; + } + await new Promise(resolve => setTimeout(resolve, 20)); + } + throw new Error(`Nothing matches ${selector}.`); + } + + /** + * Gets the answer of a route that answers a model, as json. + * @param model - The model, like a report of the fixtures. + * @returns The answer. + */ + static getAnswer(model: unknown): FakeAnswer { + return { status: 200, body: toJson(model) }; + } + + /** + * Provides a backend answering like the bookkeeping routes would: the settings, the fiscal years and the accounts + * of the fixtures, and the answers of the story. + * @param answers - What else to answer, by the method and the path below the base url, like 'GET entries'. + * @param config - The config of the story beside the base url. + * @returns The decorator of the story. + */ + static provideBackend( + answers: Record, + config: BookkeepingConfigChanges = {} + ): ReturnType { + const books: Record = { + 'GET settings': { status: 200, body: toJson(SETTINGS) }, + 'GET fiscal-years': { status: 200, body: toJson(FISCAL_YEARS) }, + 'GET accounts': { status: 200, body: toJson(ACCOUNTS) }, + ...answers + }; + const routes: Record = Object.fromEntries(Object.entries(books).map(([route, answer]) => { + const [method, path] = route.split(' '); + return [`${method} ${BOOKKEEPING_BASE_URL}/${path}`, answer]; + })); + return applicationConfig({ + providers: [ + provideHttpClient(), + HttpTestingUtilities.provideAnswers(routes), + provideBookkeepingConfig({ baseUrl: BOOKKEEPING_BASE_URL, ...config }) + ] + }); + } +} diff --git a/projects/ngx-bookkeeping/fixtures/bookkeeping-testing.utilities.ts b/projects/ngx-bookkeeping/fixtures/bookkeeping-testing.utilities.ts new file mode 100644 index 0000000..72abf19 --- /dev/null +++ b/projects/ngx-bookkeeping/fixtures/bookkeeping-testing.utilities.ts @@ -0,0 +1,189 @@ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, TestRequest } from '@angular/common/http/testing'; +import { EnvironmentProviders, Provider } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { EBilanzConfigChanges, provideBookkeepingConfig, provideEBilanzConfig } from '@service-soft/ngx-bookkeeping/api'; +import { FakeAnswer, HttpTestingUtilities } from 'testing/http'; + +import { ACCOUNTS, BOOKKEEPING_BASE_URL, FISCAL_YEARS, SETTINGS, toJson } from './bookkeeping.fixtures'; +import { E_BILANZ_BASE_URL } from './e-bilanz.fixtures'; +import { FakeEBilanzBackend } from './fake-e-bilanz-backend.model'; + +/** + * Utilities for the specs of the views of the books, which render them against the answers of the fixtures. + */ +export abstract class BookkeepingTestingUtilities { + /** + * Gets the providers of a spec of the E-Bilanz: HttpClient on its fake backend, the config of the books with their + * url, and the config of the E-Bilanz with its url. + * @param backend - The fake backend of the spec. + * @param config - The config of the E-Bilanz beside its url. + * @returns The providers. + */ + static getEBilanzProviders(backend: FakeEBilanzBackend, config: EBilanzConfigChanges = {}): (Provider | EnvironmentProviders)[] { + return [ + provideHttpClient(), + backend.provide(), + provideBookkeepingConfig({ baseUrl: BOOKKEEPING_BASE_URL }), + provideEBilanzConfig({ baseUrl: E_BILANZ_BASE_URL, ...config }) + ]; + } + + /** + * Renders what changed once the requests it sent were answered, which a fake backend does right away, and the + * focus moved. + * @param fixture - The fixture. + */ + static async renderAnswered(fixture: ComponentFixture): Promise { + fixture.detectChanges(); + await fixture.whenStable(); + // the focus moves after the next render + await new Promise(resolve => setTimeout(resolve)); + await fixture.whenStable(); + } + + /** + * The answers every view loads first: the settings, the fiscal years and the accounts. + * @returns The answers, by the method and the path of their request. + */ + static getBookAnswers(): Record { + return { + [`GET ${BOOKKEEPING_BASE_URL}/settings`]: { status: 200, body: toJson(SETTINGS) }, + [`GET ${BOOKKEEPING_BASE_URL}/fiscal-years`]: { status: 200, body: toJson(FISCAL_YEARS) }, + [`GET ${BOOKKEEPING_BASE_URL}/accounts`]: { status: 200, body: toJson(ACCOUNTS) } + }; + } + + /** + * Answers the requests of a view until it sends none, and renders it. A view loads in rounds, like its report once + * the fiscal years arrived. + * @param fixture - The fixture of the view. + * @param answers - What to answer, by the method and the path of the request. + * @returns The requests it answered, to check what they sent. + */ + static async settle(fixture: ComponentFixture, answers: Record): Promise { + const controller: HttpTestingController = TestBed.inject(HttpTestingController); + const answered: TestRequest[] = []; + let requests: TestRequest[] = []; + // a request that is still open keeps the fixture from becoming stable, so every round is answered before it is + // awaited, and the view gets the time to send the requests of the next round. + do { + TestBed.tick(); + await new Promise(resolve => setTimeout(resolve)); + TestBed.tick(); + requests = HttpTestingUtilities.flushAll(controller, answers); + answered.push(...requests); + await new Promise(resolve => setTimeout(resolve)); + } + while (requests.length); + await fixture.whenStable(); + return answered; + } + + /** + * Gets the texts of an element one after the other, as a screen reader reads them. + * @param element - The element, or null. + * @returns The texts, separated by single spaces. + */ + static getText(element: Element | null | undefined): string { + if (element == undefined) { + return ''; + } + const walker: TreeWalker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT); + const texts: string[] = []; + while (walker.nextNode()) { + texts.push(walker.currentNode.textContent ?? ''); + } + return texts.join(' ').replaceAll(/\s+/g, ' ') + .trim(); + } + + /** + * Finds the request of a path among the answered ones. + * @param requests - The answered requests. + * @param path - The path below the base url, like 'reports/ledger'. + * @returns The last request of the path, or undefined when there was none. + */ + static findRequest(requests: TestRequest[], path: string): TestRequest | undefined { + return [...requests].reverse().find(request => request.request.url === `${BOOKKEEPING_BASE_URL}/${path}`); + } + + /** + * Types a text into an input like a user does. + * @param fixture - The fixture to render afterwards. + * @param input - The input. + * @param text - What to type. + */ + static async type( + fixture: ComponentFixture, + input: HTMLInputElement | HTMLTextAreaElement | null | undefined, + text: string + ): Promise { + if (input == undefined) { + throw new Error('There is no such input.'); + } + input.value = text; + input.dispatchEvent(new InputEvent('input', { inputType: 'insertText' })); + input.dispatchEvent(new Event('blur')); + await this.render(fixture); + } + + /** + * Chooses an option of an autocomplete like a user does: types its label and clicks it. + * @param fixture - The fixture to render afterwards. + * @param input - The input of the autocomplete. + * @param label - The label of the option. + */ + static async choose(fixture: ComponentFixture, input: HTMLInputElement | null | undefined, label: string): Promise { + if (input == undefined) { + throw new Error('There is no such autocomplete.'); + } + input.value = label; + input.dispatchEvent(new InputEvent('input', { inputType: 'insertText' })); + await this.render(fixture); + const option: HTMLElement | undefined = [...document.querySelectorAll('[role="option"]')] + .find(candidate => candidate.textContent.trim() === label); + if (option == undefined) { + throw new Error(`There is no option "${label}".`); + } + option.click(); + await this.render(fixture); + } + + /** + * Chooses an option of a select like a user does: opens it by its label and clicks the option. + * @param fixture - The fixture to render afterwards. + * @param root - The element the select is in. + * @param label - The label of the select. + * @param option - The label of the option. + */ + static async select(fixture: ComponentFixture, root: HTMLElement, label: string, option: string): Promise { + const labelElement: HTMLLabelElement | undefined = [...root.querySelectorAll('label')] + .find(candidate => candidate.textContent.replace('*', '').trim() === label); + const combobox: HTMLElement | null = root.querySelector(`[role="combobox"][aria-labelledby="${labelElement?.id ?? ''}"]`); + if (combobox == undefined) { + throw new Error(`There is no select "${label}".`); + } + combobox.click(); + await this.render(fixture); + const optionElement: HTMLElement | undefined = [...document.querySelectorAll('[role="option"]')] + .find(candidate => candidate.textContent.trim() === option); + if (optionElement == undefined) { + throw new Error(`There is no option "${option}".`); + } + optionElement.click(); + await this.render(fixture); + } + + /** + * Renders what changed, without waiting for the fixture to be stable, which a request the change sent would keep + * it from: settle answers those. + * @param fixture - The fixture. + */ + static async render(fixture: ComponentFixture): Promise { + fixture.detectChanges(); + TestBed.tick(); + await new Promise(resolve => setTimeout(resolve)); + TestBed.tick(); + } +} diff --git a/projects/ngx-bookkeeping/fixtures/bookkeeping.fixtures.ts b/projects/ngx-bookkeeping/fixtures/bookkeeping.fixtures.ts new file mode 100644 index 0000000..98ab986 --- /dev/null +++ b/projects/ngx-bookkeeping/fixtures/bookkeeping.fixtures.ts @@ -0,0 +1,571 @@ +/* eslint-disable unicorn/no-null -- the api answers null for every value a row doesn't have, which the fixtures mirror */ +import { BookkeepingAccountAmountModel, BookkeepingAccountModel, BookkeepingAccountType, BookkeepingClosingProposalModel, BookkeepingLedgerLineModel, BookkeepingLedgerReportModel, BookkeepingSettingsModel, BookkeepingStatementFormChoicesModel, BookkeepingStatementModel, BookkeepingStatementPositionModel, BookkeepingStatementType, BookkeepingTrialBalanceModel, FiscalYearModel, JournalEntryDetailsModel, JournalEntryLineModel, JournalEntryModel, JournalEntryPageModel } from 'zibri-contract'; + +// The books of a small company as the bookkeeping routes of zibri answer them: a closed fiscal year 2025 with a result +// of 950, and an open 2026 with its opening balances, a rent entry and its reversal, and an invoice. The numbers add up +// like the books they stand for, so every report tells the same story. Amounts are decimal strings without trailing +// zeros and days are midnight UTC, as the api writes them. Specs and stories send them through json first, like the +// api does, so the views read their dates as the strings of json. + +/** + * The url the specs and stories have the books at. + */ +export const BOOKKEEPING_BASE_URL: string = '/api/bookkeeping'; + +/** + * The tenant whose books the fixtures are. + */ +export const TENANT_ID: string = '6f1c2d3e-4b5a-4c6d-8e7f-9a0b1c2d3e4f'; + +const START_2026: string = '2026-01-01'; +const END_2026: string = '2026-12-31'; +const END_2025: string = '2025-12-31'; +const RENT_REFERENCE: string = 'L-2026-03'; +const OPENING_TEXT: string = 'Opening balances'; +const RENT_TEXT: string = 'Rent March'; +const REVERSAL_TEXT: string = 'Booked on the wrong account'; +const RETAIN_UNTIL: Date = new Date('2036-12-31T23:00:00.000Z'); + +/** + * What the accounts of the fixtures hold. + */ +type AccountKey = 'bank' | 'receivables' | 'transit' | 'outputTax' | 'capital' | 'reserve' | 'carriedForward' | 'reserveAllocation' + | 'rent' | 'oldRent' | 'revenue'; + +/** + * The ids of the accounts of the fixtures, by what they hold. + */ +export const ACCOUNT_IDS: Record = { + bank: '0b6d6a7e-61a4-4c2f-9d0e-5f2b8c1e7a90', + receivables: '1c7e7b8f-72b5-4d30-8e1f-6a3c9d2f8ba1', + transit: '2d8f8c90-83c6-4e41-9f20-7b4dae309cb2', + outputTax: '3e9091a1-94d7-4f52-8031-8c5ebf41adc3', + capital: '4fa1a2b2-a5e8-4063-9142-9d6fc052bed4', + reserve: '50b2b3c3-b6f9-4174-a253-ae70d163cfe5', + carriedForward: '61c3c4d4-c70a-4285-b364-bf81e274d0f6', + reserveAllocation: '72d4d5e5-d81b-4396-8475-c092f385e107', + rent: '83e5e6f6-e92c-44a7-9586-d1a30496f218', + oldRent: '94f6f707-fa3d-45b8-a697-e2b415a70329', + revenue: 'a507081a-0b4e-46c9-b7a8-f3c526b8143a' +}; + +/** + * The ids of the fiscal years of the fixtures. + */ +export const FISCAL_YEAR_IDS: Record<'year2025' | 'year2026', string> = { + year2025: '6d4e3c1f-7a52-4b6a-9f20-1e7d5c4b3a21', + year2026: '1e7d5c4b-3a21-4f20-9b6a-8d4e3c1f7a52' +}; + +/** + * The ids of the entries of the fixtures. + */ +export const ENTRY_IDS: Record<'opening' | 'rent' | 'rentReversal' | 'invoice' | 'invoiceReversal', string> = { + opening: 'e0000001-0000-4000-8000-000000000001', + rent: 'e0000001-0000-4000-8000-000000000002', + rentReversal: 'e0000001-0000-4000-8000-000000000003', + invoice: 'e0000001-0000-4000-8000-000000000004', + invoiceReversal: 'e0000001-0000-4000-8000-000000000005' +}; + +/** + * Gets a day of the books, as the api holds it. + * @param iso - The day, like '2026-03-31'. + * @returns The day at midnight UTC. + */ +function day(iso: string): Date { + return new Date(`${iso}T00:00:00.000Z`); +} + +/** + * Creates an open account of the books. + * @param id - Its id. + * @param number - Its number. + * @param name - Its name. + * @param type - What it holds. + * @param statementPosition - The position of the statements it is reported in, or null for none. + * @returns The account. + */ +function createAccount( + id: string, + number: string, + name: string, + type: BookkeepingAccountType, + statementPosition: string | null +): BookkeepingAccountModel { + return { id, tenantId: TENANT_ID, number, name, type, statementPosition, creditStatementPosition: null, closedAt: null }; +} + +/** + * The settings of the books: kept in euro, by a UG. + */ +export const SETTINGS: BookkeepingSettingsModel = { + id: '7a1b2c3d-4e5f-4061-8273-94a5b6c7d8e9', + tenantId: TENANT_ID, + currency: 'EUR', + legalForms: [{ legalForm: 'UG', validFrom: day('2025-01-01') }], + company: { + name: 'Acme Software UG (haftungsbeschränkt)', + seat: 'Berlin', + registerCourt: 'Amtsgericht Charlottenburg', + registerNumber: 'HRB 123456 B' + } +}; + +const BANK: BookkeepingAccountModel = { + ...createAccount(ACCOUNT_IDS.bank, '1200', 'Bank', BookkeepingAccountType.ASSET, 'assets.B.IV'), + creditStatementPosition: 'equity-and-liabilities.C.2' +}; +const RECEIVABLES: BookkeepingAccountModel = createAccount( + ACCOUNT_IDS.receivables, + '1400', + 'Receivables', + BookkeepingAccountType.ASSET, + 'assets.B.II.1' +); +const OUTPUT_TAX: BookkeepingAccountModel = { + ...createAccount(ACCOUNT_IDS.outputTax, '1776', 'Output tax 19 %', BookkeepingAccountType.LIABILITY, 'assets.B.II.4'), + creditStatementPosition: 'equity-and-liabilities.C.8' +}; +const CAPITAL: BookkeepingAccountModel = createAccount( + ACCOUNT_IDS.capital, + '2900', + 'Share capital', + BookkeepingAccountType.EQUITY, + 'equity-and-liabilities.A.I' +); +const CARRIED_FORWARD: BookkeepingAccountModel = createAccount( + ACCOUNT_IDS.carriedForward, + '2970', + 'Profit carried forward', + BookkeepingAccountType.EQUITY, + 'equity-and-liabilities.A.IV' +); +const RENT: BookkeepingAccountModel = createAccount(ACCOUNT_IDS.rent, '4210', 'Rent', BookkeepingAccountType.EXPENSE, 'income-statement.8'); +const REVENUE: BookkeepingAccountModel = createAccount( + ACCOUNT_IDS.revenue, + '8400', + 'Revenue 19 %', + BookkeepingAccountType.REVENUE, + 'income-statement.1' +); + +/** + * The accounts of the books, by number, one of them closed and one without a position. + */ +export const ACCOUNTS: BookkeepingAccountModel[] = [ + BANK, + createAccount(ACCOUNT_IDS.transit, '1360', 'Money in transit', BookkeepingAccountType.ASSET, null), + RECEIVABLES, + OUTPUT_TAX, + createAccount( + ACCOUNT_IDS.reserveAllocation, + '2496', + 'Allocation to the legal reserve', + BookkeepingAccountType.EQUITY, + 'equity-and-liabilities.A.V' + ), + CAPITAL, + createAccount(ACCOUNT_IDS.reserve, '2930', 'Legal reserve', BookkeepingAccountType.EQUITY, 'equity-and-liabilities.A.III.1'), + CARRIED_FORWARD, + RENT, + { + ...createAccount(ACCOUNT_IDS.oldRent, '4211', 'Rent of the old office', BookkeepingAccountType.EXPENSE, 'income-statement.8'), + closedAt: new Date('2025-12-31T12:00:00.000Z') + }, + REVENUE +]; + +/** + * The closed fiscal year 2025, the first of the books. + */ +export const FISCAL_YEAR_2025: FiscalYearModel = { + id: FISCAL_YEAR_IDS.year2025, + tenantId: TENANT_ID, + start: day('2025-01-01'), + end: day(END_2025), + closedAt: new Date('2026-02-15T10:00:00.000Z'), + conformances: null, + averageEmployees: 1, + balanceSheetNote: 'Haftungsverhältnisse nach § 268 Abs. 7 HGB bestehen nicht.', + founded: true, + previousSizeClass: null, + lastSequence: 3, + reopenings: 0 +}; + +/** + * The open fiscal year 2026. + */ +export const FISCAL_YEAR_2026: FiscalYearModel = { + id: FISCAL_YEAR_IDS.year2026, + tenantId: TENANT_ID, + start: day(START_2026), + end: day(END_2026), + closedAt: null, + conformances: null, + averageEmployees: null, + balanceSheetNote: null, + founded: null, + previousSizeClass: null, + lastSequence: 4, + reopenings: 0 +}; + +/** + * The fiscal years, the earliest first, as the api answers them. + */ +export const FISCAL_YEARS: FiscalYearModel[] = [FISCAL_YEAR_2025, FISCAL_YEAR_2026]; + +/** + * What a line of an entry of the fixtures books. + */ +type LineData = [accountId: string, side: 'debit' | 'credit', amount: string]; + +let lineCount: number = 0; + +/** + * Creates a line of an entry of 2026, the next of the chain of the lines. + * @param entryId - The id of the entry. + * @param line - The account, the side and the amount of the line. + * @returns The line. + */ +function createLine(entryId: string, [accountId, side, amount]: LineData): JournalEntryLineModel { + lineCount++; + return { + id: `line-${lineCount}`, + tenantId: TENANT_ID, + chainSequence: 100 + lineCount, + chainHash: `hash-line-${lineCount}`, + retainUntil: RETAIN_UNTIL, + archivedFiles: [], + entryId, + fiscalYearId: FISCAL_YEAR_IDS.year2026, + accountId, + debit: side === 'debit' ? amount : null, + credit: side === 'credit' ? amount : null + }; +} + +/** + * Creates an entry of 2026 posted by hand, with its lines. + * @param id - Its id. + * @param sequence - Its number in the fiscal year. + * @param postingDate - The day it is booked on, which is the day of its document as well, like '2026-03-01'. + * @param text - What it books. + * @param lines - Its lines. + * @param entry - What it has beside, like the entry it reverses. + * @returns The entry with its lines. + */ +function createEntry( + id: string, + sequence: number, + postingDate: string, + text: string, + lines: LineData[], + entry: Partial = {} +): JournalEntryDetailsModel { + return { + entry: { + id, + tenantId: TENANT_ID, + chainSequence: 40 + sequence, + chainHash: `hash-${id}`, + retainUntil: RETAIN_UNTIL, + archivedFiles: [], + fiscalYearId: FISCAL_YEAR_IDS.year2026, + sequence, + documentDate: day(postingDate), + postingDate: day(postingDate), + documentReference: null, + text, + createdBy: 'user-1', + reversesEntryId: null, + sourceType: null, + sourceId: null, + postedAt: new Date(`${postingDate}T09:30:00.000Z`), + ...entry + }, + lines: lines.map(line => createLine(id, line)), + reversedByEntryId: null + }; +} + +/** + * The entries of 2026: the opening balances, the rent of March, its reversal and an invoice. + */ +export const ENTRIES: JournalEntryDetailsModel[] = [ + createEntry(ENTRY_IDS.opening, 1, START_2026, OPENING_TEXT, [ + [ACCOUNT_IDS.bank, 'debit', '13450'], + [ACCOUNT_IDS.capital, 'credit', '12500'], + [ACCOUNT_IDS.carriedForward, 'credit', '950'] + ], { createdBy: null, sourceType: 'bookkeeping.opening', sourceId: FISCAL_YEAR_IDS.year2025 }), + { + ...createEntry(ENTRY_IDS.rent, 2, '2026-03-01', RENT_TEXT, [ + [ACCOUNT_IDS.rent, 'debit', '1200'], + [ACCOUNT_IDS.bank, 'credit', '1200'] + ], { documentReference: RENT_REFERENCE }), + reversedByEntryId: ENTRY_IDS.rentReversal + }, + createEntry(ENTRY_IDS.rentReversal, 3, '2026-03-05', REVERSAL_TEXT, [ + [ACCOUNT_IDS.bank, 'debit', '1200'], + [ACCOUNT_IDS.rent, 'credit', '1200'] + ], { documentReference: RENT_REFERENCE, reversesEntryId: ENTRY_IDS.rent }), + createEntry(ENTRY_IDS.invoice, 4, '2026-03-10', 'Invoice RE-2026-0001 to Example Ltd.', [ + [ACCOUNT_IDS.receivables, 'debit', '1190'], + [ACCOUNT_IDS.revenue, 'credit', '1000'], + [ACCOUNT_IDS.outputTax, 'credit', '190'] + ], { documentReference: 'RE-2026-0001', documentDate: day('2026-03-09'), sourceType: 'invoicing.invoice', sourceId: 'invoice-1' }) +]; + +/** + * The entries of 2026 as one page of `GET /entries`, with the sums of their lines. + */ +export const ENTRY_PAGE_2026: JournalEntryPageModel = { items: ENTRIES, totalAmount: ENTRIES.length, debit: '17040', credit: '17040' }; + +/** + * The reversal of the invoice, as the api answers reversing it. + */ +export const INVOICE_REVERSAL: JournalEntryDetailsModel = createEntry(ENTRY_IDS.invoiceReversal, 5, '2026-03-12', 'Wrong customer', [ + [ACCOUNT_IDS.receivables, 'credit', '1190'], + [ACCOUNT_IDS.revenue, 'debit', '1000'], + [ACCOUNT_IDS.outputTax, 'debit', '190'] +], { documentReference: 'RE-2026-0001', reversesEntryId: ENTRY_IDS.invoice }); + +/** + * Creates a line of the ledger of 2026. + * @param entryId - The id of its entry. + * @param sequence - The number of its entry. + * @param postingDate - The day it is booked on, which is the day of its document as well. + * @param text - What its entry books. + * @param amounts - Its document, its amount and the balance after it. + * @returns The line of the ledger. + */ +function createLedgerLine( + entryId: string, + sequence: number, + postingDate: string, + text: string, + amounts: Pick +): BookkeepingLedgerLineModel { + return { + entryId, + fiscalYearId: FISCAL_YEAR_IDS.year2026, + sequence, + postingDate: day(postingDate), + documentDate: day(postingDate), + text, + ...amounts + }; +} + +/** + * The ledger of the bank account in 2026. + */ +export const BANK_LEDGER_2026: BookkeepingLedgerReportModel = { + account: BANK, + from: day(START_2026), + until: day(END_2026), + openingBalance: '0', + lines: [ + createLedgerLine(ENTRY_IDS.opening, 1, START_2026, OPENING_TEXT, { + documentReference: null, + debit: '13450', + credit: null, + balance: '13450' + }), + createLedgerLine(ENTRY_IDS.rent, 2, '2026-03-01', RENT_TEXT, { + documentReference: RENT_REFERENCE, + debit: null, + credit: '1200', + balance: '12250' + }), + createLedgerLine(ENTRY_IDS.rentReversal, 3, '2026-03-05', REVERSAL_TEXT, { + documentReference: RENT_REFERENCE, + debit: '1200', + credit: null, + balance: '13450' + }) + ], + debit: '14650', + credit: '1200', + closingBalance: '13450' +}; + +/** + * The trial balance of 2026. + */ +export const TRIAL_BALANCE_2026: BookkeepingTrialBalanceModel = { + fiscalYearId: FISCAL_YEAR_IDS.year2026, + start: day(START_2026), + until: day(END_2026), + rows: [ + { account: BANK, debit: '14650', credit: '1200', balance: '13450' }, + { account: RECEIVABLES, debit: '1190', credit: '0', balance: '1190' }, + { account: OUTPUT_TAX, debit: '0', credit: '190', balance: '-190' }, + { account: CAPITAL, debit: '0', credit: '12500', balance: '-12500' }, + { account: CARRIED_FORWARD, debit: '0', credit: '950', balance: '-950' }, + { account: RENT, debit: '1200', credit: '1200', balance: '0' }, + { account: REVENUE, debit: '0', credit: '1000', balance: '-1000' } + ], + debit: '17040', + credit: '17040', + debitBalances: '14640', + creditBalances: '14640' +}; + +/** + * Creates a position of a statement at the top or one below it. + * @param id - Its id. + * @param parentId - The id of the position it is below, or null for one at the top. + * @param label - What it is called. + * @param amounts - Its amount and the one of the year before. + * @param accounts - The accounts it holds. + * @returns The position. + */ +function createPosition( + id: string, + parentId: string | null, + label: string, + [amount, previousAmount]: [string, string], + accounts: BookkeepingAccountAmountModel[] = [] +): BookkeepingStatementPositionModel { + return { id, parentId, depth: parentId == undefined ? 0 : 1, label, amount, previousAmount, accounts }; +} + +/** + * Gets what an account adds to a position. + * @param account - The account. + * @param amount - What it adds. + * @returns The amount of the account. + */ +function getAmount(account: BookkeepingAccountModel, amount: string): BookkeepingAccountAmountModel { + return { accountId: account.id, number: account.number, name: account.name, amount }; +} + +const ZERO: [string, string] = ['0', '0']; +const ASSETS: string = 'assets'; +const EQUITY_AND_LIABILITIES: string = 'equity-and-liabilities'; + +/** + * The balance sheet of 2026 in the shortened form of a micro corporation, with the figures of 2025. + */ +export const BALANCE_SHEET_2026: BookkeepingStatementModel = { + fiscalYearId: FISCAL_YEAR_IDS.year2026, + start: day(START_2026), + end: day(END_2026), + previousFiscalYearId: FISCAL_YEAR_IDS.year2025, + previousEnd: day(END_2025), + closed: false, + type: BookkeepingStatementType.BALANCE_SHEET, + form: 'hgb.balance-sheet.micro', + label: 'Balance sheet', + positions: [ + createPosition(ASSETS, null, 'Assets', ['14640', '13450']), + createPosition(`${ASSETS}.A`, ASSETS, 'Fixed assets', ZERO), + createPosition( + `${ASSETS}.B`, + ASSETS, + 'Current assets', + ['14640', '13450'], + [getAmount(RECEIVABLES, '1190'), getAmount(BANK, '13450')] + ), + createPosition(`${ASSETS}.C`, ASSETS, 'Prepaid expenses', ZERO), + createPosition(`${ASSETS}.D`, ASSETS, 'Deferred tax assets', ZERO), + createPosition(`${ASSETS}.E`, ASSETS, 'Excess of plan assets over pension liabilities', ZERO), + createPosition(EQUITY_AND_LIABILITIES, null, 'Equity and liabilities', ['14640', '13450']), + createPosition( + `${EQUITY_AND_LIABILITIES}.A`, + EQUITY_AND_LIABILITIES, + 'Equity', + ['14450', '13450'], + [getAmount(CAPITAL, '12500'), getAmount(CARRIED_FORWARD, '950')] + ), + createPosition(`${EQUITY_AND_LIABILITIES}.B`, EQUITY_AND_LIABILITIES, 'Provisions', ZERO), + createPosition(`${EQUITY_AND_LIABILITIES}.C`, EQUITY_AND_LIABILITIES, 'Liabilities', ['190', '0'], [getAmount(OUTPUT_TAX, '190')]), + createPosition(`${EQUITY_AND_LIABILITIES}.D`, EQUITY_AND_LIABILITIES, 'Deferred income', ZERO), + createPosition(`${EQUITY_AND_LIABILITIES}.E`, EQUITY_AND_LIABILITIES, 'Deferred tax liabilities', ZERO) + ], + unmapped: [], + result: '1000' +}; + +/** + * The balance sheet of 2026 with a balance on the money in transit, an account without a position. + */ +export const BALANCE_SHEET_WITH_UNMAPPED: BookkeepingStatementModel = { + ...BALANCE_SHEET_2026, + unmapped: [{ accountId: ACCOUNT_IDS.transit, number: '1360', name: 'Money in transit', amount: '120' }] +}; + +/** + * The income statement of 2026 in the shortened form of a micro corporation, with the figures of 2025. + */ +export const INCOME_STATEMENT_2026: BookkeepingStatementModel = { + fiscalYearId: FISCAL_YEAR_IDS.year2026, + start: day(START_2026), + end: day(END_2026), + previousFiscalYearId: FISCAL_YEAR_IDS.year2025, + previousEnd: day(END_2025), + closed: false, + type: BookkeepingStatementType.INCOME_STATEMENT, + form: 'hgb.income-statement.micro', + label: 'Income statement', + positions: [ + createPosition('micro-income-statement.1', null, 'Revenue', ['1000', '2000'], [getAmount(REVENUE, '1000')]), + createPosition('micro-income-statement.2', null, 'Other income', ZERO), + createPosition('micro-income-statement.3', null, 'Cost of materials', ZERO), + createPosition('micro-income-statement.4', null, 'Personnel expenses', ZERO), + createPosition('micro-income-statement.5', null, 'Depreciation and amortization', ZERO), + createPosition('micro-income-statement.6', null, 'Other expenses', ['0', '-1050'], [getAmount(RENT, '0')]), + createPosition('micro-income-statement.7', null, 'Taxes', ZERO), + createPosition('micro-income-statement.8', null, 'Net income or net loss for the year', ['1000', '950']) + ], + unmapped: [], + result: '1000' +}; + +/** + * The forms the statements of 2026 can be shown in, with the shortened ones of a micro corporation applying. + */ +export const STATEMENT_FORMS_2026: BookkeepingStatementFormChoicesModel = { + fiscalYearId: FISCAL_YEAR_IDS.year2026, + balanceSheet: { + applies: 'hgb.balance-sheet.micro', + forms: [ + { id: 'hgb.balance-sheet', name: 'Balance sheet (§ 266 HGB)' }, + { id: 'hgb.balance-sheet.small', name: 'Shortened balance sheet of a small corporation (§ 266 (1) sentence 3 HGB)' }, + { id: 'hgb.balance-sheet.micro', name: 'Shortened balance sheet of a micro corporation (§ 266 (1) sentence 4 HGB)' } + ] + }, + incomeStatement: { + applies: 'hgb.income-statement.micro', + forms: [ + { id: 'hgb.income-statement', name: 'Income statement by the nature of expense method (§ 275 (2) HGB)' }, + { id: 'hgb.income-statement.micro', name: 'Shortened income statement of a micro corporation (§ 275 (5) HGB)' } + ] + } +}; + +/** + * The entry the legal reserve of a UG proposes before 2026 is closed: a quarter of its net income. + */ +export const LEGAL_RESERVE_PROPOSAL: BookkeepingClosingProposalModel = { + conformance: 'ug-legal-reserve', + entry: { + documentDate: day(END_2026), + postingDate: day(END_2026), + documentReference: null, + text: 'Allocation to the legal reserve § 5a (3) GmbHG', + lines: [{ accountId: ACCOUNT_IDS.reserveAllocation, debit: '250' }, { accountId: ACCOUNT_IDS.reserve, credit: '250' }] + } +}; + +/** + * What the api sends: json, whose dates are strings. + * @param value - A model of the fixtures. + * @returns The value as json parses it. + */ +export function toJson(value: unknown): object { + return JSON.parse(JSON.stringify(value)) as object; +} diff --git a/projects/ngx-bookkeeping/fixtures/e-bilanz.fixtures.ts b/projects/ngx-bookkeeping/fixtures/e-bilanz.fixtures.ts new file mode 100644 index 0000000..79c6de4 --- /dev/null +++ b/projects/ngx-bookkeeping/fixtures/e-bilanz.fixtures.ts @@ -0,0 +1,290 @@ +/* eslint-disable unicorn/no-null -- the api answers null for NIL and for every value a record doesn't have, which the fixtures mirror */ +import { BookkeepingAccountModel, BookkeepingAccountType, BookkeepingTrialBalanceModel, EBilanzAccountingStandard, EBilanzAccountModel, EBilanzContentModel, EBilanzRevisionStatus, EBilanzExporterModel, EBilanzFindingModel, EBilanzFixedAssetModel, EBilanzPositionModel, GermanBookkeepingCompanyModel } from 'zibri-contract'; + +import { ACCOUNT_IDS, ACCOUNTS, FISCAL_YEAR_IDS, SETTINGS } from './bookkeeping.fixtures'; + +// The E-Bilanz of the closed fiscal year 2025 of the books of the fixtures, as the E-Bilanz routes of zibri answer it: +// office equipment bought for 2,000 and depreciated by 200, the bank, money in transit of 250, the share capital and +// the result of 950, which revenue of 3,000, the rent of the old office and the depreciation make. Money in transit has +// no position of its own until it is mapped, so the balance sheet doesn't balance, and the statement of changes in +// fixed assets needs the depreciation of the year, which the books don't hold as a figure of it. The positions, columns +// and labels are those of the HGB taxonomy 6.9, shortened to what these books state. + +/** + * The url the specs and stories have the E-Bilanz at. + */ +export const E_BILANZ_BASE_URL: string = '/api/e-bilanz'; + +/** + * The element name of the position of the office equipment, the one row of the fixed assets with accounts. + */ +export const OFFICE_EQUIPMENT_POSITION: string = 'bs.ass.fixAss.tan.otherEquipm.office'; + +/** + * The column of the depreciation of the year, the figure the statement of changes in fixed assets needs. + */ +export const DEPRECIATION_COLUMN: string = 'accDepr.DeprPeriod.regular'; + +/** + * The position money in transit is mapped to. + */ +export const TRANSIT_POSITION: string = 'bs.ass.currAss.cashEquiv.misc'; + +/** + * The exporter of the XBRL instance document. + */ +export const XBRL_EXPORTER: EBilanzExporterModel = { name: 'xbrl', mimeType: 'application/xml', fileExtension: 'xbrl' }; + +/** + * The company of the books as the German company model holds it. + */ +export const GERMAN_COMPANY: GermanBookkeepingCompanyModel = { + name: SETTINGS.company?.name ?? '', + seat: 'Berlin', + registerCourt: 'Amtsgericht Charlottenburg', + registerNumber: 'HRB 123456 B', + legalStatus: 'UG', + taxNumber: '1121081508150', + taxOfficeNumber: '1121', + address: { street: 'Hauptstraße', houseNumber: '1', postalCode: '10115', city: 'Berlin', country: 'DE' }, + business: 'Software development', + taxAdvisor: false +}; + +/** + * The deadline of the E-Bilanz 2025 of a company without a tax advisor, 31 July 2026, § 149 (2) AO. + */ +export const DEADLINE_2025: string = '2026-07-31T00:00:00.000Z'; + +const OFFICE_EQUIPMENT: BookkeepingAccountModel = { + id: 'b6181a2b-1c5f-47da-88b9-04d637c92540', + tenantId: SETTINGS.tenantId, + number: '0420', + name: 'Office equipment', + type: BookkeepingAccountType.ASSET, + statementPosition: 'assets.A.II.3', + creditStatementPosition: null, + closedAt: null +}; +const DEPRECIATION: BookkeepingAccountModel = { + id: 'c7292b3c-2d60-48eb-99ca-15e748da3651', + tenantId: SETTINGS.tenantId, + number: '4830', + name: 'Depreciation', + type: BookkeepingAccountType.EXPENSE, + statementPosition: 'income-statement.7.a', + creditStatementPosition: null, + closedAt: null +}; + +/** + * Finds an account of the fixtures. + * @param id - Its id. + * @returns The account. + */ +function getAccount(id: string): BookkeepingAccountModel { + const account: BookkeepingAccountModel | undefined = [...ACCOUNTS, OFFICE_EQUIPMENT, DEPRECIATION].find(candidate => candidate.id === id); + if (account == undefined) { + throw new Error(`The fixtures have no account ${id}.`); + } + return account; +} + +/** + * The trial balance of 2025 without its closing entry, whose balances the E-Bilanz states. + */ +export const TRIAL_BALANCE_2025: BookkeepingTrialBalanceModel = { + fiscalYearId: FISCAL_YEAR_IDS.year2025, + start: new Date('2025-01-01T00:00:00.000Z'), + until: new Date('2025-12-31T00:00:00.000Z'), + rows: [ + { account: OFFICE_EQUIPMENT, debit: '2000', credit: '200', balance: '1800' }, + { account: getAccount(ACCOUNT_IDS.bank), debit: '15500', credit: '4100', balance: '11400' }, + { account: getAccount(ACCOUNT_IDS.transit), debit: '250', credit: '0', balance: '250' }, + { account: getAccount(ACCOUNT_IDS.capital), debit: '0', credit: '12500', balance: '-12500' }, + { account: getAccount(ACCOUNT_IDS.oldRent), debit: '1850', credit: '0', balance: '1850' }, + { account: DEPRECIATION, debit: '200', credit: '0', balance: '200' }, + { account: getAccount(ACCOUNT_IDS.revenue), debit: '0', credit: '3000', balance: '-3000' } + ], + debit: '19800', + credit: '19800', + debitBalances: '15500', + creditBalances: '15500' +}; + +/** + * Creates an account of a position, as its account level detail states it. + * @param account - The account. + * @param balance - Its balance, positive on the side the position counts. + * @returns The account of the position. + */ +function createAccount(account: BookkeepingAccountModel, balance: string): EBilanzAccountModel { + return { accountId: account.id, number: account.number, name: account.name, balance }; +} + +/** + * Creates a position. + * @param name - Its element name. + * @param parent - The position it is below, or null at the top. + * @param label - Its German label. + * @param amount - Its amount, or null for NIL. + * @param accounts - The accounts it is made of. + * @returns The position. + */ +function createPosition( + name: string, + parent: string | null, + label: string, + amount: string | null, + accounts: EBilanzAccountModel[] = [] +): EBilanzPositionModel { + const statement: string = name.startsWith('bs.') ? 'balanceSheet' : 'incomeStatement'; + return { name, statement, parent, label, requirement: amount == undefined ? 'M' : 'S', amount, accounts }; +} + +/** + * Creates a row of the statement of changes in fixed assets, with the columns of the fixtures. + * @param position - The element name of its position. + * @param parent - The row it is summed into, or null for the fixed assets. + * @param label - The German label of its position. + * @param depreciation - The depreciation of the year, or null while no figure names it. + * @returns The row. + */ +function createFixedAsset(position: string, parent: string | null, label: string, depreciation: string | null): EBilanzFixedAssetModel { + const accumulated: string = depreciation ?? '0'; + return { + position, + label, + parent, + values: [ + { column: 'grossCost.beginning', label: 'Anschaffungs- und Herstellungskosten zum Anfang der Periode', amount: '0' }, + { column: 'gross.addition', label: 'Anschaffungs- und Herstellungskosten, Zugänge', amount: '2000' }, + { column: 'gross.release', label: 'Anschaffungs- und Herstellungskosten, Abgänge', amount: null }, + { column: 'gross', label: 'Anschaffungs- und Herstellungskosten zum Ende der Periode', amount: '2000' }, + { column: 'accDepr.beginning', label: 'Kumulierte Abschreibungen zum Anfang der Periode', amount: '0' }, + { + column: DEPRECIATION_COLUMN, + label: 'Abschreibungen, Sonderabschreibungen und sonstige Abzüge der Periode, planmäßige Abschreibung', + amount: depreciation + }, + { column: 'accDepr', label: 'Kumulierte Abschreibungen zum Ende der Periode', amount: accumulated }, + { column: 'revaluation', label: 'Zuschreibungen', amount: null }, + { column: 'all', label: 'Buchwert zum Ende der Periode', amount: String(2000 - Number(accumulated)) } + ] + }; +} + +/** + * Resolves the E-Bilanz 2025 as the books state it. + * @param accountingStandard - Which balance sheet it states. + * @param transitMapped - Whether money in transit is mapped to a position of its own. + * @param depreciation - The depreciation of the year the figures name, or undefined for none. + * @param revisionStatus - How it corrects the E-Bilanz filed before, `original` for the first, which the GCD module + * states. + * @returns The content. + */ +export function resolveEBilanzContent( + accountingStandard: EBilanzAccountingStandard, + transitMapped: boolean, + depreciation: string | undefined, + revisionStatus: EBilanzRevisionStatus = EBilanzRevisionStatus.ORIGINAL +): EBilanzContentModel { + const transit: EBilanzAccountModel = createAccount(getAccount(ACCOUNT_IDS.transit), '250'); + const cash: string = transitMapped ? '11650' : '11400'; + const assets: string = transitMapped ? '13450' : '13200'; + return { + fiscalYearId: FISCAL_YEAR_IDS.year2025, + start: '2025-01-01T00:00:00.000Z', + end: '2025-12-31T00:00:00.000Z', + taxonomyVersion: '6.9', + accountingStandard, + incomeStatementForm: 'total-cost', + company: GERMAN_COMPANY, + positions: [ + createPosition('bs.ass', null, 'Bilanzsumme, Summe Aktiva', assets), + createPosition('bs.ass.fixAss', 'bs.ass', 'Anlagevermögen', '1800'), + createPosition('bs.ass.fixAss.intan', 'bs.ass.fixAss', 'Immaterielle Vermögensgegenstände', null), + createPosition('bs.ass.fixAss.tan', 'bs.ass.fixAss', 'Sachanlagen', '1800'), + createPosition('bs.ass.fixAss.tan.otherEquipm', 'bs.ass.fixAss.tan', 'andere Anlagen, Betriebs- und Geschäftsausstattung', '1800'), + createPosition(OFFICE_EQUIPMENT_POSITION, 'bs.ass.fixAss.tan.otherEquipm', 'Büroeinrichtung', '1800', [ + createAccount(OFFICE_EQUIPMENT, '1800') + ]), + createPosition('bs.ass.currAss', 'bs.ass', 'Umlaufvermögen', cash), + createPosition('bs.ass.currAss.receiv', 'bs.ass.currAss', 'Forderungen und sonstige Vermögensgegenstände', null), + createPosition('bs.ass.currAss.cashEquiv', 'bs.ass.currAss', 'Kassenbestand, Bundesbankguthaben, Guthaben bei Kreditinstituten und Schecks', cash), + createPosition('bs.ass.currAss.cashEquiv.bank', 'bs.ass.currAss.cashEquiv', 'Guthaben bei Kreditinstituten', '11400', [ + createAccount(getAccount(ACCOUNT_IDS.bank), '11400') + ]), + ...transitMapped + ? [createPosition(TRANSIT_POSITION, 'bs.ass.currAss.cashEquiv', 'übrige / nicht zuordenbare Zahlungsmittel', '250', [transit])] + : [], + createPosition('bs.eqLiab', null, 'Bilanzsumme, Summe Passiva', '13450'), + createPosition('bs.eqLiab.equity', 'bs.eqLiab', 'Eigenkapital', '13450'), + createPosition('bs.eqLiab.equity.subscribed', 'bs.eqLiab.equity', 'Gezeichnetes Kapital', '12500', [ + createAccount(getAccount(ACCOUNT_IDS.capital), '12500') + ]), + createPosition('bs.eqLiab.equity.netIncome', 'bs.eqLiab.equity', 'Jahresüberschuss/-fehlbetrag', '950', [ + createAccount(getAccount(ACCOUNT_IDS.carriedForward), '950') + ]), + createPosition('bs.eqLiab.liab', 'bs.eqLiab', 'Verbindlichkeiten', null), + createPosition('is.netIncome', null, 'Jahresüberschuss/Jahresfehlbetrag', '950'), + createPosition('is.netIncome.regular.operatingTC.grossTradingProfit.totalOutput.netSales', 'is.netIncome', 'Umsatzerlöse', '3000', [ + createAccount(getAccount(ACCOUNT_IDS.revenue), '3000') + ]), + createPosition('is.netIncome.regular.operatingTC.deprAmort.fixAss.tan', 'is.netIncome', 'Abschreibungen auf Sachanlagen', '200', [ + createAccount(DEPRECIATION, '200') + ]), + createPosition('is.netIncome.regular.operatingTC.otherCost.fixingLandBuildings', 'is.netIncome', 'Raumkosten', '1850', [ + createAccount(getAccount(ACCOUNT_IDS.oldRent), '1850') + ]) + ], + fixedAssets: [ + createFixedAsset('bs.ass.fixAss', null, 'Anlagevermögen', depreciation ?? null), + createFixedAsset('bs.ass.fixAss.tan', 'bs.ass.fixAss', 'Sachanlagen', depreciation ?? null), + createFixedAsset('bs.ass.fixAss.tan.otherEquipm', 'bs.ass.fixAss.tan', 'andere Anlagen, Betriebs- und Geschäftsausstattung', depreciation ?? null), + createFixedAsset(OFFICE_EQUIPMENT_POSITION, 'bs.ass.fixAss.tan.otherEquipm', 'Büroeinrichtung', depreciation ?? null) + ], + fields: [ + { name: 'genInfo.company.id.name', label: 'Firmenname', value: GERMAN_COMPANY.name, occurrence: 0 }, + { name: 'genInfo.company.id.idNo.type.companyId.ST13', label: 'Steuernummer', value: GERMAN_COMPANY.taxNumber, occurrence: 0 }, + { name: 'genInfo.report.id.revisionStatus', label: 'Status der Berichtigung', value: revisionStatus, occurrence: 0 } + ] + }; +} + +/** + * Resolves what the E-Bilanz 2025 needs, in the words of the api. + * @param transitMapped - Whether money in transit is mapped to a position of its own. + * @param depreciation - The depreciation of the year the figures name, or undefined for none. + * @returns The findings. + */ +export function resolveEBilanzFindings(transitMapped: boolean, depreciation: string | undefined): EBilanzFindingModel[] { + const bookValue: string = String(2000 - Number(depreciation ?? '0')); + return [ + ...transitMapped + ? [] + : [ + { + position: '1360', + message: 'The account 1360 Money in transit has a balance and needs a position of the taxonomy 6.9 of the E-Bilanz: ' + + 'a mapping of its own, or a statement position the taxonomy maps.' + }, + { position: 'bs.ass', message: 'The balance sheet needs to balance: bs.ass states 13200 and bs.eqLiab states 13450.' } + ], + ...bookValue === '1800' + ? [] + : [ + { + position: OFFICE_EQUIPMENT_POSITION, + message: `The statement of changes in fixed assets of ${OFFICE_EQUIPMENT_POSITION} states the book value ${bookValue} at the end ` + + 'of the year, all, and needs to equal the balance sheet, 1800: name the figures the books do not hold, such as the ' + + 'depreciation of the year.' + }, + { + position: 'bs.ass.fixAss', + message: `The statement of changes in fixed assets of bs.ass.fixAss states the book value ${bookValue} at the end of the year, ` + + 'all, and needs to equal the balance sheet, 1800: name the figures the books do not hold of the positions below it.' + } + ] + ]; +} diff --git a/projects/ngx-bookkeeping/fixtures/fake-e-bilanz-backend-options.model.ts b/projects/ngx-bookkeeping/fixtures/fake-e-bilanz-backend-options.model.ts new file mode 100644 index 0000000..a0b177b --- /dev/null +++ b/projects/ngx-bookkeeping/fixtures/fake-e-bilanz-backend-options.model.ts @@ -0,0 +1,44 @@ +import { EBilanzExporterModel } from 'zibri-contract'; + +/** + * How a FakeEBilanzBackend answers. + */ +export type FakeEBilanzBackendOptions = { + /** + * Whether the E-Bilanz can be sent from the app: with a transmitter and a certificate, without a transmitter, or + * with a transmitter but no certificate, until one is uploaded. 'missing' by default, as none is registered for an + * app. + */ + transmitter?: 'configured' | 'missing' | 'no-certificate', + /** + * The exporters, XBRL_EXPORTER by default. + */ + exporters?: EBilanzExporterModel[], + /** + * How far the E-Bilanz 2025 is filed: not prepared, with money in transit unmapped and no figures; prepared with + * both; that preparation sent as a test that was accepted; then sent for real, which is still being sent (and ends + * with the transmissionOutcome after transmissionDurationInMs), whose result is not known, or which was accepted; + * or accepted, and then prepared again as a correction of an error once the books changed. 'unprepared' by + * default. + */ + stage?: 'unprepared' | 'prepared' | 'tested' | 'sending' | 'unknown' | 'transmitted' | 'correcting', + /** + * What a transmission sent through the routes, and the one of the stage 'sending', ends with: accepted or refused + * by the tax administration, failed while it may have been sent, failed without sending anything, or not known, as + * the transmitter didn't answer in time. 'accepted' by default. + */ + transmissionOutcome?: 'accepted' | 'refused' | 'failed' | 'not-sent' | 'unknown', + /** + * How long a transmission takes until it has its result, in milliseconds. 3000 by default. + */ + transmissionDurationInMs?: number, + /** + * Whether the books changed since the preparations of the stage, which are then no longer current. False by + * default. + */ + booksChanged?: boolean, + /** + * Whether the fiscal year 2026 after it is closed as well, so 2025 is only reopened after it. False by default. + */ + laterYearClosed?: boolean +}; diff --git a/projects/ngx-bookkeeping/fixtures/fake-e-bilanz-backend.model.ts b/projects/ngx-bookkeeping/fixtures/fake-e-bilanz-backend.model.ts new file mode 100644 index 0000000..1f913cf --- /dev/null +++ b/projects/ngx-bookkeeping/fixtures/fake-e-bilanz-backend.model.ts @@ -0,0 +1,767 @@ +/* eslint-disable unicorn/no-null -- the api answers null for every value a record doesn't have, which the fake mirrors */ +import { HttpBackend, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http'; +import { Provider } from '@angular/core'; +import { of, throwError } from 'rxjs'; +import { FakeAnswer } from 'testing/http'; +import { + EBilanzAccountingStandard, + EBilanzAccountMappingModel, + EBilanzCertificateSettingsModel, + EBilanzExporterModel, + EBilanzFilingKind, + EBilanzFilingModel, + EBilanzFixedAssetInputModel, + EBilanzPreparationInputModel, + EBilanzPreviewModel, + EBilanzRevisionStatus, + EBilanzStateModel, + EBilanzTransmissionModel, + EBilanzTransmissionStatus, + ErrorResponseBody, + FiscalYearModel, + FiscalYearReopeningResultModel +} from 'zibri-contract'; + +import { ACCOUNT_IDS, ACCOUNTS, BOOKKEEPING_BASE_URL, FISCAL_YEAR_IDS, FISCAL_YEARS, SETTINGS, TENANT_ID, toJson } from './bookkeeping.fixtures'; +import { DEADLINE_2025, DEPRECIATION_COLUMN, E_BILANZ_BASE_URL, OFFICE_EQUIPMENT_POSITION, resolveEBilanzContent, resolveEBilanzFindings, TRANSIT_POSITION, TRIAL_BALANCE_2025, XBRL_EXPORTER } from './e-bilanz.fixtures'; +import { FakeEBilanzBackendOptions } from './fake-e-bilanz-backend-options.model'; + +/** + * What the fake answers: an answer of HttpTestingUtilities, with the headers of a file. + */ +type FakeFileAnswer = FakeAnswer & { + /** + * The headers, like the content disposition naming a file. + */ + headers?: Record +}; + +/** + * What a transmission of the fake ends with. + */ +type FakeTransmissionOutcome = NonNullable; + +const USER_ID: string = 'd8a03c4d-3e71-49fc-8adb-26f859eb4762'; +const NO_TRANSMITTER: string = 'No transmitter is registered: provide an EBilanzTransmitterInterface with E_BILANZ_TRANSMITTER_DI_VARIANT, ' + + 'or file an export by hand and record it.'; +const NO_CERTIFICATE: string = 'The ELSTER certificate of the company and its PIN need to be uploaded.'; +const RUNNING: string = 'The E-Bilanz of the fiscal year is being sent, or filed by hand, right now.'; +const NOT_KNOWN: string = 'A transmission of the E-Bilanz may have reached the tax administration, and its result is not known. Check it in ' + + 'ELSTER, then record the E-Bilanz as filed by hand, or confirm that the transmission did not arrive, before it is sent again.'; +const TIMEOUT: string = 'The transmitter did not answer in time. The E-Bilanz may have reached the tax administration: check it in ELSTER.'; +const REASON_MAX_LENGTH: number = 500; + +/** + * The E-Bilanz routes of an api for the specs and stories, which keeps the records, the account mappings and the + * certificate in memory and answers like the routes in the README of this library, for the E-Bilanz 2025 of the + * fixtures: it states money in transit once it is mapped, and the statement of changes in fixed assets once its figures + * name the depreciation of the year. A preparation, an export and a transmission are refused with 409 like by the api: + * while the E-Bilanz needs something, without a transmitter or a certificate, once the content prepared is filed, for + * real until a test of the same content was accepted, while a transmission runs, and while one of the same kind has a + * result that is not known. A preparation of a filed E-Bilanz needs its revisionStatus, which one not filed is refused + * with. + * + * A transmission is answered with 202 and the record it started with, and has its result after the duration of the + * options, in the `transmissions` of the state. It also answers the bookkeeping routes of the fixtures the E-Bilanz and + * the fiscal years read, reopening a fiscal year with the refusals of the api, and the protocols at their url, + * `//files/protocol`. + * + * Provide it as the backend of the HttpClient with provide, after provideHttpClient. + */ +export class FakeEBilanzBackend { + /** + * Every request to the E-Bilanz routes it answered, and to reopen a fiscal year, in order, to check what was sent. + */ + readonly requests: HttpRequest[] = []; + + private readonly baseUrl: string = new URL(E_BILANZ_BASE_URL, document.baseURI).pathname; + + private readonly booksUrl: string = new URL(BOOKKEEPING_BASE_URL, document.baseURI).pathname; + + private readonly exporters: EBilanzExporterModel[]; + + private readonly transmissionOutcome: FakeTransmissionOutcome; + + private readonly transmissionDurationInMs: number; + + private transmitter: 'configured' | 'missing' | 'no-certificate'; + + private certificateUploadedAt: string | null; + + private mappings: EBilanzAccountMappingModel[] = []; + + private readonly filings: EBilanzFilingModel[] = []; + + private fiscalYears: FiscalYearModel[]; + + // the preparations of the stage the books changed since + private readonly stalePreparationIds: Set = new Set(); + + private nextId: number = 1; + + constructor(options: FakeEBilanzBackendOptions = {}) { + this.transmitter = options.transmitter ?? 'missing'; + this.exporters = options.exporters ?? [XBRL_EXPORTER]; + this.transmissionOutcome = options.transmissionOutcome ?? 'accepted'; + this.transmissionDurationInMs = options.transmissionDurationInMs ?? 3000; + this.certificateUploadedAt = this.transmitter === 'configured' ? '2026-02-20T08:00:00.000Z' : null; + this.fiscalYears = FISCAL_YEARS.map(fiscalYear => options.laterYearClosed === true && fiscalYear.id === FISCAL_YEAR_IDS.year2026 + ? { ...fiscalYear, closedAt: new Date('2027-02-15T10:00:00.000Z') } + : fiscalYear); + this.startAt(options.stage ?? 'unprepared', options.booksChanged ?? false); + } + + /** + * Gets the records of the E-Bilanz 2025 it has now. + * @returns The records, the earliest first. + */ + getFilings(): EBilanzFilingModel[] { + return [...this.filings]; + } + + /** + * Gets the fiscal years it has now, which a reopening changes. + * @returns The fiscal years, the earliest first. + */ + getFiscalYears(): FiscalYearModel[] { + return [...this.fiscalYears]; + } + + /** + * Answers a request to the E-Bilanz routes, or to the bookkeeping routes the E-Bilanz and the fiscal years read, and + * changes what it keeps like the api would. + * @param request - The request. + * @returns The answer, or undefined for a request to another url. + */ + findAnswer(request: HttpRequest): FakeFileAnswer | undefined { + const path: string = new URL(request.url, document.baseURI).pathname; + if (path.startsWith(`${this.booksUrl}/`)) { + return this.findBookAnswer(request, path.slice(this.booksUrl.length + 1)); + } + if (!path.startsWith(`${this.baseUrl}/`)) { + return undefined; + } + this.requests.push(request); + const segments: string[] = path.slice(this.baseUrl.length + 1).split('/').map(segment => decodeURIComponent(segment)); + if (segments[1] === 'files' && segments[2] === 'protocol') { + return request.method === 'GET' ? this.answerProtocol(segments[0] ?? '') : this.refuseRoute(request, path); + } + const route: string = `${request.method} ${segments[0] ?? ''}`; + switch (route) { + case 'GET fiscal-years': + case 'POST fiscal-years': { + return this.answerFiscalYear(request, segments[1] ?? '', segments[2]); + } + case 'GET settings': { + return this.answerJson(this.getSettings()); + } + case 'PUT settings': { + return segments[1] === 'certificate' ? this.updateCertificate(request.body) : this.refuseRoute(request, path); + } + case 'GET account-mappings': { + return this.answerJson(this.mappings); + } + case 'PUT account-mappings': { + return this.updateMapping(segments[1] ?? '', request.body); + } + case 'DELETE account-mappings': { + this.mappings = this.mappings.filter(mapping => mapping.accountId !== segments[1]); + return { status: 204 }; + } + default: { + return this.refuseRoute(request, path); + } + } + } + + /** + * Provides it as the backend of the HttpClient, which answers right away. A request to another url fails with 404. + * @returns The provider, after provideHttpClient. + */ + provide(): Provider { + return { provide: HttpBackend, useValue: this.createBackend() }; + } + + /** + * Creates the backend of the HttpClient that answers with it, right away. A request to another url fails with 404. + * @returns The backend. + */ + createBackend(): HttpBackend { + // the backend, not an interceptor, like HttpTestingUtilities.provideBackend, with the headers of a file + return { + handle: request => { + const answer: FakeFileAnswer = this.findAnswer(request) ?? { status: 404 }; + return answer.status < 400 + ? of(new HttpResponse({ status: answer.status, body: answer.body ?? null, headers: new HttpHeaders(answer.headers), url: request.url })) + : throwError(() => new HttpErrorResponse({ status: answer.status, error: answer.body, url: request.url })); + } + }; + } + + private findBookAnswer(request: HttpRequest, path: string): FakeAnswer | undefined { + const segments: string[] = path.split('/'); + if (request.method === 'POST' && segments[0] === 'fiscal-years' && segments[2] === 'reopening') { + this.requests.push(request); + return this.reopen(segments[1] ?? '', request.body); + } + const answers: Record = { + 'GET settings': SETTINGS, + 'GET fiscal-years': this.fiscalYears, + 'GET accounts': ACCOUNTS, + 'GET reports/trial-balance': TRIAL_BALANCE_2025, + ...Object.fromEntries(this.fiscalYears.map(fiscalYear => [`GET fiscal-years/${fiscalYear.id}/closing-proposals`, []])) + }; + const answer: unknown = answers[`${request.method} ${path}`]; + return answer == undefined ? undefined : { status: 200, body: toJson(answer) }; + } + + private answerFiscalYear(request: HttpRequest, fiscalYearId: string, action: string | undefined): FakeFileAnswer { + if (!this.fiscalYears.some(fiscalYear => fiscalYear.id === fiscalYearId)) { + return FakeEBilanzBackend.refuse(404, 'NotFoundError', `There is no fiscal year ${fiscalYearId}.`); + } + switch (`${request.method} ${action ?? ''}`) { + case 'GET ': { + return this.answerJson(this.resolveState(fiscalYearId)); + } + case 'POST preview': { + return this.answerPreview(fiscalYearId, request.body); + } + case 'POST preparation': { + return this.prepare(fiscalYearId, request.body); + } + case 'GET export': { + return this.answerExport(fiscalYearId, request.params.get('exporter')); + } + case 'POST test-transmission': { + return this.transmit(fiscalYearId, true); + } + case 'POST transmission': { + return this.transmit(fiscalYearId, false); + } + case 'POST transmission-not-received': { + return this.recordNotReceived(fiscalYearId); + } + case 'POST manual-filing': { + return this.recordManualFiling(fiscalYearId, request.body); + } + default: { + return this.refuseRoute(request, request.url); + } + } + } + + private resolveState(fiscalYearId: string): EBilanzStateModel { + const filings: EBilanzFilingModel[] = this.findFilings(fiscalYearId); + const preparation: EBilanzFilingModel | undefined = this.findPreparation(fiscalYearId); + const current: EBilanzPreviewModel | undefined = preparation?.input == undefined ? undefined : this.resolvePreview(preparation.input); + return { + fiscalYearId, + deadline: fiscalYearId === FISCAL_YEAR_IDS.year2025 ? DEADLINE_2025 : '2027-07-31T00:00:00.000Z', + content: preparation?.content ?? null, + findings: current?.findings ?? [], + filings, + transmissions: FakeEBilanzBackend.resolveTransmissions(filings), + preparationId: preparation?.id ?? null, + preparationCurrent: preparation != undefined && this.isCurrent(preparation), + filed: filings.some(filing => FakeEBilanzBackend.isFiling(filing)), + transmitterConfigured: this.transmitter === 'configured', + transmitterUnavailableReason: this.transmitter === 'missing' ? NO_TRANSMITTER : this.transmitter === 'no-certificate' ? NO_CERTIFICATE : null, + exporters: this.exporters + }; + } + + private answerPreview(fiscalYearId: string, body: unknown): FakeAnswer { + const input: EBilanzPreparationInputModel | FakeAnswer = this.readInput(fiscalYearId, body); + return 'status' in input ? input : this.answerJson(this.resolvePreview(input)); + } + + // the checks of the api in its order: the revision status, then the findings + private prepare(fiscalYearId: string, body: unknown): FakeAnswer { + const input: EBilanzPreparationInputModel | FakeAnswer = this.readInput(fiscalYearId, body); + if ('status' in input) { + return input; + } + const filed: EBilanzFilingModel | undefined = this.findFilings(fiscalYearId).filter(filing => FakeEBilanzBackend.isFiling(filing)).at(-1); + const revisionStatus: EBilanzRevisionStatus = input.revisionStatus ?? EBilanzRevisionStatus.ORIGINAL; + if (filed == undefined && revisionStatus !== EBilanzRevisionStatus.ORIGINAL) { + return FakeEBilanzBackend.refuse(409, 'ConflictError', 'The E-Bilanz of the fiscal year is not filed, so it is prepared without a revisionStatus correcting one.'); + } + if (filed != undefined && revisionStatus === EBilanzRevisionStatus.ORIGINAL) { + return FakeEBilanzBackend.refuse(409, 'ConflictError', 'The E-Bilanz of the fiscal year is filed, so a preparation corrects it and needs its ' + + 'revisionStatus: corrected, changed, corrected-and-changed, more-detail or other-correction.'); + } + const preview: EBilanzPreviewModel = this.resolvePreview(input); + if (preview.findings.length) { + const needs: string = preview.findings.map(finding => finding.message).join(' '); + return FakeEBilanzBackend.refuse(409, 'ConflictError', `The E-Bilanz needs the following before it can be prepared: ${needs}`); + } + return this.answerJson(this.createFiling(fiscalYearId, EBilanzFilingKind.PREPARED, { + contentHash: FakeEBilanzBackend.resolveHash(preview), + content: preview.content, + input: { accountingStandard: input.accountingStandard, taxonomyVersion: '6.9', fixedAssets: input.fixedAssets ?? [], revisionStatus }, + correctsFilingId: filed?.id ?? null + })); + } + + private answerExport(fiscalYearId: string, exporterName: string | null): FakeFileAnswer { + const exporter: EBilanzExporterModel | undefined = this.exporters.find(candidate => candidate.name === exporterName); + if (exporter == undefined) { + const message: string = `The exporter ${exporterName ?? ''} of the E-Bilanz needs to be registered with E_BILANZ_EXPORTER_DI_VARIANT.`; + return FakeEBilanzBackend.refuse(409, 'ConflictError', message); + } + const refusal: FakeAnswer | undefined = this.findPreparationRefusal(fiscalYearId); + if (refusal != undefined) { + return refusal; + } + return { + status: 200, + body: new Blob([''], { type: exporter.mimeType }), + headers: { 'content-disposition': `attachment; filename="e-bilanz-2025-01-01-2025-12-31.${exporter.fileExtension}"` } + }; + } + + private answerProtocol(filingId: string): FakeFileAnswer { + const filing: EBilanzFilingModel | undefined = this.filings.find(candidate => candidate.id === filingId); + if (filing?.protocol == undefined) { + return FakeEBilanzBackend.refuse(404, 'NotFoundError', `The record ${filingId} has no protocol.`); + } + return { + status: 200, + body: new Blob(['%PDF-1.7'], { type: filing.protocol.mimeType }), + headers: { 'content-type': filing.protocol.mimeType, 'content-disposition': `attachment; filename="${filing.protocol.name}"` } + }; + } + + // the checks of the api in its order: the transmitter, the certificate, the preparation, the filing, a transmission + // running, one of the same kind not known, and the test + private transmit(fiscalYearId: string, test: boolean): FakeAnswer { + if (this.transmitter === 'missing') { + return FakeEBilanzBackend.refuse(409, 'ConflictError', NO_TRANSMITTER); + } + if (this.transmitter === 'no-certificate') { + return FakeEBilanzBackend.refuse(409, 'ConflictError', NO_CERTIFICATE); + } + const refusal: FakeAnswer | undefined = this.findPreparationRefusal(fiscalYearId) ?? this.findFiledRefusal(fiscalYearId) ?? this.findRunningRefusal(fiscalYearId); + if (refusal != undefined) { + return refusal; + } + const filings: EBilanzFilingModel[] = this.findFilings(fiscalYearId); + const manualFiling: number = filings.map(filing => filing.kind).lastIndexOf(EBilanzFilingKind.MANUAL_FILING); + const notKnown: boolean = FakeEBilanzBackend.resolveTransmissions(filings).some(transmission => transmission.test === test + && FakeEBilanzBackend.isNotKnown(transmission) + && filings.findIndex(filing => filing.id === transmission.id) > manualFiling); + if (notKnown) { + return FakeEBilanzBackend.refuse(409, 'ConflictError', NOT_KNOWN); + } + const preparation: EBilanzFilingModel | undefined = this.findPreparation(fiscalYearId); + const tested: boolean = filings.some(filing => { + return filing.kind === EBilanzFilingKind.TEST_TRANSMISSION && filing.succeeded && filing.contentHash === preparation?.contentHash; + }); + if (!test && !tested) { + return FakeEBilanzBackend.refuse(409, 'ConflictError', 'The E-Bilanz needs to be sent as a test and accepted before it is sent for real.'); + } + const started: EBilanzFilingModel = this.startTransmission(fiscalYearId, test); + // the api sends in the background, and answers once the start is recorded + setTimeout(() => this.recordResult(started, this.transmissionOutcome), this.transmissionDurationInMs); + return { status: 202, body: toJson(started) }; + } + + private startTransmission(fiscalYearId: string, test: boolean): EBilanzFilingModel { + const preparation: EBilanzFilingModel | undefined = this.findPreparation(fiscalYearId); + return this.createFiling(fiscalYearId, test ? EBilanzFilingKind.TEST_TRANSMISSION : EBilanzFilingKind.TRANSMISSION, { + preparationId: preparation?.id ?? null, + contentHash: preparation?.contentHash ?? '', + status: EBilanzTransmissionStatus.TRANSMITTING, + mayHaveBeenSent: true, + succeeded: false + }); + } + + // what the transmitter answered or threw, as the api records it + private recordResult(started: EBilanzFilingModel, outcome: FakeTransmissionOutcome): EBilanzFilingModel { + const test: boolean = started.kind === EBilanzFilingKind.TEST_TRANSMISSION; + // the ticket counts like the records, by the record the transmission started with + const ticket: string = `${test ? 'TT' : 'ET'}-2025-${started.id.slice(-4)}`; + switch (outcome) { + case 'accepted': { + return this.createResult(started, { status: EBilanzTransmissionStatus.ACCEPTED, succeeded: true, ticket }, test ? undefined : 'transmission-protocol-2025.pdf'); + } + case 'refused': { + return this.createResult(started, { + status: EBilanzTransmissionStatus.REFUSED, + ticket, + messages: ['Die Steuernummer 1121081508150 ist für das Finanzamt 1121 ungültig.'] + }); + } + case 'failed': { + const message: string = 'The connection to ELSTER was reset while the E-Bilanz was sent.'; + return this.createResult(started, { + status: EBilanzTransmissionStatus.FAILED, + error: { name: 'Error', message, paragraphs: [message, 'read ECONNRESET'] } + }); + } + case 'not-sent': { + const message: string = 'The ELSTER certificate could not be read: its PIN is wrong.'; + return this.createResult(started, { + status: EBilanzTransmissionStatus.FAILED, + mayHaveBeenSent: false, + error: { name: 'EBilanzNotSentError', message, paragraphs: [message] } + }); + } + case 'unknown': { + return this.createResult(started, { + status: EBilanzTransmissionStatus.UNKNOWN, + error: { name: 'EBilanzTransmissionTimeoutError', message: TIMEOUT, paragraphs: [TIMEOUT] } + }); + } + } + } + + private createResult(started: EBilanzFilingModel, values: Partial, protocol?: string): EBilanzFilingModel { + return this.createFiling(started.fiscalYearId, started.kind, { + preparationId: started.preparationId, + contentHash: started.contentHash, + transmissionId: started.id, + mayHaveBeenSent: true, + succeeded: false, + ...values + }, protocol); + } + + private recordNotReceived(fiscalYearId: string): FakeAnswer { + const running: FakeAnswer | undefined = this.findRunningRefusal(fiscalYearId); + if (running != undefined) { + return running; + } + const filings: EBilanzFilingModel[] = this.findFilings(fiscalYearId); + const notKnown: EBilanzTransmissionModel[] = FakeEBilanzBackend.resolveTransmissions(filings) + .filter(transmission => FakeEBilanzBackend.isNotKnown(transmission)); + if (!notKnown.length) { + return FakeEBilanzBackend.refuse(409, 'ConflictError', 'The fiscal year has no transmission of the E-Bilanz whose result is not known.'); + } + const records: EBilanzFilingModel[] = notKnown.flatMap(transmission => filings.find(filing => filing.id === transmission.id) ?? []) + .map(started => this.createResult(started, { status: EBilanzTransmissionStatus.NOT_RECEIVED, mayHaveBeenSent: false })); + return this.answerJson(records); + } + + private recordManualFiling(fiscalYearId: string, body: unknown): FakeAnswer { + const protocol: unknown = body instanceof FormData ? body.get('protocol') : undefined; + if (!(protocol instanceof File)) { + return FakeEBilanzBackend.refuse(400, 'ValidationError', 'protocol is required'); + } + const refusal: FakeAnswer | undefined = this.findRunningRefusal(fiscalYearId) ?? this.findPreparationRefusal(fiscalYearId) ?? this.findFiledRefusal(fiscalYearId); + if (refusal != undefined) { + return refusal; + } + const preparation: EBilanzFilingModel | undefined = this.findPreparation(fiscalYearId); + return this.answerJson(this.createFiling(fiscalYearId, EBilanzFilingKind.MANUAL_FILING, { + preparationId: preparation?.id ?? null, + contentHash: preparation?.contentHash ?? '' + }, protocol.name)); + } + + // the checks of the books first, then those of the E-Bilanz, the conformance of the fiscal year + private reopen(fiscalYearId: string, body: unknown): FakeAnswer { + const fiscalYear: FiscalYearModel | undefined = this.fiscalYears.find(candidate => candidate.id === fiscalYearId); + if (fiscalYear == undefined) { + return FakeEBilanzBackend.refuse(404, 'NotFoundError', `There is no fiscal year ${fiscalYearId}.`); + } + const reason: unknown = typeof body === 'object' && body != undefined ? Reflect.get(body, 'reason') : undefined; + const forCorrection: boolean = typeof body === 'object' && body != undefined && Reflect.get(body, 'forCorrection') === true; + if (typeof reason !== 'string' || !reason.length || reason.length > REASON_MAX_LENGTH) { + return FakeEBilanzBackend.refuse(400, 'ValidationError', `reason needs to be 1 to ${REASON_MAX_LENGTH} characters long`); + } + if (fiscalYear.closedAt == undefined) { + return FakeEBilanzBackend.refuse(409, 'ConflictError', `The fiscal year from ${FakeEBilanzBackend.formatDay(fiscalYear.start)} to ` + + `${FakeEBilanzBackend.formatDay(fiscalYear.end)} is open, and only a closed one is reopened.`); + } + const next: FiscalYearModel | undefined = this.fiscalYears.find(candidate => candidate.start.getTime() > fiscalYear.end.getTime()); + if (next?.closedAt != undefined) { + return FakeEBilanzBackend.refuse(409, 'ConflictError', `The fiscal year from ${FakeEBilanzBackend.formatDay(next.start)} to ` + + `${FakeEBilanzBackend.formatDay(next.end)} needs to be reopened before the fiscal year before it, as it opened with its closing.`); + } + const refusal: FakeAnswer | undefined = this.findReopeningRefusal(fiscalYearId, forCorrection); + if (refusal != undefined) { + return refusal; + } + const reopened: FiscalYearModel = { ...fiscalYear, closedAt: null, reopenings: fiscalYear.reopenings + 1 }; + this.fiscalYears = this.fiscalYears.map(candidate => candidate.id === fiscalYearId ? reopened : candidate); + // the reversals are left out, which the views of the fiscal years don't show + const result: FiscalYearReopeningResultModel = { fiscalYear: reopened, nextFiscalYear: next ?? null, closingReversal: null, openingReversal: null }; + return this.answerJson(result); + } + + private findReopeningRefusal(fiscalYearId: string, forCorrection: boolean): FakeAnswer | undefined { + const filings: EBilanzFilingModel[] = this.findFilings(fiscalYearId); + const running: FakeAnswer | undefined = this.findRunningRefusal(fiscalYearId); + if (running != undefined) { + return running; + } + if (FakeEBilanzBackend.resolveTransmissions(filings).some(transmission => FakeEBilanzBackend.isNotKnown(transmission))) { + return FakeEBilanzBackend.refuse(409, 'ConflictError', 'A transmission of the E-Bilanz of the fiscal year may have reached the tax ' + + 'administration, and its result is not known. Settle it before the fiscal year is reopened.'); + } + const filed: boolean = filings.some(filing => FakeEBilanzBackend.isFiling(filing)); + if (filed && !forCorrection) { + return FakeEBilanzBackend.refuse(409, 'ConflictError', 'The E-Bilanz of the fiscal year is filed, and the fiscal year is reopened only to ' + + 'correct it, with forCorrection.'); + } + if (!filed && forCorrection) { + return FakeEBilanzBackend.refuse(409, 'ConflictError', 'The E-Bilanz of the fiscal year is not filed, so there is nothing to correct: ' + + 'reopen it without forCorrection.'); + } + return undefined; + } + + private updateCertificate(body: unknown): FakeAnswer { + const certificate: unknown = body instanceof FormData ? body.get('certificate') : undefined; + const pin: unknown = body instanceof FormData ? body.get('pin') : undefined; + if (!(certificate instanceof File) || typeof pin !== 'string' || pin.length < 6 || pin.length > 128) { + return FakeEBilanzBackend.refuse(400, 'ValidationError', 'certificate is required, and pin needs to be 6 to 128 characters long'); + } + this.certificateUploadedAt = this.resolveMoment(); + if (this.transmitter === 'no-certificate') { + this.transmitter = 'configured'; + } + return this.answerJson(this.getSettings()); + } + + private updateMapping(accountId: string, body: unknown): FakeAnswer { + const position: unknown = typeof body === 'object' && body != undefined ? Reflect.get(body, 'position') : undefined; + const creditPosition: unknown = typeof body === 'object' && body != undefined ? Reflect.get(body, 'creditPosition') : undefined; + if (typeof position !== 'string' || position === '') { + return FakeEBilanzBackend.refuse(400, 'ValidationError', 'position is required'); + } + if (!ACCOUNTS.some(account => account.id === accountId)) { + return FakeEBilanzBackend.refuse(409, 'ConflictError', `The account ${accountId} needs to be an account of the books.`); + } + const existing: EBilanzAccountMappingModel | undefined = this.mappings.find(mapping => mapping.accountId === accountId); + const mapping: EBilanzAccountMappingModel = { + id: existing?.id ?? this.resolveId(), + tenantId: TENANT_ID, + accountId, + position, + creditPosition: typeof creditPosition === 'string' ? creditPosition : null + }; + this.mappings = [...this.mappings.filter(candidate => candidate.accountId !== accountId), mapping]; + return this.answerJson(mapping); + } + + private resolvePreview(input: EBilanzPreparationInputModel): EBilanzPreviewModel { + // the api states the position the mapping names, which these books have one of + const transitMapped: boolean = this.mappings.some(mapping => mapping.accountId === ACCOUNT_IDS.transit && mapping.position === TRANSIT_POSITION); + const amount: string | undefined = input.fixedAssets + ?.find(row => row.position === OFFICE_EQUIPMENT_POSITION) + ?.values.find(value => value.column === DEPRECIATION_COLUMN) + ?.amount; + // decimals without trailing zeros, as the api writes them + const depreciation: string | undefined = amount == undefined ? undefined : String(Number(amount)); + return { + content: resolveEBilanzContent(input.accountingStandard, transitMapped, depreciation, input.revisionStatus ?? EBilanzRevisionStatus.ORIGINAL), + findings: resolveEBilanzFindings(transitMapped, depreciation) + }; + } + + // the body as the api validates it: a closed fiscal year, one of the balance sheets, figures of rows and a revision + // status + private readInput(fiscalYearId: string, body: unknown): EBilanzPreparationInputModel | FakeAnswer { + const fiscalYear: FiscalYearModel | undefined = this.fiscalYears.find(candidate => candidate.id === fiscalYearId); + if (fiscalYearId !== FISCAL_YEAR_IDS.year2025 || fiscalYear?.closedAt == undefined) { + return FakeEBilanzBackend.refuse(409, 'ConflictError', 'The E-Bilanz states a closed fiscal year: close the fiscal year first.'); + } + const value: (key: string) => unknown = key => typeof body === 'object' && body != undefined ? Reflect.get(body, key) : undefined; + const accountingStandard: EBilanzAccountingStandard | undefined = Object.values(EBilanzAccountingStandard).find(standard => standard === value('accountingStandard')); + if (accountingStandard == undefined) { + return FakeEBilanzBackend.refuse(400, 'ValidationError', 'accountingStandard needs to be one of unified, tax'); + } + const revisionStatus: EBilanzRevisionStatus | undefined = Object.values(EBilanzRevisionStatus).find(status => status === value('revisionStatus')); + if (value('revisionStatus') != undefined && revisionStatus == undefined) { + return FakeEBilanzBackend.refuse(400, 'ValidationError', `revisionStatus needs to be one of ${Object.values(EBilanzRevisionStatus).join(', ')}`); + } + const fixedAssets: unknown = value('fixedAssets'); + return { + accountingStandard, + fixedAssets: Array.isArray(fixedAssets) ? fixedAssets.filter(row => FakeEBilanzBackend.isFigureRow(row)) : [], + ...revisionStatus == undefined ? {} : { revisionStatus } + }; + } + + private findPreparationRefusal(fiscalYearId: string): FakeAnswer | undefined { + const preparation: EBilanzFilingModel | undefined = this.findPreparation(fiscalYearId); + if (preparation == undefined) { + return FakeEBilanzBackend.refuse(409, 'ConflictError', 'The E-Bilanz of the fiscal year needs to be prepared first.'); + } + return this.isCurrent(preparation) + ? undefined + : FakeEBilanzBackend.refuse(409, 'ConflictError', 'The books state the E-Bilanz otherwise than it was prepared: prepare it again.'); + } + + private findFiledRefusal(fiscalYearId: string): FakeAnswer | undefined { + const preparation: EBilanzFilingModel | undefined = this.findPreparation(fiscalYearId); + const filed: boolean = this.filings.some(filing => filing.contentHash === preparation?.contentHash && FakeEBilanzBackend.isFiling(filing)); + return filed ? FakeEBilanzBackend.refuse(409, 'ConflictError', 'The E-Bilanz of the fiscal year is filed as prepared.') : undefined; + } + + // a running transmission holds the lease of the fiscal year, which every other transmission and filing waits for + private findRunningRefusal(fiscalYearId: string): FakeAnswer | undefined { + const running: boolean = FakeEBilanzBackend.resolveTransmissions(this.findFilings(fiscalYearId)) + .some(transmission => transmission.status === EBilanzTransmissionStatus.TRANSMITTING); + return running ? FakeEBilanzBackend.refuse(409, 'ConflictError', RUNNING) : undefined; + } + + private findFilings(fiscalYearId: string): EBilanzFilingModel[] { + return this.filings.filter(filing => filing.fiscalYearId === fiscalYearId); + } + + private findPreparation(fiscalYearId: string): EBilanzFilingModel | undefined { + return this.findFilings(fiscalYearId).filter(filing => filing.kind === EBilanzFilingKind.PREPARED).at(-1); + } + + // an open fiscal year states no E-Bilanz, like once it is reopened + private isCurrent(preparation: EBilanzFilingModel): boolean { + const fiscalYear: FiscalYearModel | undefined = this.fiscalYears.find(candidate => candidate.id === preparation.fiscalYearId); + if (this.stalePreparationIds.has(preparation.id) || preparation.input == undefined || fiscalYear?.closedAt == undefined) { + return false; + } + return FakeEBilanzBackend.resolveHash(this.resolvePreview(preparation.input)) === preparation.contentHash; + } + + private getSettings(): EBilanzCertificateSettingsModel { + return { certificateUploadedAt: this.certificateUploadedAt, certificateUploadedBy: this.certificateUploadedAt == undefined ? null : USER_ID }; + } + + private createFiling(fiscalYearId: string, kind: EBilanzFilingKind, values: Partial, protocol?: string): EBilanzFilingModel { + const id: string = this.resolveId(); + const filing: EBilanzFilingModel = { + id, + tenantId: TENANT_ID, + chainSequence: this.filings.length + 1, + chainHash: `fake-${id}`, + retainUntil: '2036-01-01T00:00:00.000Z', + archivedFiles: [], + fiscalYearId, + end: '2025-12-31T00:00:00.000Z', + kind, + preparationId: null, + contentHash: '', + content: null, + input: null, + correctsFilingId: null, + status: null, + transmissionId: null, + mayHaveBeenSent: false, + error: null, + succeeded: true, + ticket: null, + messages: [], + // the download route of the api, below its baseUrl + protocol: protocol == undefined ? null : { name: protocol, mimeType: 'application/pdf', size: 8, url: `${E_BILANZ_BASE_URL}/${id}/files/protocol` }, + createdBy: USER_ID, + createdAt: this.resolveMoment(), + ...values + }; + this.filings.push(filing); + return filing; + } + + // the records of a stage, as the routes would have made them + private startAt(stage: NonNullable, booksChanged: boolean): void { + if (stage === 'unprepared') { + return; + } + this.mappings = [{ id: this.resolveId(), tenantId: TENANT_ID, accountId: ACCOUNT_IDS.transit, position: TRANSIT_POSITION, creditPosition: null }]; + const figures: EBilanzFixedAssetInputModel[] = [{ position: OFFICE_EQUIPMENT_POSITION, values: [{ column: DEPRECIATION_COLUMN, amount: '200.00' }] }]; + this.prepare(FISCAL_YEAR_IDS.year2025, { accountingStandard: EBilanzAccountingStandard.UNIFIED, fixedAssets: figures }); + if (stage !== 'prepared') { + this.recordResult(this.startTransmission(FISCAL_YEAR_IDS.year2025, true), 'accepted'); + } + if (stage !== 'prepared' && stage !== 'tested') { + const started: EBilanzFilingModel = this.startTransmission(FISCAL_YEAR_IDS.year2025, false); + if (stage === 'sending') { + setTimeout(() => this.recordResult(started, this.transmissionOutcome), this.transmissionDurationInMs); + } + else { + this.recordResult(started, stage === 'unknown' ? 'unknown' : 'accepted'); + } + } + if (booksChanged) { + for (const filing of this.filings.filter(candidate => candidate.kind === EBilanzFilingKind.PREPARED)) { + this.stalePreparationIds.add(filing.id); + } + } + if (stage === 'correcting') { + // the books changed since it was filed, and the correction states that it fixes an error + this.stalePreparationIds.add(this.findPreparation(FISCAL_YEAR_IDS.year2025)?.id ?? ''); + this.prepare(FISCAL_YEAR_IDS.year2025, { + accountingStandard: EBilanzAccountingStandard.UNIFIED, + fixedAssets: figures, + revisionStatus: EBilanzRevisionStatus.CORRECTED + }); + } + } + + private answerJson(body: unknown): FakeAnswer { + return { status: 200, body: toJson(body) }; + } + + private refuseRoute(request: HttpRequest, path: string): FakeAnswer { + return FakeEBilanzBackend.refuse(404, 'NotFoundError', `There is no route ${request.method} ${path}.`); + } + + private resolveId(): string { + // apart from the ids of the other fixtures + return `eb000000-0000-4000-8000-${String(this.nextId++).padStart(12, '0')}`; + } + + // a minute after the one before, from a fixed moment, so specs and stories show the same moments every time + private resolveMoment(): string { + return new Date(Date.UTC(2026, 2, 2, 9, this.nextId)).toISOString(); + } + + // each record a transmission started with, with the latest record of its result, like the api + private static resolveTransmissions(filings: EBilanzFilingModel[]): EBilanzTransmissionModel[] { + return filings.filter(filing => filing.status === EBilanzTransmissionStatus.TRANSMITTING).map(started => { + const result: EBilanzFilingModel | undefined = filings.filter(filing => filing.transmissionId === started.id).at(-1); + return { + id: started.id, + test: started.kind === EBilanzFilingKind.TEST_TRANSMISSION, + status: result?.status ?? EBilanzTransmissionStatus.TRANSMITTING, + mayHaveBeenSent: result?.mayHaveBeenSent ?? true, + startedBy: started.createdBy, + startedAt: started.createdAt, + result: result ?? null + }; + }); + } + + private static isNotKnown(transmission: EBilanzTransmissionModel): boolean { + return transmission.status === EBilanzTransmissionStatus.UNKNOWN + || (transmission.status === EBilanzTransmissionStatus.FAILED && transmission.mayHaveBeenSent); + } + + private static isFiling(filing: EBilanzFilingModel): boolean { + return (filing.kind === EBilanzFilingKind.TRANSMISSION && filing.succeeded) || filing.kind === EBilanzFilingKind.MANUAL_FILING; + } + + private static isFigureRow(row: unknown): row is EBilanzFixedAssetInputModel { + return typeof row === 'object' && row != undefined && typeof Reflect.get(row, 'position') === 'string' && Array.isArray(Reflect.get(row, 'values')); + } + + // stands for the SHA-256 of the api: the same content has the same hash + private static resolveHash(preview: EBilanzPreviewModel): string { + let hash: number = 0; + for (const character of JSON.stringify(preview.content)) { + hash = Math.trunc(Math.imul(31, hash) + (character.codePointAt(0) ?? 0)); + } + return (hash >>> 0).toString(16); + } + + private static formatDay(day: Date): string { + return day.toISOString().slice(0, 10); + } + + private static refuse(status: number, name: string, message: string): FakeAnswer { + const body: ErrorResponseBody = { status, name, message, paragraphs: [message] }; + return { status, body }; + } +} diff --git a/projects/ngx-bookkeeping/income-statement/income-statement.component.html b/projects/ngx-bookkeeping/income-statement/income-statement.component.html new file mode 100644 index 0000000..f0a925c --- /dev/null +++ b/projects/ngx-bookkeeping/income-statement/income-statement.component.html @@ -0,0 +1 @@ + diff --git a/projects/ngx-bookkeeping/income-statement/income-statement.component.spec.ts b/projects/ngx-bookkeeping/income-statement/income-statement.component.spec.ts new file mode 100644 index 0000000..3dbea34 --- /dev/null +++ b/projects/ngx-bookkeeping/income-statement/income-statement.component.spec.ts @@ -0,0 +1,48 @@ +import { provideHttpClient } from '@angular/common/http'; +import { provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideBookkeepingConfig } from '@service-soft/ngx-bookkeeping/api'; +import { describe, expect, test } from 'vitest'; + +import { BookkeepingTestingUtilities } from '../fixtures/bookkeeping-testing.utilities'; +import { BOOKKEEPING_BASE_URL, FISCAL_YEAR_IDS, INCOME_STATEMENT_2026, STATEMENT_FORMS_2026, toJson } from '../fixtures/bookkeeping.fixtures'; +import { IncomeStatementComponent } from './income-statement.component'; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [IncomeStatementComponent] +}) +class HostComponent {} + +describe('IncomeStatementComponent', () => { + test('shows the positions of the fiscal year, its expenses negative, beside the ones of the year before', async () => { + TestBed.configureTestingModule({ + providers: [provideHttpClient(), provideHttpClientTesting(), provideBookkeepingConfig({ baseUrl: BOOKKEEPING_BASE_URL })] + }); + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + const requests: TestRequest[] = await BookkeepingTestingUtilities.settle(fixture, { + ...BookkeepingTestingUtilities.getBookAnswers(), + [`GET ${BOOKKEEPING_BASE_URL}/fiscal-years/${FISCAL_YEAR_IDS.year2026}/statement-forms`]: { status: 200, body: toJson(STATEMENT_FORMS_2026) }, + [`GET ${BOOKKEEPING_BASE_URL}/reports/income-statement`]: { status: 200, body: toJson(INCOME_STATEMENT_2026) } + }); + const root: HTMLElement = fixture.nativeElement as HTMLElement; + + // in the form of the income statement that applies, not the one of the balance sheet + expect(BookkeepingTestingUtilities.findRequest(requests, 'reports/income-statement')?.request.params.get('form')) + .toBe('hgb.income-statement.micro'); + // an income statement covers its fiscal year, which heads its column + expect([...root.querySelectorAll('thead th')].map(header => header.textContent.trim())).toEqual(['Position', '2026', '2025']); + expect([...root.querySelectorAll('tbody tr')].map(row => BookkeepingTestingUtilities.getText(row))).toEqual([ + 'Revenue €1,000.00 €2,000.00', + 'Other income €0.00 €0.00', + 'Cost of materials €0.00 €0.00', + 'Personnel expenses €0.00 €0.00', + 'Depreciation and amortization €0.00 €0.00', + 'Other expenses €0.00 -€1,050.00', + 'Taxes €0.00 €0.00', + 'Net income or net loss for the year €1,000.00 €950.00' + ]); + }); +}); diff --git a/projects/ngx-bookkeeping/income-statement/income-statement.component.ts b/projects/ngx-bookkeeping/income-statement/income-statement.component.ts new file mode 100644 index 0000000..813f032 --- /dev/null +++ b/projects/ngx-bookkeeping/income-statement/income-statement.component.ts @@ -0,0 +1,22 @@ +import { Component } from '@angular/core'; +import { StatementComponent } from '@service-soft/ngx-bookkeeping/statement'; +import { BookkeepingStatementType } from 'zibri-contract'; + +/** + * The income statement of the books of provideBookkeepingConfig: ``. It shows the revenue and + * the expenses of a fiscal year, the one of today at first, by position, with the figures of the year before and the + * result of the year, and every account with a balance in none of its positions, in the form that applies to the + * fiscal year or another form of the api the user chooses. It downloads as a pdf. + */ +@Component({ + selector: 'ngx-income-statement', + templateUrl: './income-statement.component.html', + imports: [StatementComponent], + host: { class: 'block' } +}) +export class IncomeStatementComponent { + /** + * The statement it shows. + */ + protected readonly type: BookkeepingStatementType = BookkeepingStatementType.INCOME_STATEMENT; +} diff --git a/projects/ngx-bookkeeping/income-statement/income-statement.stories.ts b/projects/ngx-bookkeeping/income-statement/income-statement.stories.ts new file mode 100644 index 0000000..43b18d0 --- /dev/null +++ b/projects/ngx-bookkeeping/income-statement/income-statement.stories.ts @@ -0,0 +1,36 @@ +import { Meta, StoryObj } from '@storybook/angular'; + +import { BookkeepingStoryUtilities } from '../fixtures/bookkeeping-story.utilities'; +import { FISCAL_YEAR_IDS, INCOME_STATEMENT_2026, STATEMENT_FORMS_2026 } from '../fixtures/bookkeeping.fixtures'; +import { IncomeStatementComponent } from './income-statement.component'; + +const INCOME_STATEMENT: string = 'GET reports/income-statement'; + +const FORMS: string = `GET fiscal-years/${FISCAL_YEAR_IDS.year2026}/statement-forms`; + +const meta: Meta = { + title: 'Bookkeeping/Income statement', + component: IncomeStatementComponent, + render: () => ({ template: '' }) +}; +export default meta; + +type Story = StoryObj; + +export const Default: Story = { + decorators: [ + BookkeepingStoryUtilities.provideBackend({ + [FORMS]: BookkeepingStoryUtilities.getAnswer(STATEMENT_FORMS_2026), + [INCOME_STATEMENT]: BookkeepingStoryUtilities.getAnswer(INCOME_STATEMENT_2026) + }) + ] +}; + +export const LoadingFailed: Story = { + decorators: [ + BookkeepingStoryUtilities.provideBackend({ + [FORMS]: BookkeepingStoryUtilities.getAnswer(STATEMENT_FORMS_2026), + [INCOME_STATEMENT]: { status: 503 } + }) + ] +}; diff --git a/projects/ngx-bookkeeping/income-statement/ng-package.json b/projects/ngx-bookkeeping/income-statement/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-bookkeeping/income-statement/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-bookkeeping/income-statement/public-api.ts b/projects/ngx-bookkeeping/income-statement/public-api.ts new file mode 100644 index 0000000..590293b --- /dev/null +++ b/projects/ngx-bookkeeping/income-statement/public-api.ts @@ -0,0 +1 @@ +export * from './income-statement.component'; diff --git a/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form-line-view.model.ts b/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form-line-view.model.ts new file mode 100644 index 0000000..86898c2 --- /dev/null +++ b/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form-line-view.model.ts @@ -0,0 +1,25 @@ +import { InputValidation } from '@service-soft/ui/input'; + +import { JournalEntryFormLine } from './journal-entry-form-line.model'; + +/** + * A line of the entry being typed, as the form shows it. + */ +export type JournalEntryFormLineView = { + /** + * The line. + */ + line: JournalEntryFormLine, + /** + * What screen readers call the group of its inputs, like 'Line 1'. + */ + label: string, + /** + * What screen readers call the button that removes it. + */ + removeLabel: string, + /** + * Checks that the line has an amount on exactly one side, as the rule of its debit input. + */ + validateAmount: InputValidation +}; diff --git a/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form-line.model.ts b/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form-line.model.ts new file mode 100644 index 0000000..0776102 --- /dev/null +++ b/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form-line.model.ts @@ -0,0 +1,21 @@ +/** + * A line of the entry being typed. + */ +export type JournalEntryFormLine = { + /** + * Tells the line apart from the others while lines are added and removed. + */ + key: number, + /** + * The id of the account, undefined until one is chosen. + */ + accountId: string | undefined, + /** + * The amount on the debit side, undefined while there is none. + */ + debit: number | undefined, + /** + * The amount on the credit side, undefined while there is none. + */ + credit: number | undefined +}; diff --git a/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form.component.html b/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form.component.html new file mode 100644 index 0000000..3f219ef --- /dev/null +++ b/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form.component.html @@ -0,0 +1,109 @@ +
+ @if (loadingFailed()) { + + } + +
+ @if (postedLabel(); as message) { + +
+

{{ message }}

+
+ } +
+ + @if (showForm()) { + +
+ + + + +
+
+ {{ labels.lines }} + @for (view of lineViews(); track view.line.key) { + +
+ {{ view.label }} + + + + + +
+ } +
+ +
+
+ + + + +

{{ showUnbalanced() ? unbalancedError() : '' }}

+ @if (error(); as message) { +
+ +

{{ message }}

+
+ } +
+ +
+
+ } +
diff --git a/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form.component.spec.ts b/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form.component.spec.ts new file mode 100644 index 0000000..4722e8b --- /dev/null +++ b/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form.component.spec.ts @@ -0,0 +1,150 @@ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component, signal, WritableSignal } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { BookkeepingDayUtilities, provideBookkeepingConfig } from '@service-soft/ngx-bookkeeping/api'; +import { FormTestingUtilities } from 'testing/form'; +import { beforeEach, describe, expect, test } from 'vitest'; +import { ErrorResponseBody, JournalEntryDetailsModel } from 'zibri-contract'; + +import { BookkeepingTestingUtilities } from '../fixtures/bookkeeping-testing.utilities'; +// the api answers the entry it posted, whose lines the spec doesn't read: any entry of the fixtures does. +import { ACCOUNT_IDS, BOOKKEEPING_BASE_URL, INVOICE_REVERSAL, toJson } from '../fixtures/bookkeeping.fixtures'; +import { JournalEntryFormComponent } from './journal-entry-form.component'; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [JournalEntryFormComponent] +}) +class HostComponent { + readonly posted: WritableSignal = signal(undefined); +} + +/** + * What a line of the spec types: its account and its amounts. + */ +type TypedLine = [account: string, debit: string, credit: string]; + +async function render(): Promise<[ComponentFixture, HTMLElement]> { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + await BookkeepingTestingUtilities.settle(fixture, BookkeepingTestingUtilities.getBookAnswers()); + return [fixture, fixture.nativeElement as HTMLElement]; +} + +function getLines(root: HTMLElement): HTMLFieldSetElement[] { + return [...root.querySelectorAll('fieldset fieldset')]; +} + +// fills in the text and the lines like a user does, an empty amount left as it is. +async function fill(fixture: ComponentFixture, root: HTMLElement, lines: TypedLine[]): Promise { + await BookkeepingTestingUtilities.type(fixture, FormTestingUtilities.findInput(root, 'text'), 'Rent April'); + for (const [index, [account, debit, credit]] of lines.entries()) { + if (getLines(root).length <= index) { + FormTestingUtilities.click(root, 'Add a line'); + await fixture.whenStable(); + } + const line: HTMLFieldSetElement | undefined = getLines(root)[index]; + await BookkeepingTestingUtilities.choose(fixture, line?.querySelector('ui-input-autocomplete input'), account); + const [debitInput, creditInput] = [...line?.querySelectorAll('ui-input-number input') ?? []]; + if (debit) { + await BookkeepingTestingUtilities.type(fixture, debitInput, debit); + } + if (credit) { + await BookkeepingTestingUtilities.type(fixture, creditInput, credit); + } + } +} + +async function submit(fixture: ComponentFixture, root: HTMLElement): Promise { + FormTestingUtilities.click(root, 'Post entry'); + await fixture.whenStable(); + TestBed.tick(); +} + +describe('JournalEntryFormComponent', () => { + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [provideHttpClient(), provideHttpClientTesting(), provideBookkeepingConfig({ baseUrl: BOOKKEEPING_BASE_URL })] + }); + }); + + test('shows the sums of both sides and their difference while the user types', async () => { + const [fixture, root] = await render(); + + await fill(fixture, root, [['4210 Rent', '1200', ''], ['1200 Bank', '', '1000']]); + + expect(BookkeepingTestingUtilities.getText(root.querySelector('ui-data-list'))).toBe('Debits €1,200.00 Credits €1,000.00 Difference €200.00'); + // a closed account takes no postings, so it is no option + const options: string[] = [...document.querySelectorAll('[role="option"]')].map(option => option.textContent.trim()); + expect(options).not.toContain('4211 Rent of the old office'); + }); + + test('refuses an unbalanced entry without sending it, and says why at the button that adds a line', async () => { + const [fixture, root] = await render(); + await fill(fixture, root, [['4210 Rent', '1200', ''], ['1200 Bank', '', '1000']]); + + await submit(fixture, root); + + TestBed.inject(HttpTestingController).expectNone(({ method }) => method === 'POST'); + const error: HTMLElement | null = root.querySelector('[id^="ngx-journal-entry-form-"]'); + expect(error?.textContent.trim()).toBe('The debits and the credits differ by €200.00. An entry is posted once both are equal.'); + const addLine: HTMLButtonElement | undefined = [...root.querySelectorAll('button')].find(button => button.textContent.trim() === 'Add a line'); + expect(addLine?.getAttribute('aria-describedby')).toBe(error?.id); + expect(document.activeElement).toBe(addLine); + }); + + test('refuses a line with an amount on both sides', async () => { + const [fixture, root] = await render(); + await fill(fixture, root, [['4210 Rent', '1200', '1200'], ['1200 Bank', '', '1200']]); + + await submit(fixture, root); + + TestBed.inject(HttpTestingController).expectNone(({ method }) => method === 'POST'); + expect(BookkeepingTestingUtilities.getText(getLines(root)[0])).toContain('Enter either a debit or a credit, not both.'); + }); + + test('posts a balanced entry with its amounts in the minor units of the currency, and starts over', async () => { + const [fixture, root] = await render(); + await fill(fixture, root, [['4210 Rent', '1000', ''], ['1200 Bank', '', '1190'], ['1400 Receivables', '190', '']]); + + await submit(fixture, root); + const request: TestRequest = TestBed.inject(HttpTestingController).expectOne({ method: 'POST', url: `${BOOKKEEPING_BASE_URL}/entries` }); + const today: string = BookkeepingDayUtilities.resolveToday().toISOString(); + expect(toJson(request.request.body)).toEqual({ + documentDate: today, + postingDate: today, + // eslint-disable-next-line unicorn/no-null -- the api takes null for an entry without a document number + documentReference: null, + text: 'Rent April', + lines: [ + { accountId: ACCOUNT_IDS.rent, debit: '1000.00' }, + { accountId: ACCOUNT_IDS.bank, credit: '1190.00' }, + { accountId: ACCOUNT_IDS.receivables, debit: '190.00' } + ] + }); + request.flush(toJson(INVOICE_REVERSAL)); + await BookkeepingTestingUtilities.settle(fixture, {}); + + expect(fixture.componentInstance.posted()?.entry.sequence).toBe(5); + expect(BookkeepingTestingUtilities.getText(root.querySelector('[role="status"]'))).toBe('Success Entry 5 was posted.'); + expect(document.activeElement).toBe(root.querySelector('[role="status"] > div')); + expect(FormTestingUtilities.findInput(root, 'text')?.value).toBe(''); + expect(getLines(root)).toHaveLength(2); + }); + + test('shows the message of the api when it refuses the entry', async () => { + const [fixture, root] = await render(); + await fill(fixture, root, [['4210 Rent', '1200', ''], ['1200 Bank', '', '1200']]); + + await submit(fixture, root); + const message: string = 'The posting day falls into the closed fiscal year 2025.'; + const body: ErrorResponseBody = { status: 409, name: 'ConflictError', message, paragraphs: [message] }; + TestBed.inject(HttpTestingController).expectOne({ method: 'POST', url: `${BOOKKEEPING_BASE_URL}/entries` }) + .flush(body, { status: 409, statusText: 'Conflict' }); + await BookkeepingTestingUtilities.settle(fixture, {}); + + expect(BookkeepingTestingUtilities.getText(root.querySelector('[role="alert"]'))).toBe(`Error ${message}`); + expect(FormTestingUtilities.findInput(root, 'text')?.value).toBe('Rent April'); + }); +}); diff --git a/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form.component.ts b/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form.component.ts new file mode 100644 index 0000000..e1bfc2d --- /dev/null +++ b/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form.component.ts @@ -0,0 +1,397 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { afterNextRender, afterRenderEffect, Component, computed, ElementRef, inject, Injector, LOCALE_ID, output, OutputEmitterRef, resource, ResourceRef, Signal, signal, viewChild, WritableSignal } from '@angular/core'; +import { BOOKKEEPING_CONFIG, BookkeepingAmountUtilities, BookkeepingCommonLabels, BookkeepingConfig, BookkeepingDayUtilities, BookkeepingEntryFormLabels, BookkeepingService } from '@service-soft/ngx-bookkeeping/api'; +import { ErrorResponseUtilities } from '@service-soft/ngx-error-handling/error-response'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { DataListComponent, DataListItem } from '@service-soft/ui/data-list'; +import { FormComponent } from '@service-soft/ui/form'; +import { InputOption } from '@service-soft/ui/input'; +import { InputAutocompleteComponent } from '@service-soft/ui/input-autocomplete'; +import { InputDateComponent } from '@service-soft/ui/input-date'; +import { InputNumberComponent } from '@service-soft/ui/input-number'; +import { InputStringComponent } from '@service-soft/ui/input-string'; +import { LoadingDirective } from '@service-soft/ui/loading'; +import { BookkeepingAccountModel, BookkeepingSettingsModel, JournalEntryDetailsModel, NewJournalEntryLineModel, NewJournalEntryModel } from 'zibri-contract'; + +import { JournalEntryFormLine } from './journal-entry-form-line.model'; +import { JournalEntryFormLineView } from './journal-entry-form-line-view.model'; + +/** + * The format of the currency of the books, and the decimals of its minor unit. + */ +type CurrencyFormat = { + /** + * Writes amounts in the language of the app with the currency. + */ + format: Intl.NumberFormat, + /** + * The decimals of the minor unit, like 2 for EUR. + */ + fractionDigits: number +}; + +/** + * The sums of the lines being typed, in minor units. + */ +type LineSums = { + /** + * The sum of the debits. + */ + debit: number, + /** + * The sum of the credits. + */ + credit: number +}; + +const MIN_LINES: number = 2; + +let nextId: number = 0; + +/** + * Posts an entry into the books of provideBookkeepingConfig: ``. The user + * gives the days of the document and of the posting, the number of the document and what was booked, and two or more + * lines, each on an open account with a debit or a credit. The sums of both sides and their difference show while the + * user types, and the browser only submits the form once they are equal: an unbalanced entry shows why instead, and is + * never sent. Once the api posted it, the form says so with the number of the entry, emits it and starts over; a + * refusal of the api, like for a day of a closed fiscal year, shows its message. + */ +@Component({ + selector: 'ngx-journal-entry-form', + templateUrl: './journal-entry-form.component.html', + imports: [ + ButtonComponent, + CalloutComponent, + DataListComponent, + FormComponent, + InputAutocompleteComponent, + InputDateComponent, + InputNumberComponent, + InputStringComponent, + LoadingDirective + ], + host: { class: 'block' } +}) +export class JournalEntryFormComponent { + private readonly config: BookkeepingConfig = inject(BOOKKEEPING_CONFIG); + + private readonly bookkeepingService: BookkeepingService = inject(BookkeepingService); + + private readonly locale: string = inject(LOCALE_ID); + + private readonly injector: Injector = inject(Injector); + + private readonly balanceInput: Signal | undefined> = viewChild>('balance'); + + private readonly addLineButton: Signal | undefined> = viewChild('addLineButton', { read: ElementRef }); + + private readonly postedMessage: Signal | undefined> = viewChild>('postedMessage'); + + /** + * Emits each entry once the api posted it. + */ + readonly posted: OutputEmitterRef = output(); + + /** + * The texts of the form. + */ + protected readonly labels: BookkeepingEntryFormLabels = this.config.labels.entryForm; + + /** + * The texts several views show. + */ + protected readonly commonLabels: BookkeepingCommonLabels = this.config.labels.common; + + /** + * The id of the error of an unbalanced entry. + */ + protected readonly unbalancedId: string = `ngx-journal-entry-form-${nextId++}-unbalanced`; + + private readonly settings: ResourceRef = resource({ + loader: async () => await this.bookkeepingService.resolveSettings() + }); + + private readonly accounts: ResourceRef = resource({ + loader: async () => await this.bookkeepingService.resolveAccounts() + }); + + /** + * Whether the settings or the accounts are loading. + */ + protected readonly isLoading: Signal = computed(() => this.settings.isLoading() || this.accounts.isLoading()); + + /** + * Whether the settings or the accounts couldn't be loaded. + */ + protected readonly loadingFailed: Signal = computed(() => { + return this.settings.error() != undefined || this.accounts.error() != undefined; + }); + + /** + * The open accounts to book on, by number. + */ + protected readonly accountOptions: Signal[]> = computed(() => { + const accounts: BookkeepingAccountModel[] = this.accounts.hasValue() ? this.accounts.value() ?? [] : []; + return accounts + .filter(account => account.closedAt == undefined) + .map(account => ({ label: `${account.number} ${account.name}`, value: account.id })); + }); + + /** + * Whether the form shows. It is gone for one render after posting, so its inputs start over, errors that showed + * included. + */ + protected readonly showForm: WritableSignal = signal(true); + + /** + * The day of the document, today at first. + */ + protected readonly documentDate: WritableSignal = signal(new Date()); + + /** + * The day the entry is booked on, today at first. + */ + protected readonly postingDate: WritableSignal = signal(new Date()); + + /** + * The number of the document. + */ + protected readonly documentReference: WritableSignal = signal(''); + + /** + * What was booked. + */ + protected readonly text: WritableSignal = signal(''); + + private readonly lines: WritableSignal = signal(this.createLines()); + + private nextLineKey: number = MIN_LINES; + + /** + * Whether a line can be removed, which an entry of two lines can't. + */ + protected readonly canRemoveLine: Signal = computed(() => this.lines().length > MIN_LINES); + + /** + * The lines as the form shows them. + */ + protected readonly lineViews: Signal = computed(() => this.lines().map((line, index) => ({ + line, + label: this.labels.line(index + 1), + removeLabel: this.labels.removeLineOf(index + 1), + validateAmount: () => this.validateAmount(line) + }))); + + private readonly currency: Signal = computed(() => { + const settings: BookkeepingSettingsModel | undefined = this.settings.hasValue() ? this.settings.value() : undefined; + if (settings == undefined) { + return undefined; + } + const format: Intl.NumberFormat = BookkeepingAmountUtilities.resolveFormat(settings.currency, this.locale); + return { format, fractionDigits: BookkeepingAmountUtilities.resolveFractionDigits(format) }; + }); + + /** + * The smallest amount, and the step of the amounts: one minor unit of the currency, like 0.01 for EUR. + */ + protected readonly step: Signal = computed(() => 1 / (10 ** (this.currency()?.fractionDigits ?? 2))); + + // in minor units, which add up exactly, unlike the decimals of the inputs. + private readonly sums: Signal = computed(() => { + const fractionDigits: number = this.currency()?.fractionDigits ?? 2; + return this.lines().reduce((sums, line) => ({ + debit: sums.debit + BookkeepingAmountUtilities.resolveMinorUnits(line.debit ?? 0, fractionDigits), + credit: sums.credit + BookkeepingAmountUtilities.resolveMinorUnits(line.credit ?? 0, fractionDigits) + }), { debit: 0, credit: 0 }); + }); + + /** + * The sums of both sides and their difference, as they show. + */ + protected readonly summary: Signal = computed(() => { + const { debit, credit } = this.sums(); + return [ + { label: this.labels.totalDebit, value: this.formatMinorUnits(debit) }, + { label: this.labels.totalCredit, value: this.formatMinorUnits(credit) }, + { label: this.labels.difference, value: this.formatMinorUnits(Math.abs(debit - credit)) } + ]; + }); + + /** + * Why the entry can't be posted while its sides differ, or undefined while they are equal. + */ + protected readonly unbalancedError: Signal = computed(() => { + const { debit, credit } = this.sums(); + return debit === credit ? undefined : this.labels.unbalanced(this.formatMinorUnits(Math.abs(debit - credit))); + }); + + /** + * Whether the error of an unbalanced entry shows, from the first submit on. + */ + protected readonly showUnbalanced: WritableSignal = signal(false); + + /** + * Whether the entry is being sent. + */ + protected readonly posting: WritableSignal = signal(false); + + /** + * What the form says about the last entry it posted, or undefined before the first. + */ + protected readonly postedLabel: WritableSignal = signal(undefined); + + /** + * Why the api refused the entry, its paragraphs one per line, or undefined while it refused none. + */ + protected readonly error: WritableSignal = signal(undefined); + + constructor() { + // no control holds the balance, so a hidden input is what the browser checks: invalid while the sides differ, + // which keeps the form from submitting like any invalid control. + afterRenderEffect({ + write: () => this.balanceInput()?.nativeElement.setCustomValidity(this.unbalancedError() ?? '') + }); + } + + /** + * Updates a line as the user types. + * @param key - The key of the line. + * @param change - What changed. + */ + protected updateLine(key: number, change: Partial>): void { + this.lines.update(lines => lines.map(line => line.key === key ? { ...line, ...change } : line)); + } + + /** + * Adds an empty line. + */ + protected addLine(): void { + this.lines.update(lines => [...lines, this.createLine()]); + } + + /** + * Removes a line, and gives the focus to the button that adds one, as the line that had it is gone. + * @param key - The key of the line. + */ + protected removeLine(key: number): void { + this.lines.update(lines => lines.filter(line => line.key !== key)); + this.addLineButton()?.nativeElement.focus(); + } + + /** + * Shows the error of an unbalanced entry once the form was submitted, instead of the popup of the browser. + * @param event - The invalid event of the hidden input of the balance. + */ + protected showUnbalancedError(event: Event): void { + event.preventDefault(); + this.showUnbalanced.set(true); + } + + /** + * Hands the focus the form gives the hidden input of the balance on to the button that adds a line, which the error + * describes. + */ + protected focusAddLine(): void { + this.addLineButton()?.nativeElement.focus(); + } + + /** + * Posts the entry, which the browser only submits once every line has an account and one amount, and both sides + * are equal. + */ + protected async post(): Promise { + const entry: NewJournalEntryModel | undefined = this.resolveEntry(); + if (entry == undefined) { + return; + } + this.posting.set(true); + this.error.set(undefined); + try { + const posted: JournalEntryDetailsModel = await this.bookkeepingService.postEntry(entry); + this.posted.emit(posted); + this.reset(posted); + } + catch (error) { + // a refusal of the api is the answer to the entry, like a day of a closed fiscal year. Anything else is a + // mistake, which goes on to the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.error.set(ErrorResponseUtilities.findMessage(error) ?? this.commonLabels.requestFailed); + } + finally { + this.posting.set(false); + } + } + + private resolveEntry(): NewJournalEntryModel | undefined { + const documentDate: Date | undefined = this.documentDate(); + const postingDate: Date | undefined = this.postingDate(); + const fractionDigits: number | undefined = this.currency()?.fractionDigits; + // the form only submits with both days, and its amounts have a step of the currency. + if (documentDate == undefined || postingDate == undefined || fractionDigits == undefined) { + return undefined; + } + const documentReference: string = this.documentReference().trim(); + return { + documentDate: BookkeepingDayUtilities.resolveDay(documentDate), + postingDate: BookkeepingDayUtilities.resolveDay(postingDate), + // eslint-disable-next-line unicorn/no-null -- the api takes null for an entry without a document number + documentReference: documentReference || null, + text: this.text().trim(), + lines: this.lines().map(line => this.toNewLine(line, fractionDigits)) + }; + } + + // the form only submits lines with an account and an amount on one side, which the api takes in minor units. + private toNewLine(line: JournalEntryFormLine, fractionDigits: number): NewJournalEntryLineModel { + const accountId: string = line.accountId ?? ''; + const toDecimal: (amount: number) => string = amount => BookkeepingAmountUtilities.resolveDecimal( + BookkeepingAmountUtilities.resolveMinorUnits(amount, fractionDigits), + fractionDigits + ); + return line.debit == undefined ? { accountId, credit: toDecimal(line.credit ?? 0) } : { accountId, debit: toDecimal(line.debit) }; + } + + // the days stay for the next entry, which is often of the same document. + private reset(posted: JournalEntryDetailsModel): void { + this.documentReference.set(''); + this.text.set(''); + this.lines.set(this.createLines()); + this.showUnbalanced.set(false); + this.postedLabel.set(this.labels.posted(posted.entry.sequence)); + this.showForm.set(false); + afterNextRender(() => { + this.showForm.set(true); + // the button that had the focus is gone with the form, and the message says what happened. + this.postedMessage()?.nativeElement.focus(); + }, { injector: this.injector }); + } + + private validateAmount(line: JournalEntryFormLine): string | undefined { + if (line.debit == undefined && line.credit == undefined) { + return this.labels.amountMissing; + } + return line.debit != undefined && line.credit != undefined ? this.labels.amountTwice : undefined; + } + + private formatMinorUnits(minorUnits: number): string { + const currency: CurrencyFormat | undefined = this.currency(); + if (currency == undefined) { + return ''; + } + const decimal: string = BookkeepingAmountUtilities.resolveDecimal(minorUnits, currency.fractionDigits); + return BookkeepingAmountUtilities.format(decimal, currency.format); + } + + private createLines(): JournalEntryFormLine[] { + return Array.from({ length: MIN_LINES }, (_, key) => ({ key, accountId: undefined, debit: undefined, credit: undefined })); + } + + private createLine(): JournalEntryFormLine { + const key: number = this.nextLineKey; + this.nextLineKey++; + return { key, accountId: undefined, debit: undefined, credit: undefined }; + } +} diff --git a/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form.stories.ts b/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form.stories.ts new file mode 100644 index 0000000..d727c87 --- /dev/null +++ b/projects/ngx-bookkeeping/journal-entry-form/journal-entry-form.stories.ts @@ -0,0 +1,33 @@ +import { Meta, StoryObj } from '@storybook/angular'; +import { ErrorResponseBody } from 'zibri-contract'; + +import { BookkeepingStoryUtilities } from '../fixtures/bookkeeping-story.utilities'; +import { INVOICE_REVERSAL, toJson } from '../fixtures/bookkeeping.fixtures'; +import { JournalEntryFormComponent } from './journal-entry-form.component'; + +const CLOSED_MESSAGE: string = 'The posting day 2025-12-31 falls into the closed fiscal year 2025. Post into an open fiscal year.'; + +const CLOSED: ErrorResponseBody = { status: 409, name: 'ConflictError', message: CLOSED_MESSAGE, paragraphs: [CLOSED_MESSAGE] }; + +const meta: Meta = { + title: 'Bookkeeping/Journal entry form', + component: JournalEntryFormComponent, + render: () => ({ template: '' }) +}; +export default meta; + +type Story = StoryObj; + +// a balanced entry is posted, an unbalanced one says why it isn't. +export const Default: Story = { + decorators: [BookkeepingStoryUtilities.provideBackend({ 'POST entries': { status: 200, body: toJson(INVOICE_REVERSAL) } })] +}; + +// posting shows the message of the api. +export const Refused: Story = { + decorators: [BookkeepingStoryUtilities.provideBackend({ 'POST entries': { status: 409, body: CLOSED } })] +}; + +export const LoadingFailed: Story = { + decorators: [BookkeepingStoryUtilities.provideBackend({ 'GET accounts': { status: 503 } })] +}; diff --git a/projects/ngx-bookkeeping/journal-entry-form/ng-package.json b/projects/ngx-bookkeeping/journal-entry-form/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-bookkeeping/journal-entry-form/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-bookkeeping/journal-entry-form/public-api.ts b/projects/ngx-bookkeeping/journal-entry-form/public-api.ts new file mode 100644 index 0000000..c9562ad --- /dev/null +++ b/projects/ngx-bookkeeping/journal-entry-form/public-api.ts @@ -0,0 +1 @@ +export * from './journal-entry-form.component'; diff --git a/projects/ngx-bookkeeping/journal/journal-entry-reversal-dialog-data.model.ts b/projects/ngx-bookkeeping/journal/journal-entry-reversal-dialog-data.model.ts new file mode 100644 index 0000000..61fd6a0 --- /dev/null +++ b/projects/ngx-bookkeeping/journal/journal-entry-reversal-dialog-data.model.ts @@ -0,0 +1,13 @@ +/** + * The entry the dialog reverses. + */ +export type JournalEntryReversalDialogData = { + /** + * The id of the entry. + */ + id: string, + /** + * Its number in its fiscal year. + */ + sequence: number +}; diff --git a/projects/ngx-bookkeeping/journal/journal-entry-reversal-dialog.component.html b/projects/ngx-bookkeeping/journal/journal-entry-reversal-dialog.component.html new file mode 100644 index 0000000..bd63afa --- /dev/null +++ b/projects/ngx-bookkeeping/journal/journal-entry-reversal-dialog.component.html @@ -0,0 +1,17 @@ + +

{{ labels.reversalTitle(data.sequence) }}

+

{{ labels.reversalText }}

+ + + @if (error(); as message) { +
+ +

{{ message }}

+
+ } + +
+ + +
+
diff --git a/projects/ngx-bookkeeping/journal/journal-entry-reversal-dialog.component.ts b/projects/ngx-bookkeeping/journal/journal-entry-reversal-dialog.component.ts new file mode 100644 index 0000000..4931cec --- /dev/null +++ b/projects/ngx-bookkeeping/journal/journal-entry-reversal-dialog.component.ts @@ -0,0 +1,97 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { Component, inject, signal, WritableSignal } from '@angular/core'; +import { BOOKKEEPING_CONFIG, BookkeepingCommonLabels, BookkeepingConfig, BookkeepingDayUtilities, BookkeepingJournalLabels, BookkeepingService } from '@service-soft/ngx-bookkeeping/api'; +import { ErrorResponseUtilities } from '@service-soft/ngx-error-handling/error-response'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { DIALOG_DATA, DialogRef } from '@service-soft/ui/dialog'; +import { FormComponent } from '@service-soft/ui/form'; +import { InputDateComponent } from '@service-soft/ui/input-date'; +import { InputStringComponent } from '@service-soft/ui/input-string'; +import { JournalEntryDetailsModel } from 'zibri-contract'; + +import { JournalEntryReversalDialogData } from './journal-entry-reversal-dialog-data.model'; + +/** + * Asks for the day and the reason of reversing an entry, and reverses it once the user confirms with both. It stays + * open with the message of the api when the api refuses, like for a day of a closed fiscal year, and closes with the + * reversal once it is posted. Only used by the journal. + */ +@Component({ + selector: 'ngx-journal-entry-reversal-dialog', + templateUrl: './journal-entry-reversal-dialog.component.html', + imports: [ButtonComponent, CalloutComponent, FormComponent, InputDateComponent, InputStringComponent] +}) +export class JournalEntryReversalDialogComponent { + private readonly config: BookkeepingConfig = inject(BOOKKEEPING_CONFIG); + + private readonly bookkeepingService: BookkeepingService = inject(BookkeepingService); + + /** + * The entry to reverse. + */ + protected readonly data: JournalEntryReversalDialogData = inject(DIALOG_DATA); + + /** + * The dialog, to close it with the reversal. + */ + protected readonly dialogRef: DialogRef = inject>(DialogRef); + + /** + * The texts of the journal. + */ + protected readonly labels: BookkeepingJournalLabels = this.config.labels.journal; + + /** + * The texts several views show. + */ + protected readonly commonLabels: BookkeepingCommonLabels = this.config.labels.common; + + /** + * The day the reversal is booked on, today at first. + */ + protected readonly postingDate: WritableSignal = signal(new Date()); + + /** + * Why the entry is reversed, the text of the reversal. + */ + protected readonly reason: WritableSignal = signal(''); + + /** + * Whether the reversal is being sent. + */ + protected readonly reversing: WritableSignal = signal(false); + + /** + * Why the api refused the reversal, its paragraphs one per line, or undefined while it refused none. + */ + protected readonly error: WritableSignal = signal(undefined); + + /** + * Reverses the entry, which the form only submits with a day and a reason. + */ + protected async reverse(): Promise { + const postingDate: Date | undefined = this.postingDate(); + if (postingDate == undefined) { + return; + } + this.reversing.set(true); + this.error.set(undefined); + try { + this.dialogRef.close(await this.bookkeepingService.reverseEntry(this.data.id, { + postingDate: BookkeepingDayUtilities.resolveDay(postingDate), + text: this.reason().trim() + })); + } + catch (error) { + // a refusal of the api is the answer to the reversal, anything else a mistake for the error handler. + if (!(error instanceof HttpErrorResponse)) { + throw error; + } + this.error.set(ErrorResponseUtilities.findMessage(error) ?? this.commonLabels.requestFailed); + } + finally { + this.reversing.set(false); + } + } +} diff --git a/projects/ngx-bookkeeping/journal/journal-entry-view.model.ts b/projects/ngx-bookkeeping/journal/journal-entry-view.model.ts new file mode 100644 index 0000000..2a46a5f --- /dev/null +++ b/projects/ngx-bookkeeping/journal/journal-entry-view.model.ts @@ -0,0 +1,64 @@ +import { JournalLineView } from './journal-line-view.model'; + +/** + * An entry as the journal shows it. + */ +export type JournalEntryView = { + /** + * The id of the entry. + */ + id: string, + /** + * Its number in its fiscal year. + */ + sequence: number, + /** + * What the entry is called by its number, like 'Entry 12'. + */ + title: string, + /** + * What was booked. + */ + text: string, + /** + * The day it is booked on, formatted. + */ + postingDate: string, + /** + * The day it is booked on, as an ISO string for the datetime of its time element. + */ + postingDateIso: string, + /** + * The day of its document, formatted. + */ + documentDate: string, + /** + * The number of its document, or undefined for none. + */ + documentReference: string | undefined, + /** + * The badge of a reversal, which says which entry it reverses, or undefined for an entry that reverses none. + */ + reversal: string | undefined, + /** + * The badge of an entry that was reversed, which says by which entry when that is on the page, or undefined for one + * that wasn't. + */ + reversedBy: string | undefined, + /** + * Whether it can be reversed: it is no reversal, and was not reversed. + */ + canReverse: boolean, + /** + * What screen readers call the button that reverses it. + */ + reverseLabel: string, + /** + * What screen readers call the table of its lines. + */ + linesLabel: string, + /** + * Its lines. + */ + lines: JournalLineView[] +}; diff --git a/projects/ngx-bookkeeping/journal/journal-entry.component.html b/projects/ngx-bookkeeping/journal/journal-entry.component.html new file mode 100644 index 0000000..d58c86c --- /dev/null +++ b/projects/ngx-bookkeeping/journal/journal-entry.component.html @@ -0,0 +1,59 @@ +
+ {{ entry().title }} + {{ entry().text }} + @if (entry().reversal; as reversal) { + {{ reversal }} + } + @if (entry().reversedBy; as reversedBy) { + {{ reversedBy }} + } + @if (entry().canReverse) { + + } +
+
+
+
{{ commonLabels.postingDate }}
+
+
+
+
{{ commonLabels.documentDate }}
+
{{ entry().documentDate }}
+
+ @if (entry().documentReference; as documentReference) { +
+
{{ commonLabels.documentReference }}
+
{{ documentReference }}
+
+ } +
+
+ + + + + + + + + + @for (line of entry().lines; track line.id) { + + + + + + } + +
{{ commonLabels.account }}{{ commonLabels.debit }}{{ commonLabels.credit }}
{{ line.account }}{{ line.debit }}{{ line.credit }}
+
diff --git a/projects/ngx-bookkeeping/journal/journal-entry.component.ts b/projects/ngx-bookkeeping/journal/journal-entry.component.ts new file mode 100644 index 0000000..9d02c58 --- /dev/null +++ b/projects/ngx-bookkeeping/journal/journal-entry.component.ts @@ -0,0 +1,40 @@ +import { Component, inject, input, InputSignal, output, OutputEmitterRef } from '@angular/core'; +import { BOOKKEEPING_CONFIG, BookkeepingCommonLabels, BookkeepingConfig, BookkeepingJournalLabels } from '@service-soft/ngx-bookkeeping/api'; +import { BadgeComponent } from '@service-soft/ui/badge'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { ScrollRegionDirective } from '@service-soft/ui/scroll-region'; + +import { JournalEntryView } from './journal-entry-view.model'; + +/** + * An entry of the journal with its lines, and the button that reverses it. Only used by the journal. + */ +@Component({ + selector: 'ngx-journal-entry', + templateUrl: './journal-entry.component.html', + imports: [BadgeComponent, ButtonComponent, ScrollRegionDirective], + host: { class: 'grid gap-2' } +}) +export class JournalEntryComponent { + private readonly config: BookkeepingConfig = inject(BOOKKEEPING_CONFIG); + + /** + * The entry. + */ + readonly entry: InputSignal = input.required(); + + /** + * Emits when the user wants to reverse the entry. + */ + readonly reversing: OutputEmitterRef = output(); + + /** + * The texts of the journal. + */ + protected readonly labels: BookkeepingJournalLabels = this.config.labels.journal; + + /** + * The texts several views show. + */ + protected readonly commonLabels: BookkeepingCommonLabels = this.config.labels.common; +} diff --git a/projects/ngx-bookkeeping/journal/journal-line-view.model.ts b/projects/ngx-bookkeeping/journal/journal-line-view.model.ts new file mode 100644 index 0000000..778e6ec --- /dev/null +++ b/projects/ngx-bookkeeping/journal/journal-line-view.model.ts @@ -0,0 +1,21 @@ +/** + * A line of an entry as the journal shows it. + */ +export type JournalLineView = { + /** + * The id of the line. + */ + id: string, + /** + * The account booked on, its number and name. + */ + account: string, + /** + * The amount on the debit side formatted, or an empty string for a line on the credit side. + */ + debit: string, + /** + * The amount on the credit side formatted, or an empty string for a line on the debit side. + */ + credit: string +}; diff --git a/projects/ngx-bookkeeping/journal/journal.component.html b/projects/ngx-bookkeeping/journal/journal.component.html new file mode 100644 index 0000000..a295156 --- /dev/null +++ b/projects/ngx-bookkeeping/journal/journal.component.html @@ -0,0 +1,49 @@ +
+ + + +
+
+ +
+@if (alert(); as alert) { + +} + +

{{ announcement() }}

+@if (hasNoFiscalYears()) { + +} @else { + +
+ +
    + @for (entry of items(); track entry.id) { +
  • + +
  • + } @empty { +
  • {{ labels.noEntries }}
  • + } +
+
+ + +} diff --git a/projects/ngx-bookkeeping/journal/journal.component.spec.ts b/projects/ngx-bookkeeping/journal/journal.component.spec.ts new file mode 100644 index 0000000..2cd6dbc --- /dev/null +++ b/projects/ngx-bookkeeping/journal/journal.component.spec.ts @@ -0,0 +1,220 @@ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideBookkeepingConfig } from '@service-soft/ngx-bookkeeping/api'; +import { DialogTestingUtilities } from 'testing/dialog'; +import { FormTestingUtilities } from 'testing/form'; +import { FakeAnswer } from 'testing/http'; +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; +import { ErrorResponseBody, JournalEntryDetailsModel, JournalEntryPageModel } from 'zibri-contract'; + +import { BookkeepingTestingUtilities } from '../fixtures/bookkeeping-testing.utilities'; +import { ACCOUNT_IDS, BOOKKEEPING_BASE_URL, ENTRIES, ENTRY_IDS, ENTRY_PAGE_2026, FISCAL_YEAR_IDS, INVOICE_REVERSAL, toJson } from '../fixtures/bookkeeping.fixtures'; +import { JournalComponent } from './journal.component'; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [JournalComponent] +}) +class HostComponent {} + +const ENTRIES_PATH: string = `GET ${BOOKKEEPING_BASE_URL}/entries`; + +function getAnswers(page: JournalEntryPageModel = ENTRY_PAGE_2026): Record { + return { ...BookkeepingTestingUtilities.getBookAnswers(), [ENTRIES_PATH]: { status: 200, body: toJson(page) } }; +} + +async function render(): Promise<[ComponentFixture, HTMLElement, TestRequest[]]> { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + const requests: TestRequest[] = await BookkeepingTestingUtilities.settle(fixture, getAnswers()); + return [fixture, fixture.nativeElement as HTMLElement, requests]; +} + +function getEntries(root: HTMLElement): HTMLElement[] { + return [...root.querySelectorAll('ngx-journal-entry')]; +} + +function findDialog(): HTMLDialogElement | undefined { + return [...document.querySelectorAll('dialog[open]')].at(-1) ?? undefined; +} + +// presses the button that reverses an entry, and waits for the dialog it opens. +async function openReversal(root: HTMLElement, sequence: number): Promise { + root.querySelector(`button[aria-label="Reverse entry ${sequence}"]`)?.click(); + return await vi.waitFor(() => { + TestBed.tick(); + const dialog: HTMLDialogElement | undefined = findDialog(); + if (dialog == undefined) { + throw new Error('No dialog opened.'); + } + return dialog; + }); +} + +describe('JournalComponent', () => { + let removeModalDialogs: () => void; + + beforeEach(() => { + removeModalDialogs = DialogTestingUtilities.addModalDialogs(); + TestBed.configureTestingModule({ + providers: [provideHttpClient(), provideHttpClientTesting(), provideBookkeepingConfig({ baseUrl: BOOKKEEPING_BASE_URL })] + }); + }); + + afterEach(() => { + removeModalDialogs(); + for (const dialog of document.querySelectorAll('ui-dialog')) { + dialog.remove(); + } + }); + + test('shows the first page of the entries of the fiscal year of today with their lines, the reversals next to their entries', async () => { + const [, root, requests] = await render(); + + expect(BookkeepingTestingUtilities.findRequest(requests, 'entries')?.request.params.toString()) + .toBe(`page=1&limit=20&fiscalYearId=${FISCAL_YEAR_IDS.year2026}`); + expect(getEntries(root).map(entry => BookkeepingTestingUtilities.getText(entry.querySelector('div')))).toEqual([ + 'Entry 1 Opening balances Reverse', + 'Entry 2 Rent March Reversed by entry 3', + 'Entry 3 Booked on the wrong account Reverses entry 2', + 'Entry 4 Invoice RE-2026-0001 to Example Ltd. Reverse' + ]); + const invoice: HTMLElement | undefined = getEntries(root)[3]; + // the days in the language of the app, like the date inputs, whose empty period holds no example date + expect(BookkeepingTestingUtilities.getText(invoice?.querySelector('dl'))).toBe('Posting date 03/10/2026 Document date 03/09/2026 Document number RE-2026-0001'); + expect([...root.querySelectorAll('ui-input-date-range input')].map(input => input.placeholder)) + .toEqual(['MM/DD/YYYY', 'MM/DD/YYYY']); + expect(invoice?.querySelector('table')?.getAttribute('aria-label')).toBe('Lines of entry 4'); + expect([...invoice?.querySelectorAll('tbody tr') ?? []].map(row => BookkeepingTestingUtilities.getText(row))).toEqual([ + '1400 Receivables €1,190.00', + '8400 Revenue 19 % €1,000.00', + '1776 Output tax 19 % €190.00' + ]); + expect(BookkeepingTestingUtilities.getText(root.querySelector('ui-data-list'))).toBe('Debits of the period €17,040.00 Credits of the period €17,040.00'); + }); + + test('marks an entry the api names as reversed by an entry on another page, and offers no reversal of it', async () => { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + const [, , , invoice] = ENTRIES; + const page: JournalEntryPageModel = { + ...ENTRY_PAGE_2026, + items: invoice == undefined ? [] : [{ ...invoice, reversedByEntryId: ENTRY_IDS.invoiceReversal }], + totalAmount: 21 + }; + await BookkeepingTestingUtilities.settle(fixture, getAnswers(page)); + const root: HTMLElement = fixture.nativeElement as HTMLElement; + + expect(getEntries(root).map(entry => BookkeepingTestingUtilities.getText(entry.querySelector('div')))).toEqual([ + 'Entry 4 Invoice RE-2026-0001 to Example Ltd. Reversed' + ]); + expect(root.querySelector('button[aria-label="Reverse entry 4"]')).toBeNull(); + }); + + test('has the api filter the entries by the account and the period, and page them, with the sums of the account', async () => { + const [fixture, root] = await render(); + + await BookkeepingTestingUtilities.choose(fixture, root.querySelector('ui-input-autocomplete input'), '1400 Receivables'); + const invoice: JournalEntryDetailsModel[] = ENTRIES.slice(3); + const receivables: JournalEntryPageModel = { items: invoice, totalAmount: 21, debit: '1190', credit: '0' }; + let requests: TestRequest[] = await BookkeepingTestingUtilities.settle(fixture, getAnswers(receivables)); + expect(BookkeepingTestingUtilities.findRequest(requests, 'entries')?.request.params.toString()) + .toBe(`page=1&limit=20&fiscalYearId=${FISCAL_YEAR_IDS.year2026}&accountId=${ACCOUNT_IDS.receivables}`); + expect(getEntries(root).map(entry => entry.querySelector('span')?.textContent)).toEqual(['Entry 4']); + expect(BookkeepingTestingUtilities.getText(root.querySelector('ui-data-list'))).toBe('Debits of the period €1,190.00 Credits of the period €0.00'); + + root.querySelector('button[aria-label="Page 2"]')?.click(); + requests = await BookkeepingTestingUtilities.settle(fixture, getAnswers(receivables)); + expect(BookkeepingTestingUtilities.findRequest(requests, 'entries')?.request.params.get('page')).toBe('2'); + + const [start, end] = root.querySelectorAll('ui-input-date-range input'); + await BookkeepingTestingUtilities.type(fixture, start, '03/01/2026'); + await BookkeepingTestingUtilities.type(fixture, end, '03/31/2026'); + requests = await BookkeepingTestingUtilities.settle(fixture, getAnswers({ ...receivables, totalAmount: 1 })); + // another filter starts over on the first page + expect(BookkeepingTestingUtilities.findRequest(requests, 'entries')?.request.params.toString()).toBe( + `page=1&limit=20&fiscalYearId=${FISCAL_YEAR_IDS.year2026}&from=2026-03-01&until=2026-03-31&accountId=${ACCOUNT_IDS.receivables}` + ); + }); + + test('shows the message of the api when it refuses the filters', async () => { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + const message: string = 'The books have no account 9f8e7d6c.'; + const body: ErrorResponseBody = { status: 400, name: 'BadRequestError', message, paragraphs: [message] }; + await BookkeepingTestingUtilities.settle(fixture, { ...getAnswers(), [ENTRIES_PATH]: { status: 400, body } }); + + expect((fixture.nativeElement as HTMLElement).querySelector('[role="alert"]')?.textContent.trim()).toBe('The books couldn\'t be loaded.'); + }); + + test('reverses an entry on the day and with the reason of the dialog, and shows the reversal next to it', async () => { + const [fixture, root] = await render(); + + const dialog: HTMLDialogElement = await openReversal(root, 4); + expect(dialog.querySelector('h2')?.textContent).toBe('Reverse entry 4?'); + await BookkeepingTestingUtilities.type(fixture, FormTestingUtilities.findInput(dialog, 'postingDate'), '03/12/2026'); + await BookkeepingTestingUtilities.type(fixture, FormTestingUtilities.findInput(dialog, 'reason'), ' Wrong customer '); + FormTestingUtilities.click(dialog, 'Reverse'); + TestBed.tick(); + const reversal: TestRequest = TestBed.inject(HttpTestingController) + .expectOne({ method: 'POST', url: `${BOOKKEEPING_BASE_URL}/entries/${ENTRY_IDS.invoice}/reversal` }); + expect(toJson(reversal.request.body)).toEqual({ postingDate: '2026-03-12T00:00:00.000Z', text: 'Wrong customer' }); + reversal.flush(toJson(INVOICE_REVERSAL)); + + // the journal loads again, with the reversal + const reversed: JournalEntryDetailsModel[] = ENTRIES.map(details => { + return details.entry.id === ENTRY_IDS.invoice ? { ...details, reversedByEntryId: ENTRY_IDS.invoiceReversal } : details; + }); + const requests: TestRequest[] = await BookkeepingTestingUtilities.settle(fixture, getAnswers({ + items: [...reversed, INVOICE_REVERSAL], + totalAmount: ENTRIES.length + 1, + debit: '18230', + credit: '18230' + })); + expect(BookkeepingTestingUtilities.findRequest(requests, 'entries')).toBeDefined(); + expect(findDialog()).toBeUndefined(); + expect(root.querySelector('[role="status"]')?.textContent.trim()).toBe('Entry 4 was reversed by entry 5.'); + expect(BookkeepingTestingUtilities.getText(getEntries(root)[3]?.querySelector('div'))).toBe('Entry 4 Invoice RE-2026-0001 to Example Ltd. Reversed by entry 5'); + }); + + test('keeps the dialog open with the message of the api when it refuses the reversal', async () => { + const [fixture, root] = await render(); + + const dialog: HTMLDialogElement = await openReversal(root, 1); + await BookkeepingTestingUtilities.type(fixture, FormTestingUtilities.findInput(dialog, 'reason'), 'Wrong amount'); + FormTestingUtilities.click(dialog, 'Reverse'); + TestBed.tick(); + const message: string = 'The posting day 2026-11-25 falls into no open fiscal year.'; + const body: ErrorResponseBody = { status: 409, name: 'ConflictError', message, paragraphs: [message] }; + TestBed.inject(HttpTestingController).expectOne(({ method }) => method === 'POST').flush(body, { status: 409, statusText: 'Conflict' }); + await BookkeepingTestingUtilities.settle(fixture, {}); + + expect(findDialog()).toBe(dialog); + expect(BookkeepingTestingUtilities.getText(dialog.querySelector('[role="alert"]'))).toBe(`Error ${message}`); + TestBed.inject(HttpTestingController).expectNone(({ method, url }) => method === 'GET' && url === `${BOOKKEEPING_BASE_URL}/entries`); + }); + + test('neither reverses without a reason nor after cancelling', async () => { + const [fixture, root] = await render(); + + const dialog: HTMLDialogElement = await openReversal(root, 4); + FormTestingUtilities.click(dialog, 'Reverse'); + await fixture.whenStable(); + expect(findDialog()).toBe(dialog); + FormTestingUtilities.click(dialog, 'Cancel'); + await fixture.whenStable(); + + expect(findDialog()).toBeUndefined(); + TestBed.inject(HttpTestingController).expectNone(({ method }) => method === 'POST'); + }); + + test('says when the books couldn\'t be loaded', async () => { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + await BookkeepingTestingUtilities.settle(fixture, { + ...BookkeepingTestingUtilities.getBookAnswers(), + [`GET ${BOOKKEEPING_BASE_URL}/fiscal-years`]: { status: 503 } + }); + + expect((fixture.nativeElement as HTMLElement).querySelector('[role="alert"]')?.textContent.trim()).toBe('The books couldn\'t be loaded.'); + }); +}); diff --git a/projects/ngx-bookkeeping/journal/journal.component.ts b/projects/ngx-bookkeeping/journal/journal.component.ts new file mode 100644 index 0000000..024ac44 --- /dev/null +++ b/projects/ngx-bookkeeping/journal/journal.component.ts @@ -0,0 +1,300 @@ +import { Component, computed, inject, linkedSignal, resource, ResourceRef, Signal, signal, WritableSignal } from '@angular/core'; +import { BookkeepingDayUtilities, BookkeepingJournalLabels, BookkeepingViewDirective } from '@service-soft/ngx-bookkeeping/api'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { DataListComponent, DataListItem } from '@service-soft/ui/data-list'; +import { DialogService } from '@service-soft/ui/dialog'; +import { EmptyStateComponent } from '@service-soft/ui/empty-state'; +import { InputOption } from '@service-soft/ui/input'; +import { InputAutocompleteComponent } from '@service-soft/ui/input-autocomplete'; +import { InputDateRange, InputDateRangeComponent } from '@service-soft/ui/input-date-range'; +import { InputSelectComponent } from '@service-soft/ui/input-select'; +import { LoadingDirective } from '@service-soft/ui/loading'; +import { PaginationComponent } from '@service-soft/ui/pagination'; +import { BookkeepingAccountModel, FiscalYearModel, JournalEntryDetailsModel, JournalEntryLineModel, JournalEntryPageModel, JournalEntryQueryModel } from 'zibri-contract'; + +import { JournalEntryReversalDialogComponent } from './journal-entry-reversal-dialog.component'; +import { JournalEntryReversalDialogData } from './journal-entry-reversal-dialog-data.model'; +import { JournalEntryView } from './journal-entry-view.model'; +import { JournalEntryComponent } from './journal-entry.component'; +import { JournalLineView } from './journal-line-view.model'; + +/** + * The first and the last day the journal shows, at midnight UTC. + */ +type JournalRange = { + /** + * The first day. + */ + from: Date, + /** + * The last day. + */ + until: Date +}; + +/** + * What the journal loads its entries for: the page and the filters, and the last posting of the app, after which it + * loads again. + */ +type JournalParams = JournalEntryQueryModel & { + /** + * The last entry the app posted, undefined before the first. + */ + lastPosting: JournalEntryDetailsModel | undefined +}; + +/** + * The journal of the books of provideBookkeepingConfig: ``. It shows the entries of a fiscal year, the + * one of today at first, with their lines, by posting day and number, a page at a time as the api answers it, and + * filters them by a period of the year and by an account they book on, with the debits and the credits of every entry + * that matches. An entry is reversed after the user chose the day and the reason of the reversal, and the journal then + * shows the reversal next to it. The journal of the period downloads as a pdf. + */ +@Component({ + selector: 'ngx-journal', + templateUrl: './journal.component.html', + imports: [ + ButtonComponent, + DataListComponent, + EmptyStateComponent, + InputAutocompleteComponent, + InputDateRangeComponent, + InputSelectComponent, + JournalEntryComponent, + LoadingDirective, + PaginationComponent + ], + host: { class: 'block' } +}) +export class JournalComponent extends BookkeepingViewDirective { + private readonly dialogService: DialogService = inject(DialogService); + + /** + * The texts of the journal. + */ + protected readonly labels: BookkeepingJournalLabels = this.config.labels.journal; + + /** + * How many entries a page has. + */ + protected readonly pageSize: number = this.config.pageSize; + + private readonly accounts: ResourceRef = resource({ + loader: async () => await this.bookkeepingService.resolveAccounts() + }); + + /** + * The part of the fiscal year whose entries show, empty for all of it. It starts over with another fiscal year. + */ + protected readonly period: WritableSignal = linkedSignal({ + source: this.fiscalYearId, + computation: (): InputDateRange => ({ start: undefined, end: undefined }) + }); + + /** + * The id of the account whose entries show, undefined for every account. + */ + protected readonly accountId: WritableSignal = signal(undefined); + + /** + * The accounts to filter by, by number. + */ + protected readonly accountOptions: Signal[]> = computed(() => { + return this.getAccounts().map(account => ({ label: this.getAccountName(account), value: account.id })); + }); + + // the days the user chose, undefined while they chose none or are still typing a period with only one of its days, + // which shows the whole fiscal year meanwhile. + private readonly chosenRange: Signal = computed(() => { + const { start, end } = this.period(); + return start == undefined || end == undefined + ? undefined + : { from: BookkeepingDayUtilities.resolveDay(start), until: BookkeepingDayUtilities.resolveDay(end) }; + }); + + private readonly range: Signal = computed(() => { + const fiscalYear: FiscalYearModel | undefined = this.fiscalYear(); + if (fiscalYear == undefined) { + return undefined; + } + return this.chosenRange() ?? { from: fiscalYear.start, until: fiscalYear.end }; + }); + + /** + * Whether there is a period to download the journal of. + */ + protected readonly hasRange: Signal = computed(() => this.range() != undefined); + + /** + * The page that shows. It starts over when a filter changes. + */ + protected readonly page: WritableSignal = linkedSignal({ + source: () => [this.range(), this.accountId()], + computation: () => 1 + }); + + private readonly journal: ResourceRef = resource({ + params: (): JournalParams | undefined => { + const fiscalYearId: string | undefined = this.fiscalYear()?.id; + if (fiscalYearId == undefined) { + return undefined; + } + const accountId: string | undefined = this.accountId(); + return { + page: this.page(), + limit: this.pageSize, + fiscalYearId, + ...this.chosenRange(), + ...accountId == undefined ? {} : { accountId }, + lastPosting: this.bookkeepingService.lastPosting() + }; + }, + loader: async ({ params }) => await this.bookkeepingService.resolveEntries(params) + }); + + /** + * Whether the journal is loading. + */ + protected readonly isLoading: Signal = computed(() => { + return this.journal.isLoading() || this.settings.isLoading() || this.fiscalYears.isLoading() || this.accounts.isLoading(); + }); + + /** + * Whether the books or the journal couldn't be loaded. + */ + protected readonly loadingFailed: Signal = computed(() => { + return [this.journal, this.settings, this.fiscalYears, this.accounts].some(loaded => loaded.error() != undefined); + }); + + /** + * What the journal last said about a reversal, read by screen readers as it changes. + */ + protected readonly announcement: WritableSignal = signal(''); + + private readonly entryPage: Signal = computed(() => { + return this.journal.hasValue() ? this.journal.value() : undefined; + }); + + // the entries of the page, which the api filtered by the account, the days and the fiscal year. + private readonly entries: Signal = computed(() => this.entryPage()?.items ?? []); + + /** + * How many entries match the filters on all pages together. + */ + protected readonly totalAmount: Signal = computed(() => this.entryPage()?.totalAmount ?? 0); + + private readonly accountNames: Signal> = computed(() => { + return new Map(this.getAccounts().map(account => [account.id, this.getAccountName(account)])); + }); + + /** + * The entries of the page. + */ + protected readonly items: Signal = computed(() => { + const format: Intl.NumberFormat | undefined = this.format(); + if (format == undefined) { + return []; + } + return this.entries().map(details => this.toView(details, format)); + }); + + /** + * The debits and the credits of every entry that matches the filters, as the api adds them up, of the lines on the + * account of the filter when there is one. None while no entry matches. + */ + protected readonly totals: Signal = computed(() => { + const format: Intl.NumberFormat | undefined = this.format(); + const page: JournalEntryPageModel | undefined = this.entryPage(); + if (format == undefined || page == undefined || !page.items.length) { + return []; + } + return [ + { label: this.labels.totalDebit, value: this.formatAmount(page.debit, format) }, + { label: this.labels.totalCredit, value: this.formatAmount(page.credit, format) } + ]; + }); + + /** + * Reverses an entry, after the user chose the day and the reason in a dialog, and says so once it is posted. + * @param entry - The entry. + */ + protected async reverse(entry: JournalEntryView): Promise { + const data: JournalEntryReversalDialogData = { id: entry.id, sequence: entry.sequence }; + const reversal: JournalEntryDetailsModel | undefined = await this.dialogService + .open(JournalEntryReversalDialogComponent, data) + .closed; + if (reversal != undefined) { + // the journal loads again with the lastPosting of the service, and shows the reversal. + this.announcement.set(this.labels.reversed(entry.sequence, reversal.entry.sequence)); + } + } + + /** + * Downloads the journal of the period as a pdf. + */ + protected async downloadPdf(): Promise { + const range: JournalRange | undefined = this.range(); + if (range != undefined) { + await this.download(async () => await this.bookkeepingService.resolveJournalPdf(range.from, range.until)); + } + } + + private toView(details: JournalEntryDetailsModel, format: Intl.NumberFormat): JournalEntryView { + const { entry, lines, reversedByEntryId } = details; + // the api names the reversal of an entry, wherever it is. Its number, and that of the entry a reversal + // reverses, are only known for an entry on the page, the others only say that they are one. + const reversed: JournalEntryDetailsModel | undefined = this.entries() + .find(candidate => candidate.entry.id === entry.reversesEntryId); + const reversedBy: JournalEntryDetailsModel | undefined = this.entries() + .find(candidate => candidate.entry.id === reversedByEntryId); + const isReversal: boolean = entry.reversesEntryId != undefined; + const isReversed: boolean = reversedByEntryId != undefined; + return { + id: entry.id, + sequence: entry.sequence, + title: this.commonLabels.entryNumber(entry.sequence), + text: entry.text, + postingDate: this.formatDay(entry.postingDate), + postingDateIso: BookkeepingDayUtilities.getQueryValue(entry.postingDate), + documentDate: this.formatDay(entry.documentDate), + documentReference: entry.documentReference ?? undefined, + reversal: this.resolveReversalLabel(isReversal, reversed), + reversedBy: this.resolveReversedByLabel(isReversed, reversedBy), + canReverse: !isReversal && !isReversed, + reverseLabel: this.labels.reverseEntry(entry.sequence), + linesLabel: this.labels.lines(entry.sequence), + lines: lines.map(line => this.toLineView(line, format)) + }; + } + + private resolveReversalLabel(isReversal: boolean, reversed: JournalEntryDetailsModel | undefined): string | undefined { + if (!isReversal) { + return undefined; + } + return reversed == undefined ? this.labels.reversal : this.labels.reversalOf(reversed.entry.sequence); + } + + private resolveReversedByLabel(isReversed: boolean, reversedBy: JournalEntryDetailsModel | undefined): string | undefined { + if (!isReversed) { + return undefined; + } + return reversedBy == undefined ? this.labels.reversedEntry : this.labels.reversedBy(reversedBy.entry.sequence); + } + + private toLineView(line: JournalEntryLineModel, format: Intl.NumberFormat): JournalLineView { + return { + id: line.id, + account: this.accountNames().get(line.accountId) ?? line.accountId, + debit: line.debit == undefined ? '' : this.formatAmount(line.debit, format), + credit: line.credit == undefined ? '' : this.formatAmount(line.credit, format) + }; + } + + private getAccountName(account: BookkeepingAccountModel): string { + return `${account.number} ${account.name}`; + } + + private getAccounts(): BookkeepingAccountModel[] { + return this.accounts.hasValue() ? this.accounts.value() ?? [] : []; + } +} diff --git a/projects/ngx-bookkeeping/journal/journal.stories.ts b/projects/ngx-bookkeeping/journal/journal.stories.ts new file mode 100644 index 0000000..b1c9c1f --- /dev/null +++ b/projects/ngx-bookkeeping/journal/journal.stories.ts @@ -0,0 +1,55 @@ +import { Meta, StoryObj } from '@storybook/angular'; +import { JournalEntryPageModel } from 'zibri-contract'; + +import { BookkeepingStoryUtilities } from '../fixtures/bookkeeping-story.utilities'; +import { ENTRY_IDS, ENTRY_PAGE_2026, INVOICE_REVERSAL } from '../fixtures/bookkeeping.fixtures'; +import { JournalComponent } from './journal.component'; + +const JOURNAL: string = 'GET entries'; + +const meta: Meta = { + title: 'Bookkeeping/Journal', + component: JournalComponent, + render: () => ({ template: '' }) +}; +export default meta; + +type Story = StoryObj; + +// reversing an entry opens the dialog of its day and reason, and posts the reversal. +export const Default: Story = { + decorators: [ + BookkeepingStoryUtilities.provideBackend({ + [JOURNAL]: BookkeepingStoryUtilities.getAnswer(ENTRY_PAGE_2026), + [`POST entries/${ENTRY_IDS.invoice}/reversal`]: BookkeepingStoryUtilities.getAnswer(INVOICE_REVERSAL) + }) + ] +}; + +// more entries than a page holds, which the api answers a page at a time. The invoice is reversed by an entry on a +// later page, so it says that it is reversed and offers no reversal. +const PAGE_OF_MANY: JournalEntryPageModel = { + ...ENTRY_PAGE_2026, + items: ENTRY_PAGE_2026.items.map(details => { + return details.entry.id === ENTRY_IDS.invoice ? { ...details, reversedByEntryId: ENTRY_IDS.invoiceReversal } : details; + }), + totalAmount: 64 +}; + +export const Pages: Story = { + decorators: [BookkeepingStoryUtilities.provideBackend({ [JOURNAL]: BookkeepingStoryUtilities.getAnswer(PAGE_OF_MANY) })] +}; + +const NO_ENTRIES: JournalEntryPageModel = { items: [], totalAmount: 0, debit: '0', credit: '0' }; + +export const NoEntries: Story = { + decorators: [BookkeepingStoryUtilities.provideBackend({ [JOURNAL]: BookkeepingStoryUtilities.getAnswer(NO_ENTRIES) })] +}; + +export const NoFiscalYears: Story = { + decorators: [BookkeepingStoryUtilities.provideBackend({ 'GET fiscal-years': BookkeepingStoryUtilities.getAnswer([]) })] +}; + +export const LoadingFailed: Story = { + decorators: [BookkeepingStoryUtilities.provideBackend({ [JOURNAL]: { status: 503 } })] +}; diff --git a/projects/ngx-bookkeeping/journal/ng-package.json b/projects/ngx-bookkeeping/journal/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-bookkeeping/journal/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-bookkeeping/journal/public-api.ts b/projects/ngx-bookkeeping/journal/public-api.ts new file mode 100644 index 0000000..6f16cea --- /dev/null +++ b/projects/ngx-bookkeeping/journal/public-api.ts @@ -0,0 +1 @@ +export * from './journal.component'; diff --git a/projects/ngx-bookkeeping/ledger/ledger-balance-view.model.ts b/projects/ngx-bookkeeping/ledger/ledger-balance-view.model.ts new file mode 100644 index 0000000..9cc1994 --- /dev/null +++ b/projects/ngx-bookkeeping/ledger/ledger-balance-view.model.ts @@ -0,0 +1,17 @@ +/** + * A balance of the ledger as it shows: its amount without a sign, and the side it is on. + */ +export type LedgerBalanceView = { + /** + * The amount without a sign, formatted. + */ + amount: string, + /** + * What shows after the amount for its side, like 'Dr', or an empty string for a balance of zero. + */ + side: string, + /** + * What screen readers read for its side, like 'Debit', or an empty string for a balance of zero. + */ + sideLabel: string +}; diff --git a/projects/ngx-bookkeeping/ledger/ledger-balance.component.html b/projects/ngx-bookkeeping/ledger/ledger-balance.component.html new file mode 100644 index 0000000..489e49c --- /dev/null +++ b/projects/ngx-bookkeeping/ledger/ledger-balance.component.html @@ -0,0 +1,5 @@ +{{ balance().amount }} +@if (balance().side) { + + {{ balance().sideLabel }} +} diff --git a/projects/ngx-bookkeeping/ledger/ledger-balance.component.ts b/projects/ngx-bookkeeping/ledger/ledger-balance.component.ts new file mode 100644 index 0000000..2b157d5 --- /dev/null +++ b/projects/ngx-bookkeeping/ledger/ledger-balance.component.ts @@ -0,0 +1,19 @@ +import { Component, input, InputSignal } from '@angular/core'; + +import { LedgerBalanceView } from './ledger-balance-view.model'; + +/** + * A balance of the ledger: its amount, and its side after it, which screen readers read as a word. Only used by the + * ledger. + */ +@Component({ + selector: 'ngx-ledger-balance', + templateUrl: './ledger-balance.component.html', + host: { class: 'contents' } +}) +export class LedgerBalanceComponent { + /** + * The balance. + */ + readonly balance: InputSignal = input.required(); +} diff --git a/projects/ngx-bookkeeping/ledger/ledger-line-view.model.ts b/projects/ngx-bookkeeping/ledger/ledger-line-view.model.ts new file mode 100644 index 0000000..f77aad6 --- /dev/null +++ b/projects/ngx-bookkeeping/ledger/ledger-line-view.model.ts @@ -0,0 +1,39 @@ +import { LedgerBalanceView } from './ledger-balance-view.model'; + +/** + * A line of the ledger as it shows. + */ +export type LedgerLineView = { + /** + * Tells the line apart from the others, its entry. + */ + key: string, + /** + * The day it is booked on, formatted. + */ + postingDate: string, + /** + * The entry by its number, like 'Entry 12'. + */ + entry: string, + /** + * The number of the document, or an empty string for none. + */ + documentReference: string, + /** + * What was booked. + */ + text: string, + /** + * The amount on the debit side formatted, or an empty string. + */ + debit: string, + /** + * The amount on the credit side formatted, or an empty string. + */ + credit: string, + /** + * The balance after the line. + */ + balance: LedgerBalanceView +}; diff --git a/projects/ngx-bookkeeping/ledger/ledger-table.component.html b/projects/ngx-bookkeeping/ledger/ledger-table.component.html new file mode 100644 index 0000000..6cc92ce --- /dev/null +++ b/projects/ngx-bookkeeping/ledger/ledger-table.component.html @@ -0,0 +1,49 @@ + +
+ + + + + + + + + + + + + + + + + + @for (line of ledger().lines; track line.key) { + + + + + + + + + + } @empty { + + + + } + + + + + + + + + + + + + +
{{ commonLabels.postingDate }}{{ commonLabels.entry }}{{ commonLabels.documentReference }}{{ commonLabels.text }}{{ commonLabels.debit }}{{ commonLabels.credit }}{{ commonLabels.balance }}
{{ labels.openingBalance }}
{{ line.postingDate }}{{ line.entry }}{{ line.documentReference }}{{ line.text }}{{ line.debit }}{{ line.credit }}
{{ labels.noLines }}
{{ commonLabels.total }}{{ ledger().debit }}{{ ledger().credit }}
{{ labels.closingBalance }}
+
diff --git a/projects/ngx-bookkeeping/ledger/ledger-table.component.ts b/projects/ngx-bookkeeping/ledger/ledger-table.component.ts new file mode 100644 index 0000000..a04c433 --- /dev/null +++ b/projects/ngx-bookkeeping/ledger/ledger-table.component.ts @@ -0,0 +1,35 @@ +import { Component, inject, input, InputSignal } from '@angular/core'; +import { BOOKKEEPING_CONFIG, BookkeepingCommonLabels, BookkeepingConfig, BookkeepingLedgerLabels } from '@service-soft/ngx-bookkeeping/api'; +import { ScrollRegionDirective } from '@service-soft/ui/scroll-region'; + +import { LedgerBalanceComponent } from './ledger-balance.component'; +import { LedgerView } from './ledger-view.model'; + +/** + * The table of the ledger: the balance before the period, each line with the balance after it, the sums of both sides + * and the balance after. Only used by the ledger. + */ +@Component({ + selector: 'ngx-ledger-table', + templateUrl: './ledger-table.component.html', + imports: [LedgerBalanceComponent, ScrollRegionDirective], + host: { class: 'block' } +}) +export class LedgerTableComponent { + private readonly config: BookkeepingConfig = inject(BOOKKEEPING_CONFIG); + + /** + * The ledger. + */ + readonly ledger: InputSignal = input.required(); + + /** + * The texts of the ledger. + */ + protected readonly labels: BookkeepingLedgerLabels = this.config.labels.ledger; + + /** + * The texts several views show. + */ + protected readonly commonLabels: BookkeepingCommonLabels = this.config.labels.common; +} diff --git a/projects/ngx-bookkeeping/ledger/ledger-view.model.ts b/projects/ngx-bookkeeping/ledger/ledger-view.model.ts new file mode 100644 index 0000000..6b7f508 --- /dev/null +++ b/projects/ngx-bookkeeping/ledger/ledger-view.model.ts @@ -0,0 +1,32 @@ +import { LedgerBalanceView } from './ledger-balance-view.model'; +import { LedgerLineView } from './ledger-line-view.model'; + +/** + * The ledger of an account as it shows. + */ +export type LedgerView = { + /** + * What screen readers call the table, with the account. + */ + label: string, + /** + * The balance before the period. + */ + openingBalance: LedgerBalanceView, + /** + * The lines of the period. + */ + lines: LedgerLineView[], + /** + * The sum of the debits of the period, formatted. + */ + debit: string, + /** + * The sum of the credits of the period, formatted. + */ + credit: string, + /** + * The balance after the period. + */ + closingBalance: LedgerBalanceView +}; diff --git a/projects/ngx-bookkeeping/ledger/ledger.component.html b/projects/ngx-bookkeeping/ledger/ledger.component.html new file mode 100644 index 0000000..71fae7b --- /dev/null +++ b/projects/ngx-bookkeeping/ledger/ledger.component.html @@ -0,0 +1,32 @@ +
+ + + +
+
+ +
+@if (alert(); as alert) { + +} +@if (hasNoFiscalYears()) { + +} @else if (!hasAccount()) { +

{{ labels.chooseAccount }}

+} @else { +
+ @if (view(); as view) { + + } +
+} diff --git a/projects/ngx-bookkeeping/ledger/ledger.component.spec.ts b/projects/ngx-bookkeeping/ledger/ledger.component.spec.ts new file mode 100644 index 0000000..f7c3420 --- /dev/null +++ b/projects/ngx-bookkeeping/ledger/ledger.component.spec.ts @@ -0,0 +1,68 @@ +import { provideHttpClient } from '@angular/common/http'; +import { provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component, input, InputSignal } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideBookkeepingConfig } from '@service-soft/ngx-bookkeeping/api'; +import { FakeAnswer } from 'testing/http'; +import { beforeEach, describe, expect, test } from 'vitest'; + +import { BookkeepingTestingUtilities } from '../fixtures/bookkeeping-testing.utilities'; +import { ACCOUNT_IDS, BANK_LEDGER_2026, BOOKKEEPING_BASE_URL, toJson } from '../fixtures/bookkeeping.fixtures'; +import { LedgerComponent } from './ledger.component'; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [LedgerComponent] +}) +class HostComponent { + readonly accountId: InputSignal = input(); +} + +const ANSWERS: Record = { + ...BookkeepingTestingUtilities.getBookAnswers(), + [`GET ${BOOKKEEPING_BASE_URL}/reports/ledger`]: { status: 200, body: toJson(BANK_LEDGER_2026) } +}; + +async function render(accountId?: string): Promise<[ComponentFixture, HTMLElement, TestRequest[]]> { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + fixture.componentRef.setInput('accountId', accountId); + const requests: TestRequest[] = await BookkeepingTestingUtilities.settle(fixture, ANSWERS); + return [fixture, fixture.nativeElement as HTMLElement, requests]; +} + +describe('LedgerComponent', () => { + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [provideHttpClient(), provideHttpClientTesting(), provideBookkeepingConfig({ baseUrl: BOOKKEEPING_BASE_URL })] + }); + }); + + test('shows what was booked on the account in the fiscal year, each balance with its side', async () => { + const [, root, requests] = await render(ACCOUNT_IDS.bank); + + expect(BookkeepingTestingUtilities.findRequest(requests, 'reports/ledger')?.request.params.toString()) + .toBe(`accountId=${ACCOUNT_IDS.bank}&from=2026-01-01&until=2026-12-31`); + expect(root.querySelector('table')?.getAttribute('aria-label')).toBe('Ledger of 1200 Bank'); + expect([...root.querySelectorAll('tbody tr, tfoot tr')].map(row => BookkeepingTestingUtilities.getText(row))).toEqual([ + 'Opening balance €0.00', + '01/01/2026 Entry 1 Opening balances €13,450.00 €13,450.00 Dr Debit', + '03/01/2026 Entry 2 L-2026-03 Rent March €1,200.00 €12,250.00 Dr Debit', + '03/05/2026 Entry 3 L-2026-03 Booked on the wrong account €1,200.00 €13,450.00 Dr Debit', + 'Total €14,650.00 €1,200.00', + 'Closing balance €13,450.00 Dr Debit' + ]); + // screen readers read the side as a word, instead of its abbreviation + expect(root.querySelector('tfoot [aria-hidden="true"]')?.textContent).toBe('Dr'); + expect(root.querySelector('tfoot .sr-only')?.textContent).toBe('Debit'); + }); + + test('asks for an account before it loads a ledger', async () => { + const [, root, requests] = await render(); + + expect(BookkeepingTestingUtilities.findRequest(requests, 'reports/ledger')).toBeUndefined(); + expect([...root.querySelectorAll('p')].map(paragraph => paragraph.textContent.trim())) + .toContain('Choose an account to see what was booked on it.'); + expect([...root.querySelectorAll('button')].find(button => button.textContent.trim() === 'Download as PDF')?.disabled).toBe(true); + }); +}); diff --git a/projects/ngx-bookkeeping/ledger/ledger.component.ts b/projects/ngx-bookkeeping/ledger/ledger.component.ts new file mode 100644 index 0000000..aa82f96 --- /dev/null +++ b/projects/ngx-bookkeeping/ledger/ledger.component.ts @@ -0,0 +1,177 @@ +import { Component, computed, linkedSignal, model, ModelSignal, resource, ResourceRef, Signal, WritableSignal } from '@angular/core'; +import { BookkeepingAmountUtilities, BookkeepingDayUtilities, BookkeepingLedgerLabels, BookkeepingViewDirective } from '@service-soft/ngx-bookkeeping/api'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { EmptyStateComponent } from '@service-soft/ui/empty-state'; +import { InputOption } from '@service-soft/ui/input'; +import { InputAutocompleteComponent } from '@service-soft/ui/input-autocomplete'; +import { InputDateRange, InputDateRangeComponent } from '@service-soft/ui/input-date-range'; +import { InputSelectComponent } from '@service-soft/ui/input-select'; +import { LoadingDirective } from '@service-soft/ui/loading'; +import { BookkeepingAccountModel, BookkeepingLedgerLineModel, BookkeepingLedgerReportModel, FiscalYearModel } from 'zibri-contract'; + +import { LedgerBalanceView } from './ledger-balance-view.model'; +import { LedgerLineView } from './ledger-line-view.model'; +import { LedgerTableComponent } from './ledger-table.component'; +import { LedgerView } from './ledger-view.model'; + +/** + * The account and the days the ledger shows. + */ +type LedgerParams = { + /** + * The id of the account. + */ + accountId: string, + /** + * The first day, at midnight UTC. + */ + from: Date, + /** + * The last day, at midnight UTC. + */ + until: Date +}; + +/** + * The ledger of an account of the books of provideBookkeepingConfig: ``, or `` + * for an account chosen beforehand. It shows what was booked on the account in a fiscal year, the one of today at first, + * or in a period of it: the balance before, each line with the balance after it, the sums of both sides and the + * balance after. Each balance says its side, as the api answers it. The ledger of the period downloads as a pdf. + */ +@Component({ + selector: 'ngx-ledger', + templateUrl: './ledger.component.html', + imports: [ + ButtonComponent, + EmptyStateComponent, + InputAutocompleteComponent, + InputDateRangeComponent, + InputSelectComponent, + LedgerTableComponent, + LoadingDirective + ], + host: { class: 'block' } +}) +export class LedgerComponent extends BookkeepingViewDirective { + /** + * The texts of the ledger. + */ + protected readonly labels: BookkeepingLedgerLabels = this.config.labels.ledger; + + private readonly accounts: ResourceRef = resource({ + loader: async () => await this.bookkeepingService.resolveAccounts() + }); + + /** + * The accounts to choose from, by number. + */ + protected readonly accountOptions: Signal[]> = computed(() => { + const accounts: BookkeepingAccountModel[] = this.accounts.hasValue() ? this.accounts.value() ?? [] : []; + return accounts.map(account => ({ label: `${account.number} ${account.name}`, value: account.id })); + }); + + /** + * The id of the account whose ledger shows, undefined until one is chosen. Bind it with `[(accountId)]` to keep it, + * like in the url. + */ + readonly accountId: ModelSignal = model(); + + /** + * The part of the fiscal year the ledger shows, empty for all of it. It starts over with another fiscal year. + */ + protected readonly period: WritableSignal = linkedSignal({ + source: this.fiscalYearId, + computation: (): InputDateRange => ({ start: undefined, end: undefined }) + }); + + // a period the user is still typing, with only one of its days, shows the whole fiscal year meanwhile. + private readonly params: Signal = computed(() => { + const fiscalYear: FiscalYearModel | undefined = this.fiscalYear(); + const accountId: string | undefined = this.accountId(); + if (fiscalYear == undefined || accountId == undefined) { + return undefined; + } + const { start, end } = this.period(); + return start == undefined || end == undefined + ? { accountId, from: fiscalYear.start, until: fiscalYear.end } + : { accountId, from: BookkeepingDayUtilities.resolveDay(start), until: BookkeepingDayUtilities.resolveDay(end) }; + }); + + /** + * Whether an account is chosen, whose ledger shows and downloads. + */ + protected readonly hasAccount: Signal = computed(() => this.params() != undefined); + + private readonly ledger: ResourceRef = resource({ + params: () => this.params(), + loader: async ({ params }) => await this.bookkeepingService.resolveLedger(params.accountId, params.from, params.until) + }); + + /** + * Whether the ledger is loading. + */ + protected readonly isLoading: Signal = computed(() => { + return this.ledger.isLoading() || this.settings.isLoading() || this.fiscalYears.isLoading() || this.accounts.isLoading(); + }); + + /** + * Whether the books or the ledger couldn't be loaded. + */ + protected readonly loadingFailed: Signal = computed(() => { + return [this.ledger, this.settings, this.fiscalYears, this.accounts].some(loaded => loaded.error() != undefined); + }); + + /** + * The ledger as it shows, undefined until it is loaded. + */ + protected readonly view: Signal = computed(() => { + const ledger: BookkeepingLedgerReportModel | undefined = this.ledger.hasValue() ? this.ledger.value() : undefined; + const format: Intl.NumberFormat | undefined = this.format(); + if (ledger == undefined || format == undefined) { + return undefined; + } + return { + label: this.labels.table(`${ledger.account.number} ${ledger.account.name}`), + openingBalance: this.toBalanceView(ledger.openingBalance, format), + lines: ledger.lines.map(line => this.toLineView(line, format)), + debit: this.formatAmount(ledger.debit, format), + credit: this.formatAmount(ledger.credit, format), + closingBalance: this.toBalanceView(ledger.closingBalance, format) + }; + }); + + /** + * Downloads the ledger of the period as a pdf. + */ + protected async downloadPdf(): Promise { + const params: LedgerParams | undefined = this.params(); + if (params != undefined) { + const { accountId, from, until } = params; + await this.download(async () => await this.bookkeepingService.resolveLedgerPdf(accountId, from, until)); + } + } + + private toLineView(line: BookkeepingLedgerLineModel, format: Intl.NumberFormat): LedgerLineView { + return { + key: line.entryId, + postingDate: this.formatDay(line.postingDate), + entry: this.commonLabels.entryNumber(line.sequence), + documentReference: line.documentReference ?? '', + text: line.text, + debit: line.debit == undefined ? '' : this.formatAmount(line.debit, format), + credit: line.credit == undefined ? '' : this.formatAmount(line.credit, format), + balance: this.toBalanceView(line.balance, format) + }; + } + + // a balance of the ledger is the debits less the credits, so its sign says its side. + private toBalanceView(balance: string, format: Intl.NumberFormat): LedgerBalanceView { + const amount: string = this.formatAmount(BookkeepingAmountUtilities.getAbsolute(balance), format); + if (BookkeepingAmountUtilities.isZero(balance)) { + return { amount, side: '', sideLabel: '' }; + } + return BookkeepingAmountUtilities.isNegative(balance) + ? { amount, side: this.commonLabels.creditSide, sideLabel: this.commonLabels.credit } + : { amount, side: this.commonLabels.debitSide, sideLabel: this.commonLabels.debit }; + } +} diff --git a/projects/ngx-bookkeeping/ledger/ledger.stories.ts b/projects/ngx-bookkeeping/ledger/ledger.stories.ts new file mode 100644 index 0000000..cae1141 --- /dev/null +++ b/projects/ngx-bookkeeping/ledger/ledger.stories.ts @@ -0,0 +1,31 @@ +import { Meta, StoryObj } from '@storybook/angular'; + +import { BookkeepingStoryUtilities } from '../fixtures/bookkeeping-story.utilities'; +import { ACCOUNT_IDS, BANK_LEDGER_2026 } from '../fixtures/bookkeeping.fixtures'; +import { LedgerComponent } from './ledger.component'; + +const LEDGER: string = 'GET reports/ledger'; + +const meta: Meta = { + title: 'Bookkeeping/Ledger', + component: LedgerComponent, + decorators: [BookkeepingStoryUtilities.provideBackend({ [LEDGER]: BookkeepingStoryUtilities.getAnswer(BANK_LEDGER_2026) })] +}; +export default meta; + +type Story = StoryObj; + +export const Default: Story = { + render: () => ({ template: `` }) +}; + +export const NoAccount: Story = { + render: () => ({ template: '' }) +}; + +export const NoLines: Story = { + decorators: [ + BookkeepingStoryUtilities.provideBackend({ [LEDGER]: BookkeepingStoryUtilities.getAnswer({ ...BANK_LEDGER_2026, lines: [] }) }) + ], + render: () => ({ template: `` }) +}; diff --git a/projects/ngx-bookkeeping/ledger/ng-package.json b/projects/ngx-bookkeeping/ledger/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-bookkeeping/ledger/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-bookkeeping/ledger/public-api.ts b/projects/ngx-bookkeeping/ledger/public-api.ts new file mode 100644 index 0000000..9560854 --- /dev/null +++ b/projects/ngx-bookkeeping/ledger/public-api.ts @@ -0,0 +1 @@ +export * from './ledger.component'; diff --git a/projects/ngx-bookkeeping/locale/messages.de.xlf b/projects/ngx-bookkeeping/locale/messages.de.xlf new file mode 100644 index 0000000..f7ef819 --- /dev/null +++ b/projects/ngx-bookkeeping/locale/messages.de.xlf @@ -0,0 +1,1283 @@ + + + + + + Cancel + Abbrechen + + + Close fiscal year + Geschäftsjahr abschließen + + + This can't be undone. + Das kann nicht rückgängig gemacht werden. + + + Nothing can be posted into it afterwards. Its balance sheet and income statement are archived as they are, and the next fiscal year opens with its balances. + Danach kann nichts mehr in das Geschäftsjahr gebucht werden. Seine Bilanz und seine Gewinn- und Verlustrechnung werden so archiviert, wie sie sind, und das nächste Geschäftsjahr wird mit seinen Salden eröffnet. + + + Close this fiscal year? + Dieses Geschäftsjahr abschließen? + + + Account + Konto + + + Balance + Saldo + + + Cancel + Abbrechen + + + Credit + Haben + + + Cr + H + + + Debit + Soll + + + Dr + S + + + Document date + Belegdatum + + + Document number + Belegnummer + + + The file couldn't be downloaded. Please try again. + Die Datei konnte nicht heruntergeladen werden. Bitte versuchen Sie es erneut. + + + Download as PDF + Als PDF herunterladen + + + Entry + Buchung + + + Entry + Buchung + + + Fiscal year + Geschäftsjahr + + + Loading the books + Die Buchhaltung wird geladen + + + The books couldn't be loaded. + Die Buchhaltung konnte nicht geladen werden. + + + The books have no fiscal year yet. + Die Buchhaltung hat noch kein Geschäftsjahr. + + + Period + Zeitraum + + + Until + Bis + + + The whole fiscal year when empty + Leer für das ganze Geschäftsjahr + + + From + Von + + + Posting date + Buchungsdatum + + + The request couldn't be sent. Please try again. + Die Anfrage konnte nicht gesendet werden. Bitte versuchen Sie es erneut. + + + Text + Buchungstext + + + Total + Summe + + + Account mappings + Kontenzuordnungen + + + An account reports as the position of the taxonomy its statement position stands for, or as a position of its own it is mapped to here. A mapping counts for every fiscal year not prepared yet. + Ein Konto wird unter der Position der Taxonomie übermittelt, für die seine Bilanzposition steht, oder unter einer eigenen Position, der es hier zugeordnet wird. Eine Zuordnung gilt für jedes Geschäftsjahr, das noch nicht aufbereitet ist. + + + Position of a credit balance + Position bei Habensaldo + + + The position while its balance is a credit, the one above when empty + Die Position, solange sein Saldo im Haben steht, leer für die Position oben + + + Edit + Bearbeiten + + + Edit the mapping of + Zuordnung von bearbeiten + + + The account mappings couldn't be loaded. + Die Kontenzuordnungen konnten nicht geladen werden. + + + Map + Zuordnen + + + Map an account + Ein Konto zuordnen + + + Map + zuordnen + + + was mapped. Preview the E-Bilanz again to see what it states now. + wurde zugeordnet. Zeigen Sie die Vorschau der E-Bilanz erneut, um zu sehen, was sie jetzt enthält. + + + Accounts mapped to a position of their own + Konten mit einer eigenen Position + + + No account is mapped to a position of its own. + Kein Konto ist einer eigenen Position zugeordnet. + + + Position + Position + + + The element name of the position in the taxonomy, like bs.ass.currAss.cashEquiv.bank + Der Elementname der Position in der Taxonomie, wie bs.ass.currAss.cashEquiv.bank + + + Remove + Entfernen + + + Remove the mapping of + Zuordnung von entfernen + + + The mapping of was removed. + Die Zuordnung von wurde entfernt. + + + Save the mapping + Zuordnung speichern + + + Accounts that need a position + Konten, die eine Position brauchen + + + ELSTER certificate + ELSTER-Zertifikat + + + The transmitter signs the E-Bilanz with the certificate of the company. Whoever has it and its PIN signs for the company, so upload a certificate of its own for the app, and a new one after each renewal in Mein ELSTER. + Der Übermittler signiert die E-Bilanz mit dem Zertifikat des Unternehmens. Wer es und seine PIN hat, unterschreibt für das Unternehmen. Laden Sie daher ein eigenes Zertifikat für die App hoch, und nach jeder Verlängerung in Mein ELSTER ein neues. + + + Certificate + Zertifikat + + + The .pfx file of Mein ELSTER + Die .pfx-Datei aus Mein ELSTER + + + Whether a certificate is uploaded couldn't be loaded. + Ob ein Zertifikat hochgeladen ist, konnte nicht geladen werden. + + + No certificate is uploaded. + Es ist kein Zertifikat hochgeladen. + + + PIN + PIN + + + It is stored encrypted and never shown again. + Sie wird verschlüsselt gespeichert und nie wieder angezeigt. + + + Upload the certificate + Zertifikat hochladen + + + The certificate was uploaded. + Das Zertifikat wurde hochgeladen. + + + A certificate was uploaded on . + Ein Zertifikat wurde am hochgeladen. + + + A tax balance sheet of its own (Steuerbilanz) + Eine eigene Steuerbilanz + + + The commercial balance sheet, which is the tax balance sheet as well (Einheitsbilanz) + Die Handelsbilanz, die zugleich die Steuerbilanz ist (Einheitsbilanz) + + + Filed, being corrected + Eingereicht, wird berichtigt + + + To correct it, reopen the fiscal year, post the corrections and close it again. The E-Bilanz then asks for a correction here. + Um sie zu berichtigen, eröffnen Sie das Geschäftsjahr wieder, buchen Sie die Korrekturen und schließen Sie es erneut ab. Die E-Bilanz fragt dann hier nach einer Berichtigung. + + + The books, or what the E-Bilanz states beside them, changed since it was filed. Prepare a correction: choose what it corrects, preview and prepare it, send it as a test, and file it again. + Die Bücher oder die Angaben der E-Bilanz neben den Büchern haben sich geändert, seit sie eingereicht wurde. Bereiten Sie eine Berichtigung auf: Wählen Sie, was sie berichtigt, zeigen Sie die Vorschau an und bereiten Sie sie auf, senden Sie sie als Test und reichen Sie sie erneut ein. + + + To be filed by + Einzureichen bis + + + E-Bilanz + E-Bilanz + + + Send or file by hand + Senden oder manuell einreichen + + + Filed + Eingereicht + + + Filing + Einreichen + + + The E-Bilanz couldn't be loaded. + Die E-Bilanz konnte nicht geladen werden. + + + The E-Bilanz was marked as filed by hand on . Its transmission protocol is in the records. + Die E-Bilanz wurde am als manuell eingereicht markiert. Ihr Übertragungsprotokoll ist bei den Vorgängen. + + + No fiscal year is closed yet. The E-Bilanz states a fiscal year once it is closed. + Es ist noch kein Geschäftsjahr abgeschlossen. Die E-Bilanz enthält ein Geschäftsjahr, sobald es abgeschlossen ist. + + + You may read the E-Bilanz, but not send it, download it or mark it as filed. + Sie dürfen die E-Bilanz lesen, aber nicht senden, herunterladen oder als eingereicht markieren. + + + Not prepared + Nicht aufbereitet + + + Prepare the E-Bilanz first. + Bereiten Sie die E-Bilanz zuerst auf. + + + Prepared before the books changed + Vor einer Änderung der Bücher aufbereitet + + + The books changed since the E-Bilanz was prepared. Prepare it again. + Die Bücher haben sich geändert, seit die E-Bilanz aufbereitet wurde. Bereiten Sie sie erneut auf. + + + Prepare + Aufbereiten + + + Prepared + Aufbereitet + + + Review + Prüfen + + + Show the records + Vorgänge anzeigen + + + Steps of filing the E-Bilanz + Schritte zum Einreichen der E-Bilanz + + + Test + Test + + + The E-Bilanz was sent to the tax administration on and accepted, with the ticket . + Die E-Bilanz wurde am an die Finanzverwaltung gesendet und angenommen, mit dem Ticket . + + + Sending also needs the ELSTER certificate of the company, which isn't uploaded yet: upload it under ELSTER certificate. + Zum Senden wird außerdem das ELSTER-Zertifikat des Unternehmens gebraucht, das noch nicht hochgeladen ist: Laden Sie es unter ELSTER-Zertifikat hoch. + + + Mark as filed + Als eingereicht markieren + + + It did not arrive + Sie ist nicht angekommen + + + Send for real + Verbindlich senden + + + Download the E-Bilanz + E-Bilanz herunterladen + + + Download (.) + herunterladen (.) + + + Sending failed, and nothing reached the tax administration, so it can be sent again. What failed: + Das Senden ist fehlgeschlagen, und nichts hat die Finanzverwaltung erreicht, sie kann also erneut gesendet werden. Was fehlgeschlagen ist: + + + The E-Bilanz is filed as it was prepared. + Die E-Bilanz ist so eingereicht, wie sie aufbereitet wurde. + + + Nothing is ever sent by itself: each of these happens once you press its button. Send the E-Bilanz from here, or download it, file it with another program and mark it as filed. + Nichts wird jemals von selbst gesendet: Jeder dieser Schritte geschieht erst, wenn Sie seine Schaltfläche drücken. Senden Sie die E-Bilanz von hier, oder laden Sie sie herunter, reichen Sie sie mit einem anderen Programm ein und markieren Sie sie als eingereicht. + + + Mark as filed by hand + Als manuell eingereicht markieren + + + Upload the transmission protocol of the program you filed it with. It is archived with the record, and the E-Bilanz as it was prepared counts as filed. + Laden Sie das Übertragungsprotokoll des Programms hoch, mit dem Sie sie eingereicht haben. Es wird mit dem Vorgang archiviert, und die E-Bilanz gilt so, wie sie aufbereitet wurde, als eingereicht. + + + Mark the E-Bilanz as filed by hand? + Die E-Bilanz als manuell eingereicht markieren? + + + File it by hand + Manuell einreichen + + + The E-Bilanz was marked as filed by hand. + Die E-Bilanz wurde als manuell eingereicht markiert. + + + It can't be downloaded: this app can't write the E-Bilanz as a file. To download it, ask your administrator to set up the download. + Sie kann nicht heruntergeladen werden: Diese App kann die E-Bilanz nicht als Datei schreiben. Um sie herunterzuladen, bitten Sie Ihren Administrator, das Herunterladen einzurichten. + + + Sending isn't set up in this app. Download the file, file it with another program and mark it as filed here. To send from here, ask your administrator to set up sending. + Das Senden ist in dieser App nicht eingerichtet. Laden Sie die Datei herunter, reichen Sie sie mit einem anderen Programm ein und markieren Sie sie hier als eingereicht. Um von hier zu senden, bitten Sie Ihren Administrator, das Senden einzurichten. + + + ELSTER did not receive it + ELSTER hat sie nicht erhalten + + + If it did arrive, sending it again files it twice. You may be asked for your second factor. + Ist sie doch angekommen, wird sie durch erneutes Senden doppelt eingereicht. Eventuell werden Sie nach Ihrem zweiten Faktor gefragt. + + + Recorded that ELSTER did not receive it. It can be sent again. + Es wurde festgehalten, dass ELSTER sie nicht erhalten hat. Sie kann erneut gesendet werden. + + + Only confirm this once you checked in ELSTER that it did not arrive. Each transmission whose result isn't known is then recorded as not received, and the E-Bilanz can be sent again. + Bestätigen Sie das erst, wenn Sie in ELSTER geprüft haben, dass sie nicht angekommen ist. Jede Übermittlung, deren Ergebnis nicht bekannt ist, wird dann als nicht erhalten festgehalten, und die E-Bilanz kann erneut gesendet werden. + + + ELSTER did not receive it? + Hat ELSTER sie nicht erhalten? + + + Transmission protocol + Übertragungsprotokoll + + + Like the pdf the program wrote + Wie die PDF, die das Programm geschrieben hat + + + It is being sent to ELSTER right now. Wait for the result, which shows above. + Sie wird gerade an ELSTER gesendet. Warten Sie auf das Ergebnis, das oben erscheint. + + + Send it from here + Von hier senden + + + Sending to ELSTER started. + Das Senden an ELSTER hat begonnen. + + + This can take several minutes. You can leave this page; the result is recorded. + Das kann mehrere Minuten dauern. Sie können diese Seite verlassen; das Ergebnis wird festgehalten. + + + Sending to ELSTER… + Wird an ELSTER gesendet … + + + Filing it by hand with another program? Go on without a test. + Sie reichen sie mit einem anderen Programm ein? Dann gehen Sie ohne Test weiter. + + + The test was accepted. The E-Bilanz can be sent for real now. + Der Test wurde angenommen. Die E-Bilanz kann jetzt verbindlich gesendet werden. + + + The test was refused. The tax administration answered: + Der Test wurde abgelehnt. Die Finanzverwaltung hat geantwortet: + + + A test goes to the tax administration like the real transmission, which checks it and keeps nothing. The E-Bilanz can be sent for real once a test of the same content was accepted. + Ein Test geht wie die echte Übermittlung an die Finanzverwaltung, die ihn prüft und nichts davon behält. Die E-Bilanz kann verbindlich gesendet werden, sobald ein Test desselben Inhalts angenommen wurde. + + + Send as a test + Als Test senden + + + Send to the tax administration + An die Finanzverwaltung senden + + + This sends the E-Bilanz of , tax number , for the fiscal year , as it was prepared on . + Damit wird die E-Bilanz von , Steuernummer , für das Geschäftsjahr gesendet, so wie sie am aufbereitet wurde. + + + This is final: the tax administration keeps what it receives, and it can't be taken back. You may be asked for your second factor before it is sent. + Das ist endgültig: Die Finanzverwaltung behält, was sie erhält, und es kann nicht zurückgenommen werden. Vor dem Senden werden Sie eventuell nach Ihrem zweiten Faktor gefragt. + + + The transmission was refused. The tax administration answered: + Die Übermittlung wurde abgelehnt. Die Finanzverwaltung hat geantwortet: + + + It states positions in the version of the taxonomy, with the accounts of each position and the statement of changes in fixed assets. Its balance sheet: . + Sie enthält Positionen in der Version der Taxonomie, mit den Konten jeder Position und dem Anlagenspiegel. Ihre Bilanz: . + + + Its test was accepted on , with the ticket . + Ihr Test wurde am mit dem Ticket angenommen. + + + Send the E-Bilanz to the tax administration? + Die E-Bilanz an die Finanzverwaltung senden? + + + The E-Bilanz was sent and accepted, with the ticket . + Die E-Bilanz wurde gesendet und angenommen, mit dem Ticket . + + + If it arrived, mark it as filed by hand with the transmission protocol of ELSTER. If it didn't arrive, say so here, and it can be sent again. + Ist sie angekommen, markieren Sie sie mit dem Übertragungsprotokoll von ELSTER als manuell eingereicht. Ist sie nicht angekommen, geben Sie das hier an, dann kann sie erneut gesendet werden. + + + It may have been sent already. Check in ELSTER whether it arrived, then mark it as filed by hand or say that ELSTER didn't receive it. + Sie wurde möglicherweise schon gesendet. Prüfen Sie in ELSTER, ob sie angekommen ist, und markieren Sie sie dann als manuell eingereicht oder geben Sie an, dass ELSTER sie nicht erhalten hat. + + + The test started on may have reached ELSTER. + Der am begonnene Test hat ELSTER möglicherweise erreicht. + + + It may have been sent. Check in ELSTER whether it arrived before you do anything else. + Sie wurde möglicherweise gesendet. Prüfen Sie in ELSTER, ob sie angekommen ist, bevor Sie irgendetwas anderes tun. + + + The result isn't known + Das Ergebnis ist nicht bekannt + + + The transmission started on may have reached ELSTER. + Die am begonnene Übermittlung hat ELSTER möglicherweise erreicht. + + + Send it as a test first: it can be sent for real once a test of the same content was accepted. + Senden Sie sie zuerst als Test: Verbindlich gesendet werden kann sie, sobald ein Test desselben Inhalts angenommen wurde. + + + Balance sheet + Bilanz + + + Which balance sheet the E-Bilanz states. Both are legitimate, so choose the one your books are kept for. + Welche Bilanz die E-Bilanz enthält. Beide sind zulässig, wählen Sie also die, für die Ihre Bücher geführt werden. + + + Choose the balance sheet first. + Wählen Sie zuerst die Bilanz. + + + Figures of + Werte von + + + Figures of the statement of changes in fixed assets + Werte des Anlagenspiegels + + + The books don't hold these figures of the positions the findings name. Enter the ones that apply, then preview again. + Diese Werte der Positionen, die die Hinweise nennen, enthalten die Bücher nicht. Geben Sie die zutreffenden ein und zeigen Sie dann erneut die Vorschau. + + + The preview shows the E-Bilanz as the books state it, with what it needs, and keeps nothing. Prepare it once it needs nothing more: the preparation is archived, and it is what an export and a transmission send. + Die Vorschau zeigt die E-Bilanz, wie die Bücher sie ergeben, mit dem, was ihr fehlt, und speichert nichts. Bereiten Sie sie auf, sobald ihr nichts mehr fehlt: Die Aufbereitung wird archiviert, und sie ist es, die ein Export und eine Übermittlung senden. + + + Prepare + Aufbereiten + + + The E-Bilanz was prepared. Review it, then send it as a test or file it by hand. + Die E-Bilanz wurde aufbereitet. Prüfen Sie sie, dann senden Sie sie als Test oder reichen Sie sie manuell ein. + + + Preview + Vorschau + + + It can be prepared once it needs nothing more. + Sie kann aufbereitet werden, sobald ihr nichts mehr fehlt. + + + Preview it first, with the balance sheet and the figures above. + Zeigen Sie zuerst die Vorschau, mit der Bilanz und den Werten oben. + + + The preview shows the E-Bilanz as the books state it now. + Die Vorschau zeigt die E-Bilanz, wie die Bücher sie jetzt ergeben. + + + What the correction corrects + Was die Berichtigung berichtigt + + + Nothing was wrong, but a choice the law allows is made differently now, like how an asset is valued (geändert, § 4 (2) sentence 2 EStG). + Nichts war falsch, aber ein Wahlrecht, das das Gesetz lässt, wird jetzt anders ausgeübt, etwa wie ein Vermögensgegenstand bewertet wird (Bilanzänderung, § 4 Abs. 2 Satz 2 EStG). + + + The balance sheet or the income statement had an error, which is fixed now (berichtigt, § 4 (2) sentence 1 EStG). + Die Bilanz oder die Gewinn- und Verlustrechnung enthielt einen Fehler, der jetzt behoben ist (Bilanzberichtigung, § 4 Abs. 2 Satz 1 EStG). + + + An error is fixed, and a choice is made differently as well (berichtigt und geändert). + Ein Fehler ist behoben, und zusätzlich wird ein Wahlrecht anders ausgeübt (berichtigt und geändert). + + + The same figures as filed, only with more detail, like the accounts of each position. + Dieselben Zahlen wie eingereicht, nur ausführlicher, etwa mit den Konten jeder Position. + + + Only something outside the balance sheet and the income statement changed, like the details of the company (sonstige Korrektur). + Geändert hat sich nur etwas außerhalb der Bilanz und der Gewinn- und Verlustrechnung, etwa die Angaben zum Unternehmen (sonstige Korrektur). + + + The E-Bilanz of this fiscal year is filed, so this one corrects it. Tell the tax administration what changed. + Die E-Bilanz dieses Geschäftsjahres ist eingereicht, diese hier berichtigt sie also. Teilen Sie der Finanzverwaltung mit, was sich geändert hat. + + + Choose what the correction corrects first. + Wählen Sie zuerst, was die Berichtigung berichtigt. + + + A choice changed + Ein Wahlrecht geändert + + + Errors corrected + Fehler berichtigt + + + Both + Beides + + + Only more detail + Nur ausführlicher + + + Another correction + Eine andere Korrektur + + + Corrects the record "" of : + Berichtigt den Vorgang „“ vom : + + + Download + herunterladen + + + Record + Vorgang + + + Filed by hand + Manuell eingereicht + + + Prepared + Aufbereitet + + + Test transmission + Testübermittlung + + + Transmission + Übermittlung + + + Messages + Meldungen + + + Nothing was prepared or filed yet. + Bisher wurde nichts aufbereitet oder eingereicht. + + + Protocol + Protokoll + + + Recorded + Erfasst + + + Records + Vorgänge + + + Result + Ergebnis + + + Accepted + Angenommen + + + Failed + Fehlgeschlagen + + + Not received, as confirmed + Nicht erhalten, wie bestätigt + + + Refused + Abgelehnt + + + Started + Begonnen + + + Result not known + Ergebnis nicht bekannt + + + Ticket + Ticket + + + Balance sheet + Bilanz + + + Amount + Betrag + + + Company + Unternehmen + + + What the E-Bilanz needs + Was der E-Bilanz fehlt + + + Each of these needs to change before the E-Bilanz can be prepared. + Jeder dieser Punkte muss geändert werden, bevor die E-Bilanz aufbereitet werden kann. + + + Statement of changes in fixed assets + Anlagenspiegel + + + NIL + NIL + + + NIL marks a position the tax administration asks for that the books don't state, which isn't 0. + NIL kennzeichnet eine Position, die die Finanzverwaltung verlangt und die die Bücher nicht enthalten. Das ist nicht 0. + + + The E-Bilanz isn't prepared yet. Choose its balance sheet and preview it. + Die E-Bilanz ist noch nicht aufbereitet. Wählen Sie ihre Bilanz und zeigen Sie die Vorschau. + + + The E-Bilanz states no fixed assets. + Die E-Bilanz enthält kein Anlagevermögen. + + + Position + Position + + + As prepared on . + So, wie sie am aufbereitet wurde. + + + A preview, as the books state it now. It isn't prepared. + Eine Vorschau, wie die Bücher sie jetzt ergeben. Sie ist nicht aufbereitet. + + + Appropriation of profits + Ergebnisverwendung + + + Balance sheet + Bilanz + + + Income statement + Gewinn- und Verlustrechnung + + + Income statement of a micro corporation + Gewinn- und Verlustrechnung einer Kleinstkapitalgesellschaft + + + Tax number + Steuernummer + + + Version of the taxonomy + Version der Taxonomie + + + The whole E-Bilanz + Die ganze E-Bilanz + + + Add a line + Zeile hinzufügen + + + Enter a debit or a credit. + Geben Sie einen Soll- oder einen Haben-Betrag ein. + + + Enter either a debit or a credit, not both. + Geben Sie entweder einen Soll- oder einen Haben-Betrag ein, nicht beide. + + + Difference + Differenz + + + Like the number of the invoice + Etwa die Nummer der Rechnung + + + Line + Zeile + + + Lines + Zeilen + + + Post entry + Buchen + + + Entry was posted. + Buchung wurde gebucht. + + + Remove + Entfernen + + + Remove line + Zeile entfernen + + + What was booked, like "Rent March" + Was gebucht wurde, etwa „Miete März“ + + + Credits + Haben + + + Debits + Soll + + + The debits and the credits differ by . An entry is posted once both are equal. + Soll und Haben weichen um voneinander ab. Eine Buchung wird gebucht, sobald beide gleich sind. + + + Add a fiscal year + Geschäftsjahr hinzufügen + + + The fiscal year was added. + Das Geschäftsjahr wurde hinzugefügt. + + + Average number of employees + Durchschnittliche Zahl der Arbeitnehmer + + + During the fiscal year, like 2.5, for the size class of a corporation + Im Geschäftsjahr, etwa 2,5, für die Größenklasse einer Kapitalgesellschaft + + + Note below the balance sheet + Angaben unter der Bilanz + + + Stated below the balance sheet where the fiscal year states one, like that of a micro corporation + Werden unter der Bilanz angegeben, wo das Geschäftsjahr welche angibt, etwa bei einer Kleinstkapitalgesellschaft + + + Before this fiscal year + Vor diesem Geschäftsjahr + + + What the company was on the balance sheet date before the first fiscal year of the books + Was das Unternehmen am Abschlussstichtag vor dem ersten Geschäftsjahr der Buchhaltung war + + + Close fiscal year + Geschäftsjahr abschließen + + + The fiscal year was closed on . Nothing can be posted into it or changed unless it is reopened. + Das Geschäftsjahr wurde am abgeschlossen. Es kann nichts mehr hineingebucht oder geändert werden, außer es wird wieder geöffnet. + + + Closed on + Abgeschlossen am + + + The fiscal year was closed, and the fiscal year opened with its balances. + Das Geschäftsjahr wurde abgeschlossen, und das Geschäftsjahr wurde mit seinen Salden eröffnet. + + + Closing + Abschluss + + + For the statements + Für die Abschlüsse + + + Download the export + Export herunterladen + + + End + Ende + + + Export for a tax audit + Export für eine Betriebsprüfung + + + The fiscal year is open, so entries posted into it later are not in the export. Export it once it is closed. + Das Geschäftsjahr ist offen, später hineingebuchte Buchungen fehlen also im Export. Exportieren Sie es, sobald es abgeschlossen ist. + + + A zip archive of the accounts and the entries of the fiscal year, in the format the software of a tax audit reads. + Ein ZIP-Archiv der Konten und Buchungen des Geschäftsjahres, in dem Format, das die Software einer Betriebsprüfung liest. + + + Downloading the export + Der Export wird heruntergeladen + + + The end of its calendar year when empty, or an earlier day for a short first year + Leer für das Ende seines Kalenderjahres, oder ein früherer Tag für ein kurzes erstes Geschäftsjahr + + + The first day of the books + Der erste Tag der Buchhaltung + + + Fiscal year + Geschäftsjahr + + + Fiscal years + Geschäftsjahre + + + This reopening is to correct the filed E-Bilanz + Diese Wiedereröffnung dient der Berichtigung der eingereichten E-Bilanz + + + The accounts of this year are filed already, like an E-Bilanz, and this reopening is to correct them + Der Abschluss dieses Jahres ist bereits eingereicht, etwa als E-Bilanz, und diese Wiedereröffnung dient seiner Berichtigung + + + Founded in this fiscal year + In diesem Geschäftsjahr gegründet + + + It ends on , a year after its start, when empty + Leer endet es am , ein Jahr nach seinem Beginn + + + It starts on , the day after the last fiscal year. + Es beginnt am , dem Tag nach dem letzten Geschäftsjahr. + + + No entry is proposed before closing. + Vor dem Abschluss wird keine Buchung vorgeschlagen. + + + Open + Offen + + + Post + Buchen + + + Post "" + „“ buchen + + + Lines of "" + Zeilen von „“ + + + The proposed entry was posted as entry . + Die vorgeschlagene Buchung wurde als Buchung gebucht. + + + The entries proposed before closing couldn't be loaded. + Die vor dem Abschluss vorgeschlagenen Buchungen konnten nicht geladen werden. + + + The rules of the law the books are held to propose these entries before the fiscal year is closed. Post each of them, then close the year. + Die Regeln des Rechts, nach dem die Bücher geführt werden, schlagen diese Buchungen vor dem Abschluss des Geschäftsjahres vor. Buchen Sie jede von ihnen und schließen Sie danach das Jahr ab. + + + Proposed by + Vorgeschlagen von + + + Reopen fiscal year + Geschäftsjahr wiedereröffnen + + + The E-Bilanz of this fiscal year is filed with the tax administration. The year may only be reopened to correct it: once it is closed again, prepare a correction of the E-Bilanz and file it again. + Die E-Bilanz dieses Geschäftsjahres ist bei der Finanzverwaltung eingereicht. Das Jahr darf nur wiedereröffnet werden, um sie zu berichtigen: Sobald es erneut abgeschlossen ist, bereiten Sie eine Berichtigung der E-Bilanz auf und reichen sie erneut ein. + + + Nothing is deleted: the entries of the closing stay in the journal next to their reversals, and the statements archived at the closing stay archived. You may be asked for your second factor. + Nichts wird gelöscht: Die Buchungen des Abschlusses bleiben neben ihren Stornos im Journal, und die beim Abschluss archivierten Abschlüsse bleiben archiviert. Eventuell werden Sie nach Ihrem zweiten Faktor gefragt. + + + Reason + Grund + + + Why the fiscal year is reopened, like the error to correct. It is the text of the reversing entries. + Warum das Geschäftsjahr wiedereröffnet wird, etwa der zu berichtigende Fehler. Er ist der Buchungstext der Stornobuchungen. + + + Reopening reverses its closing: the fiscal year is open again, you can post corrections into it, and then close it again. The opening balances of the next fiscal year are reversed as well, and posted again when you close it. + Die Wiedereröffnung storniert seinen Abschluss: Das Geschäftsjahr ist wieder offen, Sie können Korrekturen hineinbuchen und es danach erneut abschließen. Die Eröffnungssalden des nächsten Geschäftsjahres werden ebenfalls storniert und beim erneuten Abschluss wieder gebucht. + + + Reopen the fiscal year ? + Das Geschäftsjahr wiedereröffnen? + + + The fiscal year was reopened. Post the corrections, then close it again. + Das Geschäftsjahr wurde wiedereröffnet. Buchen Sie die Korrekturen und schließen Sie es danach erneut ab. + + + Result account + Ergebniskonto + + + The equity account the result of the year is carried into + Das Eigenkapitalkonto, auf das das Ergebnis des Jahres vorgetragen wird + + + Save + Speichern + + + The fiscal year was saved. + Das Geschäftsjahr wurde gespeichert. + + + Start + Beginn + + + Status + Status + + + With the documents + Mit den Belegen + + + The invoices, receipts, bank statements and archived statements behind the entries + Die Rechnungen, Belege, Kontoauszüge und archivierten Abschlüsse hinter den Buchungen + + + All accounts + Alle Konten + + + Reverse + Stornieren + + + Lines of entry + Zeilen der Buchung + + + No entry matches the filters. + Keine Buchung entspricht den Filtern. + + + Pages of the journal + Seiten des Journals + + + Reversal + Storno + + + Reverses entry + Storniert Buchung + + + Posting date of the reversal + Buchungsdatum des Stornos + + + A day of an open fiscal year + Ein Tag eines offenen Geschäftsjahres + + + Reason + Grund + + + The text of the reversal, like "Booked on the wrong account" + Der Buchungstext des Stornos, etwa „Auf das falsche Konto gebucht“ + + + The reversal posts the lines of the entry with debit and credit swapped. The entry itself stays in the journal as it is. This can't be undone. + Das Storno bucht die Zeilen der Buchung mit vertauschtem Soll und Haben. Die Buchung selbst bleibt unverändert im Journal. Das kann nicht rückgängig gemacht werden. + + + Reverse entry ? + Buchung stornieren? + + + Reverse + Stornieren + + + Reverse entry + Buchung stornieren + + + Entry was reversed by entry . + Buchung wurde durch Buchung storniert. + + + Reversed by entry + Storniert durch Buchung + + + Reversed + Storniert + + + Credits of the period + Haben des Zeitraums + + + Debits of the period + Soll des Zeitraums + + + Choose an account to see what was booked on it. + Wählen Sie ein Konto, um zu sehen, was darauf gebucht wurde. + + + Closing balance + Schlusssaldo + + + Nothing was booked on the account in the period. + Im Zeitraum wurde nichts auf das Konto gebucht. + + + Opening balance + Anfangssaldo + + + Ledger of + Kontoblatt von + + + Cancel + Abbrechen + + + Post + Buchen + + + It is posted into the books as it is proposed. A posted entry is only corrected by reversing it. + Sie wird so in die Bücher gebucht, wie sie vorgeschlagen ist. Eine gebuchte Buchung wird nur durch ein Storno korrigiert. + + + Post this entry? + Diese Buchung buchen? + + + Existed before as a large corporation + Bestand bereits als große Kapitalgesellschaft + + + Existed before as a medium-sized corporation + Bestand bereits als mittelgroße Kapitalgesellschaft + + + Existed before as a micro corporation + Bestand bereits als Kleinstkapitalgesellschaft + + + Existed before as a small corporation + Bestand bereits als kleine Kapitalgesellschaft + + + (the form of the fiscal year) + (die Form des Geschäftsjahres) + + + Final + Endgültig + + + The fiscal year is closed. This is the statement archived at its closing. + Das Geschäftsjahr ist abgeschlossen. Dies ist der bei seinem Abschluss archivierte Abschluss. + + + Form + Form + + + Position + Posten + + + Preliminary + Vorläufig + + + The fiscal year is open, so its figures can still change. + Das Geschäftsjahr ist offen, seine Zahlen können sich also noch ändern. + + + Result of the fiscal year + Ergebnis des Geschäftsjahres + + + Accounts without a position + Konten ohne Posten + + + These accounts have a balance but no position in this statement, so none of its positions holds them. Map each of them to a position. + Diese Konten haben einen Saldo, aber keinen Posten in diesem Abschluss, sodass keiner seiner Posten sie enthält. Ordnen Sie jedes von ihnen einem Posten zu. + + + Credit balance + Saldo Haben + + + Debit balance + Saldo Soll + + + Nothing was booked in the fiscal year until then. + Bis dahin wurde im Geschäftsjahr nichts gebucht. + + + No. + Nr. + + + Trial balance of until + Summen- und Saldenliste bis + + + Until + Bis + + + The last day whose entries count, the end of the fiscal year when empty + Der letzte Tag, dessen Buchungen zählen, leer für das Ende des Geschäftsjahres + + + + diff --git a/projects/ngx-bookkeeping/ng-package.json b/projects/ngx-bookkeeping/ng-package.json new file mode 100644 index 0000000..d4cfd05 --- /dev/null +++ b/projects/ngx-bookkeeping/ng-package.json @@ -0,0 +1,8 @@ +{ + "$schema": "../../node_modules/ng-packagr/ng-package.schema.json", + "assets": ["tailwind.css", "locale/messages.de.xlf", "CHANGELOG.md"], + "dest": "../../dist/ngx-bookkeeping", + "lib": { + "entryFile": "src/public-api.ts" + } +} diff --git a/projects/ngx-bookkeeping/package.json b/projects/ngx-bookkeeping/package.json new file mode 100644 index 0000000..ff2d84d --- /dev/null +++ b/projects/ngx-bookkeeping/package.json @@ -0,0 +1,36 @@ +{ + "name": "@service-soft/ngx-bookkeeping", + "version": "22.4.0", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/Service-Soft/angular-libraries.git", + "directory": "projects/ngx-bookkeeping" + }, + "publishConfig": { + "access": "public" + }, + "dependencies": { + "tslib": "^2.3.0" + }, + "exports": { + ".": { + "style": "./tailwind.css" + } + }, + "peerDependencies": { + "@angular/aria": "^22.2.0", + "@angular/common": "^22.2.0", + "@angular/core": "^22.2.0", + "@angular/localize": "^22.2.0", + "@service-soft/ngx-error-handling": "^22.4.0", + "@service-soft/ui": "^22.4.0", + "rxjs": "^7.8.0", + "tailwindcss": "^4.3.3", + "zibri-contract": "^3.3.0" + }, + "sideEffects": false, + "translations": { + "de": "./locale/messages.de.xlf" + } +} diff --git a/projects/ngx-bookkeeping/src/public-api.ts b/projects/ngx-bookkeeping/src/public-api.ts new file mode 100644 index 0000000..c95b950 --- /dev/null +++ b/projects/ngx-bookkeeping/src/public-api.ts @@ -0,0 +1,4 @@ +/** + * Every view lives in its own secondary entry point, eg. '@service-soft/ngx-bookkeeping/journal'. + */ +export {}; diff --git a/projects/ngx-bookkeeping/statement/ng-package.json b/projects/ngx-bookkeeping/statement/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-bookkeeping/statement/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-bookkeeping/statement/public-api.ts b/projects/ngx-bookkeeping/statement/public-api.ts new file mode 100644 index 0000000..c4ef3fc --- /dev/null +++ b/projects/ngx-bookkeeping/statement/public-api.ts @@ -0,0 +1 @@ +export * from './statement.component'; diff --git a/projects/ngx-bookkeeping/statement/statement-position-view.model.ts b/projects/ngx-bookkeeping/statement/statement-position-view.model.ts new file mode 100644 index 0000000..8d818fa --- /dev/null +++ b/projects/ngx-bookkeeping/statement/statement-position-view.model.ts @@ -0,0 +1,25 @@ +/** + * A position of a statement as it shows. + */ +export type StatementPositionView = { + /** + * The id of the position. + */ + id: string, + /** + * What the position is called. + */ + label: string, + /** + * The classes of the cell of its label: indented by its depth, and bold for a position with positions below it. + */ + labelClasses: string, + /** + * Its amount, formatted. + */ + amount: string, + /** + * Its amount in the fiscal year before, formatted, or an empty string for a statement without one. + */ + previousAmount: string +}; diff --git a/projects/ngx-bookkeeping/statement/statement-table.component.html b/projects/ngx-bookkeeping/statement/statement-table.component.html new file mode 100644 index 0000000..43beab4 --- /dev/null +++ b/projects/ngx-bookkeeping/statement/statement-table.component.html @@ -0,0 +1,26 @@ + +
+ + + + + + + @if (statement().previousLabel; as previousLabel) { + + } + + + + @for (position of statement().positions; track position.id) { + + + + @if (statement().previousLabel) { + + } + + } + +
{{ statement().label }}
{{ labels.position }}{{ statement().currentLabel }}{{ previousLabel }}
{{ position.label }}{{ position.amount }}{{ position.previousAmount }}
+
diff --git a/projects/ngx-bookkeeping/statement/statement-table.component.ts b/projects/ngx-bookkeeping/statement/statement-table.component.ts new file mode 100644 index 0000000..17444b6 --- /dev/null +++ b/projects/ngx-bookkeeping/statement/statement-table.component.ts @@ -0,0 +1,29 @@ +import { Component, inject, input, InputSignal } from '@angular/core'; +import { BOOKKEEPING_CONFIG, BookkeepingConfig, BookkeepingStatementLabels } from '@service-soft/ngx-bookkeeping/api'; +import { ScrollRegionDirective } from '@service-soft/ui/scroll-region'; + +import { StatementView } from './statement-view.model'; + +/** + * The table of a statement: its positions in their order, each indented by its depth, with its amount and the one of + * the fiscal year before. Only used by the statement. + */ +@Component({ + selector: 'ngx-statement-table', + templateUrl: './statement-table.component.html', + imports: [ScrollRegionDirective], + host: { class: 'block' } +}) +export class StatementTableComponent { + private readonly config: BookkeepingConfig = inject(BOOKKEEPING_CONFIG); + + /** + * The statement. + */ + readonly statement: InputSignal = input.required(); + + /** + * The texts of the statements. + */ + protected readonly labels: BookkeepingStatementLabels = this.config.labels.statements; +} diff --git a/projects/ngx-bookkeeping/statement/statement-view.model.ts b/projects/ngx-bookkeeping/statement/statement-view.model.ts new file mode 100644 index 0000000..d8d5a26 --- /dev/null +++ b/projects/ngx-bookkeeping/statement/statement-view.model.ts @@ -0,0 +1,37 @@ +import { DataListItem } from '@service-soft/ui/data-list'; + +import { StatementPositionView } from './statement-position-view.model'; + +/** + * A balance sheet or an income statement as it shows. + */ +export type StatementView = { + /** + * What the form of the statement is called, the caption of its table. + */ + label: string, + /** + * Whether its fiscal year is closed, which makes it final. + */ + closed: boolean, + /** + * The header of the column of the fiscal year, like its last day. + */ + currentLabel: string, + /** + * The header of the column of the fiscal year before, or undefined for a statement without one. + */ + previousLabel: string | undefined, + /** + * Its positions, in their order. + */ + positions: StatementPositionView[], + /** + * The accounts with a balance in none of its positions, each its number and name with its amount. + */ + unmapped: DataListItem[], + /** + * The result of the fiscal year, formatted. + */ + result: string +}; diff --git a/projects/ngx-bookkeeping/statement/statement.component.html b/projects/ngx-bookkeeping/statement/statement.component.html new file mode 100644 index 0000000..0bf50eb --- /dev/null +++ b/projects/ngx-bookkeeping/statement/statement.component.html @@ -0,0 +1,32 @@ +
+ + @if (hasFormChoice()) { + + } +
+
+ +
+@if (alert(); as alert) { + +} +@if (hasNoFiscalYears()) { + +} @else { +
+ @if (view(); as view) { +
+ {{ view.closed ? labels.final : labels.preliminary }} +

{{ view.closed ? labels.finalNote : labels.preliminaryNote }}

+
+ + + @if (view.unmapped.length) { + +

{{ labels.unmappedText }}

+ +
+ } + } +
+} diff --git a/projects/ngx-bookkeeping/statement/statement.component.ts b/projects/ngx-bookkeeping/statement/statement.component.ts new file mode 100644 index 0000000..42ea0ce --- /dev/null +++ b/projects/ngx-bookkeeping/statement/statement.component.ts @@ -0,0 +1,212 @@ +import { Component, computed, input, InputSignal, linkedSignal, resource, ResourceRef, Signal, WritableSignal } from '@angular/core'; +import { BookkeepingFiscalYearUtilities, BookkeepingStatementLabels, BookkeepingViewDirective } from '@service-soft/ngx-bookkeeping/api'; +import { BadgeComponent } from '@service-soft/ui/badge'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { CalloutComponent } from '@service-soft/ui/callout'; +import { DataListComponent, DataListItem } from '@service-soft/ui/data-list'; +import { EmptyStateComponent } from '@service-soft/ui/empty-state'; +import { InputOption } from '@service-soft/ui/input'; +import { InputSelectComponent } from '@service-soft/ui/input-select'; +import { LoadingDirective } from '@service-soft/ui/loading'; +import { BookkeepingStatementFormChoiceModel, BookkeepingStatementFormChoicesModel, BookkeepingStatementModel, BookkeepingStatementPositionModel, BookkeepingStatementType, FiscalYearModel } from 'zibri-contract'; + +import { StatementPositionView } from './statement-position-view.model'; +import { StatementTableComponent } from './statement-table.component'; +import { StatementView } from './statement-view.model'; + +// the label of a position, indented by its depth below the top. Deeper positions keep the deepest indent. +const DEPTH_CLASSES: string[] = [ + 'py-2 pe-3 ps-3 text-start wrap-break-word', + 'py-2 pe-3 ps-7 text-start wrap-break-word', + 'py-2 pe-3 ps-11 text-start wrap-break-word', + 'py-2 pe-3 ps-15 text-start wrap-break-word', + 'py-2 pe-3 ps-19 text-start wrap-break-word', + 'py-2 pe-3 ps-23 text-start wrap-break-word' +]; + +// a position with positions below it adds them up, which reads best set apart from them. A header cell is bold +// otherwise. +const WEIGHT_CLASSES: Record<'sum' | 'position', string> = { sum: 'font-semibold', position: 'font-normal' }; + +/** + * The statement, the fiscal year and the form it shows. + */ +type StatementParams = { + /** + * Which statement. + */ + type: BookkeepingStatementType, + /** + * The id of the fiscal year. + */ + fiscalYearId: string, + /** + * The id of the form. + */ + form: string +}; + +/** + * A balance sheet or an income statement of the books of provideBookkeepingConfig, by its type: + * ``. It shows the positions of a fiscal year, the one of today at first, in + * their order, each indented by its depth, with its amount and the one of the fiscal year before, and the result of the + * year. It says whether the statement is final, as its year is closed, and shows every account with a balance in none + * of its positions. It shows the form that applies to the fiscal year, and the user chooses another of the forms the + * api has. The statement downloads as a pdf. The balance sheet and the income statement are this, with their type. + */ +@Component({ + selector: 'ngx-statement', + templateUrl: './statement.component.html', + imports: [ + BadgeComponent, + ButtonComponent, + CalloutComponent, + DataListComponent, + EmptyStateComponent, + InputSelectComponent, + LoadingDirective, + StatementTableComponent + ], + host: { class: 'block' } +}) +export class StatementComponent extends BookkeepingViewDirective { + /** + * Which statement it shows. + */ + readonly type: InputSignal = input.required(); + + /** + * The texts of the statements. + */ + protected readonly labels: BookkeepingStatementLabels = this.config.labels.statements; + + private readonly formChoices: ResourceRef = resource({ + params: () => this.fiscalYear()?.id, + loader: async ({ params }) => await this.bookkeepingService.resolveStatementFormChoices(params) + }); + + // the forms of the statement in the fiscal year that shows, undefined while they load, also for another fiscal year. + private readonly formChoice: Signal = computed(() => { + const choices: BookkeepingStatementFormChoicesModel | undefined = this.formChoices.hasValue() ? this.formChoices.value() : undefined; + if (choices == undefined || choices.fiscalYearId !== this.fiscalYear()?.id) { + return undefined; + } + return this.type() === BookkeepingStatementType.BALANCE_SHEET ? choices.balanceSheet : choices.incomeStatement; + }); + + /** + * The forms of the statement to choose from, the one that applies to the fiscal year marked. + */ + protected readonly formOptions: Signal[]> = computed(() => { + const choice: BookkeepingStatementFormChoiceModel | undefined = this.formChoice(); + return (choice?.forms ?? []).map(form => ({ + label: form.id === choice?.applies ? this.labels.applyingForm(form.name) : form.name, + value: form.id + })); + }); + + /** + * Whether there are forms to choose from: a statement with one form has no choice. + */ + protected readonly hasFormChoice: Signal = computed(() => this.formOptions().length > 1); + + /** + * The id of the form that shows: the one that applies to the fiscal year at first, and again with another fiscal + * year. Undefined while the forms load. + */ + protected readonly form: WritableSignal = linkedSignal(() => this.formChoice()?.applies); + + private readonly params: Signal = computed(() => { + const fiscalYearId: string | undefined = this.fiscalYear()?.id; + const form: string | undefined = this.form(); + return fiscalYearId == undefined || form == undefined ? undefined : { type: this.type(), fiscalYearId, form }; + }); + + /** + * Whether there is a fiscal year and a form to download the statement of. + */ + protected readonly hasFiscalYear: Signal = computed(() => this.params() != undefined); + + private readonly statement: ResourceRef = resource({ + params: () => this.params(), + loader: async ({ params }) => await this.bookkeepingService.resolveStatement(params.type, params.fiscalYearId, params.form) + }); + + /** + * Whether the statement is loading. + */ + protected readonly isLoading: Signal = computed(() => { + return this.statement.isLoading() || this.formChoices.isLoading() || this.settings.isLoading() || this.fiscalYears.isLoading(); + }); + + /** + * Whether the books, the forms or the statement couldn't be loaded. + */ + protected readonly loadingFailed: Signal = computed(() => { + return [this.statement, this.formChoices, this.settings, this.fiscalYears].some(loaded => loaded.error() != undefined); + }); + + /** + * The statement as it shows, undefined until it is loaded. + */ + protected readonly view: Signal = computed(() => { + const statement: BookkeepingStatementModel | undefined = this.statement.hasValue() ? this.statement.value() : undefined; + const format: Intl.NumberFormat | undefined = this.format(); + if (statement == undefined || format == undefined) { + return undefined; + } + const parentIds: Set = new Set(statement.positions.map(position => position.parentId ?? '')); + return { + label: statement.label, + closed: statement.closed, + currentLabel: this.resolveColumnLabel(statement.fiscalYearId, statement.end, statement.type), + previousLabel: statement.previousFiscalYearId == undefined || statement.previousEnd == undefined + ? undefined + : this.resolveColumnLabel(statement.previousFiscalYearId, statement.previousEnd, statement.type), + positions: statement.positions.map(position => this.toPositionView(position, parentIds.has(position.id), format)), + unmapped: statement.unmapped.map(account => ({ + label: `${account.number} ${account.name}`, + value: this.formatAmount(account.amount, format) + })), + result: this.formatAmount(statement.result, format) + }; + }); + + /** + * The result of the fiscal year, below the statement. + */ + protected readonly resultItems: Signal = computed(() => { + const view: StatementView | undefined = this.view(); + return view == undefined ? [] : [{ label: this.labels.result, value: view.result }]; + }); + + /** + * Downloads the statement as a pdf, in the form that shows. + */ + protected async downloadPdf(): Promise { + const params: StatementParams | undefined = this.params(); + if (params != undefined) { + const { type, fiscalYearId, form } = params; + await this.download(async () => await this.bookkeepingService.resolveStatementPdf(type, fiscalYearId, form)); + } + } + + private toPositionView(position: BookkeepingStatementPositionModel, isSum: boolean, format: Intl.NumberFormat): StatementPositionView { + const depthClasses: string = DEPTH_CLASSES[Math.min(position.depth, DEPTH_CLASSES.length - 1)] ?? ''; + return { + id: position.id, + label: position.label, + labelClasses: `${depthClasses} ${WEIGHT_CLASSES[isSum ? 'sum' : 'position']}`, + amount: this.formatAmount(position.amount, format), + previousAmount: position.previousAmount == undefined ? '' : this.formatAmount(position.previousAmount, format) + }; + } + + // a balance sheet states the day it is drawn up on, an income statement the fiscal year it covers. + private resolveColumnLabel(fiscalYearId: string, end: Date, type: BookkeepingStatementType): string { + const fiscalYear: FiscalYearModel | undefined = this.getFiscalYears().find(candidate => candidate.id === fiscalYearId); + return type === BookkeepingStatementType.BALANCE_SHEET || fiscalYear == undefined + ? this.formatDay(end) + : BookkeepingFiscalYearUtilities.resolveLabel(fiscalYear, this.config.dateFormat, this.locale); + } +} diff --git a/projects/ngx-bookkeeping/tailwind.css b/projects/ngx-bookkeeping/tailwind.css new file mode 100644 index 0000000..4c7b7e3 --- /dev/null +++ b/projects/ngx-bookkeeping/tailwind.css @@ -0,0 +1 @@ +@source "./fesm2022"; diff --git a/projects/ngx-bookkeeping/test-setup.ts b/projects/ngx-bookkeeping/test-setup.ts new file mode 100644 index 0000000..fd2135e --- /dev/null +++ b/projects/ngx-bookkeeping/test-setup.ts @@ -0,0 +1,29 @@ +import { PopoverTestingUtilities } from 'testing/popover'; + +// jsdom has no popover api, which the lists of the autocompletes and the calendars of the dates open with. +PopoverTestingUtilities.addPopovers(); + +// jsdom has no layout and no ResizeObserver, which the scroll regions of the reports watch their widths with. Nothing +// is ever wider than it is there, so an observer that never calls back is what jsdom would answer. +globalThis.ResizeObserver ??= class implements ResizeObserver { + /** + * Observes nothing, as jsdom has no sizes. + */ + observe(): void { + // jsdom has no sizes to observe + } + + /** + * Stops observing nothing. + */ + unobserve(): void { + // nothing is observed + } + + /** + * Stops observing nothing. + */ + disconnect(): void { + // nothing is observed + } +}; diff --git a/projects/ngx-bookkeeping/trial-balance/ng-package.json b/projects/ngx-bookkeeping/trial-balance/ng-package.json new file mode 100644 index 0000000..fa158ab --- /dev/null +++ b/projects/ngx-bookkeeping/trial-balance/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} diff --git a/projects/ngx-bookkeeping/trial-balance/public-api.ts b/projects/ngx-bookkeeping/trial-balance/public-api.ts new file mode 100644 index 0000000..2fa82ed --- /dev/null +++ b/projects/ngx-bookkeeping/trial-balance/public-api.ts @@ -0,0 +1 @@ +export * from './trial-balance.component'; diff --git a/projects/ngx-bookkeeping/trial-balance/trial-balance-row-view.model.ts b/projects/ngx-bookkeeping/trial-balance/trial-balance-row-view.model.ts new file mode 100644 index 0000000..38806af --- /dev/null +++ b/projects/ngx-bookkeeping/trial-balance/trial-balance-row-view.model.ts @@ -0,0 +1,33 @@ +/** + * A row of the trial balance as it shows: an account with its sums and its balance in the column of its side. + */ +export type TrialBalanceRowView = { + /** + * The id of the account. + */ + key: string, + /** + * The number of the account. + */ + number: string, + /** + * The name of the account. + */ + name: string, + /** + * The sum of its debits, formatted. + */ + debit: string, + /** + * The sum of its credits, formatted. + */ + credit: string, + /** + * Its balance while it is on the debit side, formatted, or an empty string. + */ + debitBalance: string, + /** + * Its balance while it is on the credit side, formatted without a sign, or an empty string. + */ + creditBalance: string +}; diff --git a/projects/ngx-bookkeeping/trial-balance/trial-balance-view.model.ts b/projects/ngx-bookkeeping/trial-balance/trial-balance-view.model.ts new file mode 100644 index 0000000..2634833 --- /dev/null +++ b/projects/ngx-bookkeeping/trial-balance/trial-balance-view.model.ts @@ -0,0 +1,31 @@ +import { TrialBalanceRowView } from './trial-balance-row-view.model'; + +/** + * The trial balance as it shows. + */ +export type TrialBalanceView = { + /** + * What screen readers call the table, with the fiscal year and the last day. + */ + label: string, + /** + * A row per account booked on. + */ + rows: TrialBalanceRowView[], + /** + * The sum of every debit, formatted. + */ + debit: string, + /** + * The sum of every credit, formatted. + */ + credit: string, + /** + * The sum of the balances on the debit side, formatted. + */ + debitBalances: string, + /** + * The sum of the balances on the credit side, formatted. + */ + creditBalances: string +}; diff --git a/projects/ngx-bookkeeping/trial-balance/trial-balance.component.html b/projects/ngx-bookkeeping/trial-balance/trial-balance.component.html new file mode 100644 index 0000000..e675c1f --- /dev/null +++ b/projects/ngx-bookkeeping/trial-balance/trial-balance.component.html @@ -0,0 +1,66 @@ +
+ + +
+
+ +
+@if (alert(); as alert) { + +} +@if (hasNoFiscalYears()) { + +} @else { +
+ @if (view(); as view) { + +
+ + + + + + + + + + + + + @for (row of view.rows; track row.key) { + + + + + + + + + } @empty { + + + + } + + + + + + + + + + +
{{ labels.number }}{{ commonLabels.account }}{{ commonLabels.debit }}{{ commonLabels.credit }}{{ labels.debitBalance }}{{ labels.creditBalance }}
{{ row.number }}{{ row.name }}{{ row.debit }}{{ row.credit }}{{ row.debitBalance }}{{ row.creditBalance }}
{{ labels.noRows }}
{{ commonLabels.total }}{{ view.debit }}{{ view.credit }}{{ view.debitBalances }}{{ view.creditBalances }}
+
+ } +
+} diff --git a/projects/ngx-bookkeeping/trial-balance/trial-balance.component.spec.ts b/projects/ngx-bookkeeping/trial-balance/trial-balance.component.spec.ts new file mode 100644 index 0000000..4f3100c --- /dev/null +++ b/projects/ngx-bookkeeping/trial-balance/trial-balance.component.spec.ts @@ -0,0 +1,65 @@ +import { provideHttpClient } from '@angular/common/http'; +import { provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { provideBookkeepingConfig } from '@service-soft/ngx-bookkeeping/api'; +import { FakeAnswer } from 'testing/http'; +import { beforeEach, describe, expect, test } from 'vitest'; + +import { BookkeepingTestingUtilities } from '../fixtures/bookkeeping-testing.utilities'; +import { BOOKKEEPING_BASE_URL, FISCAL_YEAR_IDS, toJson, TRIAL_BALANCE_2026 } from '../fixtures/bookkeeping.fixtures'; +import { TrialBalanceComponent } from './trial-balance.component'; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [TrialBalanceComponent] +}) +class HostComponent {} + +const ANSWERS: Record = { + ...BookkeepingTestingUtilities.getBookAnswers(), + [`GET ${BOOKKEEPING_BASE_URL}/reports/trial-balance`]: { status: 200, body: toJson(TRIAL_BALANCE_2026) } +}; + +describe('TrialBalanceComponent', () => { + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [provideHttpClient(), provideHttpClientTesting(), provideBookkeepingConfig({ baseUrl: BOOKKEEPING_BASE_URL })] + }); + }); + + test('shows the sums of every account and its balance in the column of its side, with the sums of the api', async () => { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + const requests: TestRequest[] = await BookkeepingTestingUtilities.settle(fixture, ANSWERS); + const root: HTMLElement = fixture.nativeElement as HTMLElement; + + expect(BookkeepingTestingUtilities.findRequest(requests, 'reports/trial-balance')?.request.params.toString()) + .toBe(`fiscalYearId=${FISCAL_YEAR_IDS.year2026}`); + expect(root.querySelector('table')?.getAttribute('aria-label')).toBe('Trial balance of 2026 until 12/31/2026'); + const rows: string[][] = [...root.querySelectorAll('tbody tr, tfoot tr')] + .map(row => [...row.querySelectorAll('td, th')].map(cell => cell.textContent.trim())); + expect(rows).toEqual([ + ['1200', 'Bank', '€14,650.00', '€1,200.00', '€13,450.00', ''], + ['1400', 'Receivables', '€1,190.00', '€0.00', '€1,190.00', ''], + ['1776', 'Output tax 19 %', '€0.00', '€190.00', '', '€190.00'], + ['2900', 'Share capital', '€0.00', '€12,500.00', '', '€12,500.00'], + ['2970', 'Profit carried forward', '€0.00', '€950.00', '', '€950.00'], + ['4210', 'Rent', '€1,200.00', '€1,200.00', '', ''], + ['8400', 'Revenue 19 %', '€0.00', '€1,000.00', '', '€1,000.00'], + ['Total', '€17,040.00', '€17,040.00', '€14,640.00', '€14,640.00'] + ]); + }); + + test('counts the entries up to the day the user chooses', async () => { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + await BookkeepingTestingUtilities.settle(fixture, ANSWERS); + const root: HTMLElement = fixture.nativeElement as HTMLElement; + + await BookkeepingTestingUtilities.type(fixture, root.querySelector('ui-input-date input'), '06/30/2026'); + const requests: TestRequest[] = await BookkeepingTestingUtilities.settle(fixture, ANSWERS); + + expect(BookkeepingTestingUtilities.findRequest(requests, 'reports/trial-balance')?.request.params.toString()) + .toBe(`fiscalYearId=${FISCAL_YEAR_IDS.year2026}&until=2026-06-30`); + }); +}); diff --git a/projects/ngx-bookkeeping/trial-balance/trial-balance.component.ts b/projects/ngx-bookkeeping/trial-balance/trial-balance.component.ts new file mode 100644 index 0000000..0228a59 --- /dev/null +++ b/projects/ngx-bookkeeping/trial-balance/trial-balance.component.ts @@ -0,0 +1,132 @@ +import { Component, computed, linkedSignal, resource, ResourceRef, Signal, WritableSignal } from '@angular/core'; +import { BookkeepingAmountUtilities, BookkeepingDayUtilities, BookkeepingFiscalYearUtilities, BookkeepingViewDirective, BookkeepingTrialBalanceLabels } from '@service-soft/ngx-bookkeeping/api'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { EmptyStateComponent } from '@service-soft/ui/empty-state'; +import { InputDateComponent } from '@service-soft/ui/input-date'; +import { InputSelectComponent } from '@service-soft/ui/input-select'; +import { LoadingDirective } from '@service-soft/ui/loading'; +import { ScrollRegionDirective } from '@service-soft/ui/scroll-region'; +import { BookkeepingTrialBalanceModel, BookkeepingTrialBalanceRowModel, FiscalYearModel } from 'zibri-contract'; + +import { TrialBalanceRowView } from './trial-balance-row-view.model'; +import { TrialBalanceView } from './trial-balance-view.model'; + +/** + * The fiscal year and the last day the trial balance shows. + */ +type TrialBalanceParams = { + /** + * The id of the fiscal year. + */ + fiscalYearId: string, + /** + * The last day whose entries count, at midnight UTC, or undefined for the end of the fiscal year. + */ + until: Date | undefined +}; + +/** + * The trial balance of the books of provideBookkeepingConfig: ``. It shows the sums of the debits + * and the credits of every account booked on in a fiscal year, the one of today at first, and its balance in the + * column of its side, up to a day of the year or to its end, with the sums of every column, as the api answers them. + * It downloads as a pdf. + */ +@Component({ + selector: 'ngx-trial-balance', + templateUrl: './trial-balance.component.html', + imports: [ButtonComponent, EmptyStateComponent, InputDateComponent, InputSelectComponent, LoadingDirective, ScrollRegionDirective], + host: { class: 'block' } +}) +export class TrialBalanceComponent extends BookkeepingViewDirective { + /** + * The texts of the trial balance. + */ + protected readonly labels: BookkeepingTrialBalanceLabels = this.config.labels.trialBalance; + + /** + * The last day whose entries count, in the time zone of the browser, or undefined for the end of the fiscal year. + * It starts over with another fiscal year. + */ + protected readonly until: WritableSignal = linkedSignal({ + source: this.fiscalYearId, + computation: () => undefined + }); + + private readonly params: Signal = computed(() => { + const fiscalYearId: string | undefined = this.fiscalYear()?.id; + const until: Date | undefined = this.until(); + return fiscalYearId == undefined + ? undefined + : { fiscalYearId, until: until == undefined ? undefined : BookkeepingDayUtilities.resolveDay(until) }; + }); + + /** + * Whether there is a fiscal year to download the trial balance of. + */ + protected readonly hasFiscalYear: Signal = computed(() => this.params() != undefined); + + private readonly trialBalance: ResourceRef = resource({ + params: () => this.params(), + loader: async ({ params }) => await this.bookkeepingService.resolveTrialBalance(params.fiscalYearId, params.until) + }); + + /** + * Whether the trial balance is loading. + */ + protected readonly isLoading: Signal = computed(() => { + return this.trialBalance.isLoading() || this.settings.isLoading() || this.fiscalYears.isLoading(); + }); + + /** + * Whether the books or the trial balance couldn't be loaded. + */ + protected readonly loadingFailed: Signal = computed(() => { + return [this.trialBalance, this.settings, this.fiscalYears].some(loaded => loaded.error() != undefined); + }); + + /** + * The trial balance as it shows, undefined until it is loaded. + */ + protected readonly view: Signal = computed(() => { + const trialBalance: BookkeepingTrialBalanceModel | undefined = this.trialBalance.hasValue() ? this.trialBalance.value() : undefined; + const fiscalYear: FiscalYearModel | undefined = this.fiscalYear(); + const format: Intl.NumberFormat | undefined = this.format(); + if (trialBalance == undefined || fiscalYear == undefined || format == undefined) { + return undefined; + } + const fiscalYearLabel: string = BookkeepingFiscalYearUtilities.resolveLabel(fiscalYear, this.config.dateFormat, this.locale); + return { + label: this.labels.table(fiscalYearLabel, this.formatDay(trialBalance.until)), + rows: trialBalance.rows.map(row => this.toRowView(row, format)), + debit: this.formatAmount(trialBalance.debit, format), + credit: this.formatAmount(trialBalance.credit, format), + debitBalances: this.formatAmount(trialBalance.debitBalances, format), + creditBalances: this.formatAmount(trialBalance.creditBalances, format) + }; + }); + + /** + * Downloads the trial balance as a pdf. + */ + protected async downloadPdf(): Promise { + const params: TrialBalanceParams | undefined = this.params(); + if (params != undefined) { + await this.download(async () => await this.bookkeepingService.resolveTrialBalancePdf(params.fiscalYearId, params.until)); + } + } + + // the balance is the debits less the credits, so its sign says the column of its side. + private toRowView(row: BookkeepingTrialBalanceRowModel, format: Intl.NumberFormat): TrialBalanceRowView { + const isZero: boolean = BookkeepingAmountUtilities.isZero(row.balance); + const isCredit: boolean = BookkeepingAmountUtilities.isNegative(row.balance); + return { + key: row.account.id, + number: row.account.number, + name: row.account.name, + debit: this.formatAmount(row.debit, format), + credit: this.formatAmount(row.credit, format), + debitBalance: isZero || isCredit ? '' : this.formatAmount(row.balance, format), + creditBalance: !isZero && isCredit ? this.formatAmount(BookkeepingAmountUtilities.getAbsolute(row.balance), format) : '' + }; + } +} diff --git a/projects/ngx-bookkeeping/trial-balance/trial-balance.stories.ts b/projects/ngx-bookkeeping/trial-balance/trial-balance.stories.ts new file mode 100644 index 0000000..52698ba --- /dev/null +++ b/projects/ngx-bookkeeping/trial-balance/trial-balance.stories.ts @@ -0,0 +1,35 @@ +import { Meta, StoryObj } from '@storybook/angular'; + +import { BookkeepingStoryUtilities } from '../fixtures/bookkeeping-story.utilities'; +import { TRIAL_BALANCE_2026 } from '../fixtures/bookkeeping.fixtures'; +import { TrialBalanceComponent } from './trial-balance.component'; + +const TRIAL_BALANCE: string = 'GET reports/trial-balance'; + +const meta: Meta = { + title: 'Bookkeeping/Trial balance', + component: TrialBalanceComponent, + render: () => ({ template: '' }) +}; +export default meta; + +type Story = StoryObj; + +export const Default: Story = { + decorators: [BookkeepingStoryUtilities.provideBackend({ [TRIAL_BALANCE]: BookkeepingStoryUtilities.getAnswer(TRIAL_BALANCE_2026) })] +}; + +export const NothingBooked: Story = { + decorators: [ + BookkeepingStoryUtilities.provideBackend({ + [TRIAL_BALANCE]: BookkeepingStoryUtilities.getAnswer({ + ...TRIAL_BALANCE_2026, + rows: [], + debit: '0', + credit: '0', + debitBalances: '0', + creditBalances: '0' + }) + }) + ] +}; diff --git a/projects/ngx-bookkeeping/tsconfig.lib.json b/projects/ngx-bookkeeping/tsconfig.lib.json new file mode 100644 index 0000000..ab37473 --- /dev/null +++ b/projects/ngx-bookkeeping/tsconfig.lib.json @@ -0,0 +1,18 @@ +/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ +/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ +{ + "compilerOptions": { + "declaration": true, + "declarationMap": true, + "outDir": "../../out-tsc/lib", + // the paths of the workspace point to the sources of the other libraries, which the build would then compile + // into this one. Without them, they resolve from node_modules like for a consumer, so ui and ngx-error-handling + // have to be built first. + "paths": {}, + "types": ["@angular/localize"] + }, + // the fixtures are the answers of the api the specs and stories render, never part of the package. + "exclude": ["**/*.spec.ts", "**/*.stories.ts", "fixtures/**", "test-setup.ts"], + "extends": "../../tsconfig.json", + "include": ["**/*.ts"] +} diff --git a/projects/ngx-bookkeeping/tsconfig.lib.prod.json b/projects/ngx-bookkeeping/tsconfig.lib.prod.json new file mode 100644 index 0000000..a416f78 --- /dev/null +++ b/projects/ngx-bookkeeping/tsconfig.lib.prod.json @@ -0,0 +1,11 @@ +/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ +/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ +{ + "angularCompilerOptions": { + "compilationMode": "partial" + }, + "compilerOptions": { + "declarationMap": false + }, + "extends": "./tsconfig.lib.json" +} diff --git a/projects/ngx-bookkeeping/tsconfig.spec.json b/projects/ngx-bookkeeping/tsconfig.spec.json new file mode 100644 index 0000000..7a9cb00 --- /dev/null +++ b/projects/ngx-bookkeeping/tsconfig.spec.json @@ -0,0 +1,10 @@ +/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ +/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ +{ + "compilerOptions": { + "outDir": "../../out-tsc/spec", + "types": ["vitest/globals", "@angular/localize"] + }, + "extends": "../../tsconfig.json", + "include": ["**/*.d.ts", "**/*.spec.ts", "fixtures/**/*.ts", "test-setup.ts"] +} diff --git a/projects/ngx-change-sets/CHANGELOG.md b/projects/ngx-change-sets/CHANGELOG.md new file mode 100644 index 0000000..94e9c82 --- /dev/null +++ b/projects/ngx-change-sets/CHANGELOG.md @@ -0,0 +1,17 @@ +# Changelog + +## 22.4.0 + +### Breaking changes +- The peer `zibri-contract` is `^3.3.0`, was `^3.1.0`, like in every library of `@service-soft`. +- The dates of change sets and of changed values follow the `LOCALE_ID` of the app by default, instead of + `dd.MM.yyyy HH:mm`. Set `dateFormat` and `valueDateFormat` of the config to `'dd.MM.yyyy HH:mm'` to keep the old + format. Both are `string | undefined` now. + +### Features +- `@service-soft/ngx-change-sets/changes`: ``, the table of the changed values, on its own, with + `provideChangesConfig`, `ChangeValueUtilities` and `ValueChange`. +- `@service-soft/ngx-change-sets/entity-field`: the change sets of an entity as a field of an ngx-entity form, which + replaces the entity of the form when a change set is undone. Needs the optional peer `@service-soft/ngx-entity`. +- The German translation of the texts ships with the package (`locale/messages.de.xlf`). +- Icons are imported from one file each, so a page only loads the icons it shows. diff --git a/projects/ngx-change-sets/README.md b/projects/ngx-change-sets/README.md index 3885184..fd4d2b1 100644 --- a/projects/ngx-change-sets/README.md +++ b/projects/ngx-change-sets/README.md @@ -9,6 +9,8 @@ It is built on [@service-soft/ui](https://www.npmjs.com/package/@service-soft/ui - [Requirements](#requirements) - [Setup](#setup) - [Usage](#usage) +- [In a form of ngx-entity](#in-a-form-of-ngx-entity) +- [Changes on their own](#changes-on-their-own) - [Configuration](#configuration) - [Translating](#translating) - [Moving from ngx-material-change-sets](#moving-from-ngx-material-change-sets) @@ -76,6 +78,61 @@ import { ChangeSetsComponent } from '@service-soft/ngx-change-sets/change-sets'; The newest change sets show first, to the nanosecond, 10 at a time. "Show more" adds the next ones and moves the focus to the first new one. The creation can't be reset on its own, and the newest change set is the state already, so it offers no rollback. +# In a form of ngx-entity +With [@service-soft/ngx-entity](https://www.npmjs.com/package/@service-soft/ngx-entity), the change sets are a field of the form of their entity, which you show where and when you want, like on a tab of its own after all others. `ChangeSetsFieldComponent` of `@service-soft/ngx-change-sets/entity-field` is the component of a `@Property.custom` of the `changeSets` of the entity, loaded the first time a form shows it: + +```ts +import { ChangeSetsFieldData } from '@service-soft/ngx-change-sets/entity-field'; +import { Property } from '@service-soft/ngx-entity/entity'; +import { ChangeSet } from 'zibri-contract'; + +export class Order { + @Property.string({ displayName: 'Id', omitForCreate: true, readonly: true, display: false }) + id!: string; + + @Property.string({ displayName: 'Name' }) + name!: string; + + @Property.custom({ + displayName: 'History', + component: async () => (await import('@service-soft/ngx-change-sets/entity-field')).ChangeSetsFieldComponent, + data: { changeSetsApiBaseUrl: '/api/orders' } satisfies ChangeSetsFieldData, + position: { tab: 'last', tabName: 'History' } + }) + changeSets?: ChangeSet[]; +} +``` + +```ts +// app.config.ts +providers: [provideHttpClient(), provideChangeSetService(MyChangeSetService)] +``` + +The `ChangeSetService` is the one of [Setup](#setup), and the entity has to come with its change sets, like the `findById` of your zibri controller answers it with `{ relations: { changeSets: { changes: true } } }`. A table of ngx-entity edits the row its page read, which a list usually reads without them, so open the entity by its id first, or edit it on the page of `edit="page"`, which loads it by its id. + +| `data` | Values | Default | +|---|---|---| +| `changeSetsApiBaseUrl` | `string` | required — passed on to the `ChangeSetService` | +| `canResetAndRollback` | `boolean` | `canResetAndRollback` of `provideChangeSetsConfig` — never while the field is `readonly` | +| `canOpenCreatedBy` | `boolean` | `canOpenCreatedBy` of `provideChangeSetsConfig` | + +Undoing a change set hands the form the entity the server answered, so every field shows its values, and the editor, its dialogs and pages take it as saved: it is no unsaved change, and saving sends only what the user changes after it. The field never changes the change sets itself, so they are never sent, not with the changes of an entity and not with a new one. A new entity has none yet, so the field says that they show once it is saved, the text `createFirstLabel` of `provideChangeSetsFieldConfig`. + +`@service-soft/ngx-entity` is an optional peer: only `@service-soft/ngx-change-sets/entity-field` needs it. + +# Changes on their own +The values before and after, as a change set shows them, without its history, like the values an approval request would change. `ChangesComponent` of `@service-soft/ngx-change-sets/changes` takes any list of a `key`, a `previousValue` and a `newValue`: the `changes` of a `ChangeSet`, or the `ApprovalValueChangeModel`s of [zibri-contract](https://www.npmjs.com/package/zibri-contract): + +```ts +import { ChangesComponent } from '@service-soft/ngx-change-sets/changes'; +``` + +```html + +``` + +Dates among the values show with their day and time in the language of the app, its `LOCALE_ID`, like `10/12/2026, 02:30 PM` in `en-US` and `12.10.2026, 14:30` in `de`, or in the `dateFormat` of `provideChangesConfig` when it sets one, lists of simple values on one line, objects as indented json, and a value that isn't there as a dash. It shows nothing without changes. Change the format and the headers of its columns, `labels: { key, previousValue, newValue }`, with `provideChangesConfig`, like `provideChangeSetsConfig` below. `` shows its values with this component, with the `valueDateFormat` and the labels of `provideChangeSetsConfig`, so `provideChangesConfig` doesn't change them there. + # Configuration `provideChangeSetsConfig` sets the defaults for the whole app, or for a part of it when you add it to the providers of a component. Values you leave out keep the defaults of the parent, labels and dialog texts included: @@ -88,8 +145,8 @@ provideChangeSetsConfig({ | Option | Default | |---|---| -| `dateFormat` | `'dd.MM.yyyy HH:mm'` — the date of a change set, in the format of Angular's `DatePipe` | -| `valueDateFormat` | `'dd.MM.yyyy HH:mm'` — dates among the changed values | +| `dateFormat` | `undefined` — the date of a change set: its day and time in the `LOCALE_ID` of the app, or a fixed format of Angular's `DatePipe`, like `'dd.MM.yyyy HH:mm'` | +| `valueDateFormat` | `undefined` — dates among the changed values, like `dateFormat` | | `pageSize` | `10` — how many change sets show at first, and how many each "show more" adds | | `canResetAndRollback` | `true` | | `canOpenCreatedBy` | `true` | @@ -100,6 +157,8 @@ provideChangeSetsConfig({ ## Translating The default texts are `$localize` with an id of their own, like `@@ngx-change-sets.change-sets.showMore`, so `ng extract-i18n` puts them into the messages of your app, and you translate them like its own texts. The library needs `@angular/localize` for that, `ng add @angular/localize`, also in an app of one language. A build with `localize` fills the texts in, so no part of `@angular/localize` reaches the browser. The defaults are made once a config is injected, so translations an app loads at runtime with `loadTranslations` apply as well. A text of `provideChangeSetsConfig` replaces the default in every language. So translate a default in your messages, and change it in the config only to say something else: a default the config replaces stays in your messages, though nothing shows it. +German ships with the library: `locale/messages.de.xlf` of the package is an XLIFF 1.2 file with a German target for each of its texts, and its `package.json` names it in `"translations": { "de": "./locale/messages.de.xlf" }`. A merge of the translations of an app's dependencies reads that field and fills these targets into the German messages of the app, so German needs no translation of your own. Only the texts your app uses end up there, since its `ng extract-i18n` decides which units its messages have. Other languages you translate in your messages. + # Moving from ngx-material-change-sets - It needs `@service-soft/ui` and Tailwind instead of Angular Material and the Font Awesome packages. Import from `@service-soft/ngx-change-sets/change-sets`. - `` is ``. The `config` input is gone: the labels, formats and dialog texts are set with `provideChangeSetsConfig`, and `canResetAndRollback` and `canOpenCreatedBy` are inputs, which only take booleans. diff --git a/projects/ngx-change-sets/change-sets/change-set-view.model.ts b/projects/ngx-change-sets/change-sets/change-set-view.model.ts index 623cdca..6f90902 100644 --- a/projects/ngx-change-sets/change-sets/change-set-view.model.ts +++ b/projects/ngx-change-sets/change-sets/change-set-view.model.ts @@ -1,8 +1,6 @@ import { IconDefinition } from '@service-soft/ui/icon'; import { ChangeSet } from 'zibri-contract'; -import { ChangeView } from './change-view.model'; - /** * A change set as the change sets component shows it. */ @@ -38,9 +36,5 @@ export type ChangeSetView = { /** * Whether the entity can be rolled back to it. Rolling back to the newest one would change nothing. */ - canRollback: boolean, - /** - * The values that changed. - */ - changes: ChangeView[] + canRollback: boolean }; \ No newline at end of file diff --git a/projects/ngx-change-sets/change-sets/change-sets-config.model.ts b/projects/ngx-change-sets/change-sets/change-sets-config.model.ts index b80e3d1..68a2eda 100644 --- a/projects/ngx-change-sets/change-sets/change-sets-config.model.ts +++ b/projects/ngx-change-sets/change-sets/change-sets-config.model.ts @@ -52,13 +52,15 @@ export type ChangeSetsLabels = { */ export type ChangeSetsConfig = { /** - * How the date of a change set is shown, in the format of Angular's DatePipe. + * How the date of a change set is shown: a fixed format of Angular's DatePipe, like 'dd.MM.yyyy HH:mm', or undefined + * for the day and the time in the LOCALE_ID of the app, like '10/12/2026, 02:30 PM' in 'en-US' and + * '12.10.2026, 14:30' in 'de'. Undefined by default. */ - dateFormat: string, + dateFormat: string | undefined, /** - * How dates among the changed values are shown, in the format of Angular's DatePipe. + * How dates among the changed values are shown, like dateFormat. Undefined by default, for the LOCALE_ID of the app. */ - valueDateFormat: string, + valueDateFormat: string | undefined, /** * How many change sets show at first, and how many more each click on "show more" adds. */ diff --git a/projects/ngx-change-sets/change-sets/change-sets-config.provider.ts b/projects/ngx-change-sets/change-sets/change-sets-config.provider.ts index 1eeeb9e..3996303 100644 --- a/projects/ngx-change-sets/change-sets/change-sets-config.provider.ts +++ b/projects/ngx-change-sets/change-sets/change-sets-config.provider.ts @@ -11,8 +11,8 @@ import { ChangeSetsConfig } from './change-sets-config.model'; */ function getDefaultChangeSetsConfig(): ChangeSetsConfig { return { - dateFormat: 'dd.MM.yyyy HH:mm', - valueDateFormat: 'dd.MM.yyyy HH:mm', + dateFormat: undefined, + valueDateFormat: undefined, pageSize: 10, canResetAndRollback: true, canOpenCreatedBy: true, diff --git a/projects/ngx-change-sets/change-sets/change-sets.component.html b/projects/ngx-change-sets/change-sets/change-sets.component.html index df4ef64..f331e77 100644 --- a/projects/ngx-change-sets/change-sets/change-sets.component.html +++ b/projects/ngx-change-sets/change-sets/change-sets.component.html @@ -43,7 +43,7 @@ - + } diff --git a/projects/ngx-change-sets/change-sets/change-sets.component.spec.ts b/projects/ngx-change-sets/change-sets/change-sets.component.spec.ts index 3ad2f4f..42e1085 100644 --- a/projects/ngx-change-sets/change-sets/change-sets.component.spec.ts +++ b/projects/ngx-change-sets/change-sets/change-sets.component.spec.ts @@ -1,6 +1,6 @@ import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; -import { Component, input, InputSignal, linkedSignal, Service, WritableSignal } from '@angular/core'; +import { Component, input, InputSignal, linkedSignal, LOCALE_ID, Service, WritableSignal } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { describe, expect, test } from 'vitest'; import { ChangeSet, ChangeSetEntity, ChangeSetType, ResetChangeSetResult } from 'zibri-contract'; @@ -84,9 +84,9 @@ describe('ChangeSetsComponent', () => { const [, root] = await render(); expect(getSummaries(root)).toEqual([ - 'Deleted 03.10.2026 09:00', - 'Updated 02.10.2026 09:00 Jane Doe', - 'Created 01.10.2026 09:00 Jane Doe' + 'Deleted 10/03/2026, 09:00 AM', + 'Updated 10/02/2026, 09:00 AM Jane Doe', + 'Created 10/01/2026, 09:00 AM Jane Doe' ]); // the icons in front of the date and the name say what they are const iconLabels: (string | null)[] = [...root.querySelectorAll('summary')[1]?.querySelectorAll('svg[role="img"]') ?? []] @@ -108,7 +108,18 @@ describe('ChangeSetsComponent', () => { } }); - expect(getSummaries(root)).toEqual(['Updated 02.10.2026 09:00', 'Created 02.10.2026 09:00']); + expect(getSummaries(root)).toEqual(['Updated 10/02/2026, 09:00 AM', 'Created 10/02/2026, 09:00 AM']); + }); + + test('shows the dates in the language of the app, and in a fixed format the config sets', async () => { + TestBed.configureTestingModule({ providers: [{ provide: LOCALE_ID, useValue: 'de' }] }); + const [, inGerman] = await render(); + expect(getSummaries(inGerman)[0]).toBe('Deleted 03.10.2026, 09:00'); + + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ providers: [provideChangeSetsConfig({ dateFormat: 'dd.MM.yyyy HH:mm' })] }); + const [, fixed] = await render(); + expect(getSummaries(fixed)[0]).toBe('Deleted 03.10.2026 09:00'); }); test('offers to reset a change set unless it is the creation, to roll back to one unless it is the newest, and nothing when read only', async () => { diff --git a/projects/ngx-change-sets/change-sets/change-sets.component.ts b/projects/ngx-change-sets/change-sets/change-sets.component.ts index b4a5b12..84a7d31 100644 --- a/projects/ngx-change-sets/change-sets/change-sets.component.ts +++ b/projects/ngx-change-sets/change-sets/change-sets.component.ts @@ -1,6 +1,13 @@ -import { formatDate } from '@angular/common'; import { afterNextRender, booleanAttribute, Component, computed, inject, Injector, input, InputSignal, InputSignalWithTransform, linkedSignal, LOCALE_ID, model, ModelSignal, resource, ResourceRef, Signal, viewChildren, WritableSignal } from '@angular/core'; -import { faArrowRotateLeft, faCircleLeft, faCircleMinus, faCirclePlus, faCircleUp, faClock, faClockRotateLeft, faUser } from '@fortawesome/free-solid-svg-icons'; +import { faArrowRotateLeft } from '@fortawesome/free-solid-svg-icons/faArrowRotateLeft'; +import { faCircleLeft } from '@fortawesome/free-solid-svg-icons/faCircleLeft'; +import { faCircleMinus } from '@fortawesome/free-solid-svg-icons/faCircleMinus'; +import { faCirclePlus } from '@fortawesome/free-solid-svg-icons/faCirclePlus'; +import { faCircleUp } from '@fortawesome/free-solid-svg-icons/faCircleUp'; +import { faClock } from '@fortawesome/free-solid-svg-icons/faClock'; +import { faClockRotateLeft } from '@fortawesome/free-solid-svg-icons/faClockRotateLeft'; +import { faUser } from '@fortawesome/free-solid-svg-icons/faUser'; +import { CHANGES_CONFIG, ChangesComponent, ChangesConfig, ChangeValueUtilities } from '@service-soft/ngx-change-sets/changes'; import { ButtonComponent } from '@service-soft/ui/button'; import { DetailsComponent, SummaryComponent } from '@service-soft/ui/details'; import { ConfirmDialogComponent, ConfirmDialogData, DialogService } from '@service-soft/ui/dialog'; @@ -14,8 +21,6 @@ import { ChangeSetView } from './change-set-view.model'; import { ChangeSetService } from './change-set.service'; import { ChangeSetsConfig, ChangeSetsLabels } from './change-sets-config.model'; import { CHANGE_SETS_CONFIG } from './change-sets-config.provider'; -import { ChangeValueUtilities } from './change-value.utilities'; -import { ChangesTableComponent } from './changes-table.component'; const TYPE_LABEL_CLASSES: string = 'inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-label'; @@ -55,7 +60,7 @@ type ChangeSetsIcons = Record<'clock' | 'user' | 'reset', IconDefinition>; templateUrl: './change-sets.component.html', imports: [ ButtonComponent, - ChangesTableComponent, + ChangesComponent, DetailsComponent, IconComponent, LinkComponent, @@ -64,6 +69,20 @@ type ChangeSetsIcons = Record<'clock' | 'user' | 'reset', IconDefinition>; MenuTriggerDirective, SummaryComponent ], + // the changes of a change set take their date format and texts from provideChangeSetsConfig, which had them before + // the changes were an entry point of their own, not from provideChangesConfig. + providers: [ + { + provide: CHANGES_CONFIG, + useFactory: (): ChangesConfig => { + const config: ChangeSetsConfig = inject(CHANGE_SETS_CONFIG); + return { + dateFormat: config.valueDateFormat, + labels: { key: config.labels.key, previousValue: config.labels.previousValue, newValue: config.labels.newValue } + }; + } + } + ], host: { class: 'grid gap-2' } @@ -198,15 +217,10 @@ export class ChangeSetsComponent { typeLabel: this.config.labels.types[changeSet.type], typeClasses: [TYPE_LABEL_CLASSES, TYPE_CLASSES[changeSet.type]].join(' '), typeIcon: TYPE_ICONS[changeSet.type], - createdAt: formatDate(ChangeSetTimeUtilities.resolveDate(changeSet), this.config.dateFormat, this.locale), + createdAt: ChangeValueUtilities.formatDate(ChangeSetTimeUtilities.resolveDate(changeSet), this.config.dateFormat, this.locale), createdByName: this.findCreatedByName(changeSet), canReset: changeSet.type !== ChangeSetType.CREATE, - canRollback: !isNewest, - changes: changeSet.changes.map(change => ({ - key: change.key, - previousValue: ChangeValueUtilities.format(change.previousValue, this.config.valueDateFormat, this.locale), - newValue: ChangeValueUtilities.format(change.newValue, this.config.valueDateFormat, this.locale) - })) + canRollback: !isNewest }; } diff --git a/projects/ngx-change-sets/change-sets/change-value.utilities.ts b/projects/ngx-change-sets/change-sets/change-value.utilities.ts deleted file mode 100644 index 24d4b33..0000000 --- a/projects/ngx-change-sets/change-sets/change-value.utilities.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { formatDate } from '@angular/common'; - -// only full ISO dates, like the api sends them. Anything new Date() accepts would include strings like '1' or 'May'. -const ISO_DATE: RegExp = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/; - -/** - * Formats the values of changes for reading. - */ -export abstract class ChangeValueUtilities { - /** - * Formats a changed value as text: dates in the given format, lists of simple values on one line, objects as - * indented json, and a dash for no value. - * @param value - The previous or new value of a change. - * @param dateFormat - The format of dates, in the format of Angular's DatePipe. - * @param locale - The locale dates are formatted in. - * @returns The text to show. - */ - static format(value: unknown, dateFormat: string, locale: string): string { - if (value == undefined) { - return '-'; - } - if (value instanceof Date || (typeof value === 'string' && ISO_DATE.test(value))) { - return formatDate(value, dateFormat, locale); - } - if (Array.isArray(value) && value.every(item => !this.isObject(item))) { - return `[${value.map(item => JSON.stringify(item)).join(', ')}]`; - } - // values come from the api as json, so everything that isn't a string is a number, a boolean or an object. - return typeof value === 'string' ? value : JSON.stringify(value, undefined, 2); - } - - private static isObject(value: unknown): boolean { - return typeof value === 'object' && value != undefined; - } -} \ No newline at end of file diff --git a/projects/ngx-change-sets/change-sets/changes-table.component.ts b/projects/ngx-change-sets/change-sets/changes-table.component.ts deleted file mode 100644 index d16c7c1..0000000 --- a/projects/ngx-change-sets/change-sets/changes-table.component.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { Component, inject, input, InputSignal } from '@angular/core'; -import { faArrowRightLong } from '@fortawesome/free-solid-svg-icons'; -import { IconComponent, IconDefinition } from '@service-soft/ui/icon'; - -import { ChangeSetsLabels } from './change-sets-config.model'; -import { CHANGE_SETS_CONFIG } from './change-sets-config.provider'; -import { ChangeView } from './change-view.model'; - -/** - * The values that changed in a change set, each with its value before and after. Only used by the change sets - * component. - */ -@Component({ - selector: 'ngx-changes-table', - templateUrl: './changes-table.component.html', - imports: [IconComponent], - host: { - class: 'block' - } -}) -export class ChangesTableComponent { - /** - * The changes to show. - */ - readonly changes: InputSignal = input.required(); - - /** - * The texts to show. - */ - protected readonly labels: ChangeSetsLabels = inject(CHANGE_SETS_CONFIG).labels; - - /** - * The arrow between the values before and after. - */ - protected readonly arrow: IconDefinition = faArrowRightLong; -} \ No newline at end of file diff --git a/projects/ngx-change-sets/change-sets/change-value.utilities.spec.ts b/projects/ngx-change-sets/changes/change-value.utilities.spec.ts similarity index 81% rename from projects/ngx-change-sets/change-sets/change-value.utilities.spec.ts rename to projects/ngx-change-sets/changes/change-value.utilities.spec.ts index 247229f..52b30ef 100644 --- a/projects/ngx-change-sets/change-sets/change-value.utilities.spec.ts +++ b/projects/ngx-change-sets/changes/change-value.utilities.spec.ts @@ -13,6 +13,12 @@ describe('ChangeValueUtilities.format', () => { expect(ChangeValueUtilities.format('May 2', FORMAT, 'en-US')).toBe('May 2'); }); + test('formats dates in the language of the locale without a format', () => { + expect(ChangeValueUtilities.format('2026-10-12T14:30:00', undefined, 'en-US')).toBe('10/12/2026, 02:30 PM'); + expect(ChangeValueUtilities.format(new Date(2026, 9, 12, 14, 30), undefined, 'de')).toBe('12.10.2026, 14:30'); + expect(ChangeValueUtilities.format('May 2', undefined, 'de')).toBe('May 2'); + }); + test('shows lists of simple values on one line and objects as indented json', () => { expect(ChangeValueUtilities.format(['a', 1, true], FORMAT, 'en-US')).toBe('["a", 1, true]'); expect(ChangeValueUtilities.format([], FORMAT, 'en-US')).toBe('[]'); diff --git a/projects/ngx-change-sets/changes/change-value.utilities.ts b/projects/ngx-change-sets/changes/change-value.utilities.ts new file mode 100644 index 0000000..9560365 --- /dev/null +++ b/projects/ngx-change-sets/changes/change-value.utilities.ts @@ -0,0 +1,54 @@ +import { formatDate } from '@angular/common'; + +// only full ISO dates, like the api sends them. Anything new Date() accepts would include strings like '1' or 'May'. +const ISO_DATE: RegExp = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/; + +// the day and the time as the other libraries show a moment, in the order and with the separators of the locale +const LOCALE_DATE_TIME: Intl.DateTimeFormatOptions = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }; + +/** + * Formats the values of changes and the dates of change sets for reading. + */ +export abstract class ChangeValueUtilities { + /** + * Formats a changed value as text: dates like formatDate does, lists of simple values on one line, objects as + * indented json, and a dash for no value. + * @param value - The previous or new value of a change. + * @param dateFormat - The format of dates, in the format of Angular's DatePipe, or undefined for the day and the + * time in the language of the locale. + * @param locale - The locale dates are formatted in. + * @returns The text to show. + */ + static format(value: unknown, dateFormat: string | undefined, locale: string): string { + if (value == undefined) { + return '-'; + } + if (value instanceof Date || (typeof value === 'string' && ISO_DATE.test(value))) { + return this.formatDate(value, dateFormat, locale); + } + if (Array.isArray(value) && value.every(item => !this.isObject(item))) { + return `[${value.map(item => JSON.stringify(item)).join(', ')}]`; + } + // values come from the api as json, so everything that isn't a string is a number, a boolean or an object. + return typeof value === 'string' ? value : JSON.stringify(value, undefined, 2); + } + + /** + * Formats a moment, like when a change set was created, in the time zone of the browser. + * @param date - The moment, or an ISO date. + * @param dateFormat - A fixed format, in the format of Angular's DatePipe, like 'dd.MM.yyyy HH:mm', or undefined for + * the day and the time in the language of the locale, like '10/12/2026, 02:30 PM' in 'en-US' and '12.10.2026, 14:30' + * in 'de'. + * @param locale - The locale it is formatted in, the LOCALE_ID of the app. + * @returns The text to show. + */ + static formatDate(date: Date | string, dateFormat: string | undefined, locale: string): string { + return dateFormat == undefined + ? new Intl.DateTimeFormat(locale, LOCALE_DATE_TIME).format(new Date(date)) + : formatDate(date, dateFormat, locale); + } + + private static isObject(value: unknown): boolean { + return typeof value === 'object' && value != undefined; + } +} diff --git a/projects/ngx-change-sets/change-sets/change-view.model.ts b/projects/ngx-change-sets/changes/change-view.model.ts similarity index 85% rename from projects/ngx-change-sets/change-sets/change-view.model.ts rename to projects/ngx-change-sets/changes/change-view.model.ts index 090df25..8c5f7fb 100644 --- a/projects/ngx-change-sets/change-sets/change-view.model.ts +++ b/projects/ngx-change-sets/changes/change-view.model.ts @@ -1,5 +1,5 @@ /** - * A change as the change sets component shows it. + * A change as the changes component shows it. */ export type ChangeView = { /** diff --git a/projects/ngx-change-sets/changes/changes-config-changes.model.ts b/projects/ngx-change-sets/changes/changes-config-changes.model.ts new file mode 100644 index 0000000..5325a6c --- /dev/null +++ b/projects/ngx-change-sets/changes/changes-config-changes.model.ts @@ -0,0 +1,11 @@ +import { ChangesConfig, ChangesLabels } from './changes-config.model'; + +/** + * The values to change in the config of the changes. Everything is optional, including every single label. + */ +export type ChangesConfigChanges = Partial> & { + /** + * The labels to change. + */ + labels?: Partial +}; \ No newline at end of file diff --git a/projects/ngx-change-sets/changes/changes-config.model.ts b/projects/ngx-change-sets/changes/changes-config.model.ts new file mode 100644 index 0000000..75fb84e --- /dev/null +++ b/projects/ngx-change-sets/changes/changes-config.model.ts @@ -0,0 +1,33 @@ +/** + * The texts the changes show, to translate them. + */ +export type ChangesLabels = { + /** + * The column of the names of the changed values. + */ + key: string, + /** + * The column of the values before the change. + */ + previousValue: string, + /** + * The column of the values after the change. + */ + newValue: string +}; + +/** + * The values the changes use. + */ +export type ChangesConfig = { + /** + * How dates among the changed values are shown: a fixed format of Angular's DatePipe, like 'dd.MM.yyyy HH:mm', or + * undefined for the day and the time in the LOCALE_ID of the app, like '10/12/2026, 02:30 PM' in 'en-US' and + * '12.10.2026, 14:30' in 'de'. Undefined by default. + */ + dateFormat: string | undefined, + /** + * The texts the changes show. + */ + labels: ChangesLabels +}; \ No newline at end of file diff --git a/projects/ngx-change-sets/changes/changes-config.provider.ts b/projects/ngx-change-sets/changes/changes-config.provider.ts new file mode 100644 index 0000000..a2573e3 --- /dev/null +++ b/projects/ngx-change-sets/changes/changes-config.provider.ts @@ -0,0 +1,45 @@ +import { inject, InjectionToken, Provider } from '@angular/core'; + +import { ChangesConfigChanges } from './changes-config-changes.model'; +import { ChangesConfig } from './changes-config.model'; + +/** + * The values of the changes when nothing changes them. Their texts are $localize, which an app translates like its own, + * and resolved once the config is injected, so translations an app loads at runtime apply as well. + * @returns The default config. + */ +function getDefaultChangesConfig(): ChangesConfig { + return { + dateFormat: undefined, + labels: { + key: $localize`:@@ngx-change-sets.changes.key:Property`, + previousValue: $localize`:@@ngx-change-sets.changes.previousValue:Previous value`, + newValue: $localize`:@@ngx-change-sets.changes.newValue:New value` + } + }; +} + +/** + * The values every changes component below this injector uses. Change them with provideChangesConfig. + */ +export const CHANGES_CONFIG: InjectionToken = new InjectionToken('CHANGES_CONFIG', { + providedIn: 'root', + factory: () => getDefaultChangesConfig() +}); + +/** + * Changes the values the changes use, like the labels to translate them. Provide it in the application config for the + * whole app, or in a component or route for only that part of it. Values you leave out are taken from the parent + * injector, including single labels. The changes of `` take theirs from provideChangeSetsConfig. + * @param config - The values to change. + * @returns The provider for CHANGES_CONFIG. + */ +export function provideChangesConfig(config: ChangesConfigChanges): Provider { + return { + provide: CHANGES_CONFIG, + useFactory: (): ChangesConfig => { + const parent: ChangesConfig = inject(CHANGES_CONFIG, { skipSelf: true, optional: true }) ?? getDefaultChangesConfig(); + return { ...parent, ...config, labels: { ...parent.labels, ...config.labels } }; + } + }; +} \ No newline at end of file diff --git a/projects/ngx-change-sets/change-sets/changes-table.component.html b/projects/ngx-change-sets/changes/changes.component.html similarity index 96% rename from projects/ngx-change-sets/change-sets/changes-table.component.html rename to projects/ngx-change-sets/changes/changes.component.html index f20cf8e..c645486 100644 --- a/projects/ngx-change-sets/change-sets/changes-table.component.html +++ b/projects/ngx-change-sets/changes/changes.component.html @@ -1,4 +1,4 @@ -@if (changes().length) { +@if (views().length) { @@ -10,7 +10,7 @@ - @for (change of changes(); track $index) { + @for (change of views(); track $index) { @@ -41,4 +41,4 @@ }
{{ change.key }}
-} \ No newline at end of file +} diff --git a/projects/ngx-change-sets/changes/changes.component.spec.ts b/projects/ngx-change-sets/changes/changes.component.spec.ts new file mode 100644 index 0000000..8f51fd3 --- /dev/null +++ b/projects/ngx-change-sets/changes/changes.component.spec.ts @@ -0,0 +1,66 @@ +import { Component, input, InputSignal, LOCALE_ID } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { describe, expect, test } from 'vitest'; + +import { provideChangesConfig } from './changes-config.provider'; +import { ChangesComponent } from './changes.component'; +import { ValueChange } from './value-change.model'; + +const CHANGES: ValueChange[] = [ + { key: 'status', previousValue: 'open', newValue: 'done' }, + { key: 'dueAt', previousValue: '2026-10-12T14:30:00', newValue: undefined }, + { key: 'labels', previousValue: ['a'], newValue: ['a', 'b'] } +]; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [ChangesComponent] +}) +class HostComponent { + readonly changes: InputSignal = input(CHANGES); +} + +async function render(changes?: ValueChange[]): Promise { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + if (changes != undefined) { + fixture.componentRef.setInput('changes', changes); + } + await fixture.whenStable(); + return fixture.nativeElement as HTMLElement; +} + +function getValues(root: HTMLElement): string[] { + return [...root.querySelectorAll('pre')].map(pre => pre.textContent); +} + +describe('ChangesComponent', () => { + test('shows each value before and after, formatted like the change sets', async () => { + const root: HTMLElement = await render(); + + expect([...root.querySelectorAll('thead th')].map(header => header.textContent.trim())).toEqual(['Property', 'Previous value', 'New value']); + expect([...root.querySelectorAll('tbody th[scope="row"]')].map(key => key.textContent.trim())).toEqual(['status', 'dueAt', 'labels']); + expect(getValues(root)).toEqual(['open', 'done', '10/12/2026, 02:30 PM', '-', '["a"]', '["a", "b"]']); + }); + + test('shows dates in the language of the app', async () => { + TestBed.configureTestingModule({ providers: [{ provide: LOCALE_ID, useValue: 'de' }] }); + const root: HTMLElement = await render(); + + expect(getValues(root)[2]).toBe('12.10.2026, 14:30'); + }); + + test('takes its date format and texts from the config', async () => { + TestBed.configureTestingModule({ providers: [provideChangesConfig({ dateFormat: 'yyyy-MM-dd', labels: { previousValue: 'Stored' } })] }); + const root: HTMLElement = await render(); + + expect([...root.querySelectorAll('thead th')].map(header => header.textContent.trim())).toEqual(['Property', 'Stored', 'New value']); + expect(getValues(root)[2]).toBe('2026-10-12'); + }); + + test('shows nothing without changes', async () => { + const root: HTMLElement = await render([]); + + expect(root.querySelector('ngx-changes')?.childElementCount).toBe(0); + }); +}); \ No newline at end of file diff --git a/projects/ngx-change-sets/changes/changes.component.ts b/projects/ngx-change-sets/changes/changes.component.ts new file mode 100644 index 0000000..ba9490f --- /dev/null +++ b/projects/ngx-change-sets/changes/changes.component.ts @@ -0,0 +1,53 @@ +import { Component, computed, inject, input, InputSignal, LOCALE_ID, Signal } from '@angular/core'; +import { faArrowRightLong } from '@fortawesome/free-solid-svg-icons/faArrowRightLong'; +import { IconComponent, IconDefinition } from '@service-soft/ui/icon'; + +import { ChangeValueUtilities } from './change-value.utilities'; +import { ChangeView } from './change-view.model'; +import { ChangesConfig, ChangesLabels } from './changes-config.model'; +import { CHANGES_CONFIG } from './changes-config.provider'; +import { ValueChange } from './value-change.model'; + +/** + * The values that changed, each with its value before and after, formatted like the change sets show them: dates with + * their day and time in the LOCALE_ID of the app, or in the dateFormat of provideChangesConfig, lists of simple values on one line, objects as indented json and a dash for + * no value. Takes the changes of a change set as well as those an approval request would make: + * ``. Shows nothing without changes. + */ +@Component({ + selector: 'ngx-changes', + templateUrl: './changes.component.html', + imports: [IconComponent], + host: { + class: 'block' + } +}) +export class ChangesComponent { + private readonly config: ChangesConfig = inject(CHANGES_CONFIG); + + private readonly locale: string = inject(LOCALE_ID); + + /** + * The changes to show. + */ + readonly changes: InputSignal = input.required(); + + /** + * The texts to show. + */ + protected readonly labels: ChangesLabels = this.config.labels; + + /** + * The arrow between the values before and after. + */ + protected readonly arrow: IconDefinition = faArrowRightLong; + + /** + * The changes, formatted for reading. + */ + protected readonly views: Signal = computed(() => this.changes().map(change => ({ + key: change.key, + previousValue: ChangeValueUtilities.format(change.previousValue, this.config.dateFormat, this.locale), + newValue: ChangeValueUtilities.format(change.newValue, this.config.dateFormat, this.locale) + }))); +} \ No newline at end of file diff --git a/projects/ngx-change-sets/changes/changes.stories.ts b/projects/ngx-change-sets/changes/changes.stories.ts new file mode 100644 index 0000000..dc2d7c8 --- /dev/null +++ b/projects/ngx-change-sets/changes/changes.stories.ts @@ -0,0 +1,30 @@ +import { Meta, StoryObj } from '@storybook/angular'; + +import { ChangesComponent } from './changes.component'; +import { ValueChange } from './value-change.model'; + +// every kind of value: text, a number, a date, a list, an object, and values that are not there. +const CHANGES: ValueChange[] = [ + { key: 'status', previousValue: 'open', newValue: 'done' }, + { key: 'total', previousValue: 120.5, newValue: 99.9 }, + { key: 'deliveryDate', previousValue: '2026-10-10T00:00:00', newValue: '2026-10-14T00:00:00' }, + { key: 'labels', previousValue: ['urgent'], newValue: ['urgent', 'billing'] }, + { + key: 'address', + previousValue: { street: 'Main Street 1', city: 'Springfield' }, + newValue: { street: 'Elm Street 22', city: 'Riverside' } + }, + { key: 'note', previousValue: undefined, newValue: 'Leave it at the door' } +]; + +const meta: Meta = { + title: 'Change sets/Changes', + component: ChangesComponent, + args: { changes: CHANGES }, + render: args => ({ props: args, template: '' }) +}; +export default meta; + +type Story = StoryObj; + +export const Default: Story = {}; \ No newline at end of file diff --git a/projects/ngx-change-sets/changes/ng-package.json b/projects/ngx-change-sets/changes/ng-package.json new file mode 100644 index 0000000..70e0a80 --- /dev/null +++ b/projects/ngx-change-sets/changes/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} \ No newline at end of file diff --git a/projects/ngx-change-sets/changes/public-api.ts b/projects/ngx-change-sets/changes/public-api.ts new file mode 100644 index 0000000..aa2425e --- /dev/null +++ b/projects/ngx-change-sets/changes/public-api.ts @@ -0,0 +1,6 @@ +export * from './change-value.utilities'; +export * from './changes-config-changes.model'; +export * from './changes-config.model'; +export * from './changes-config.provider'; +export * from './changes.component'; +export * from './value-change.model'; \ No newline at end of file diff --git a/projects/ngx-change-sets/changes/value-change.model.ts b/projects/ngx-change-sets/changes/value-change.model.ts new file mode 100644 index 0000000..cf02459 --- /dev/null +++ b/projects/ngx-change-sets/changes/value-change.model.ts @@ -0,0 +1,7 @@ +import { Change } from 'zibri-contract'; + +/** + * A value that changed, or would change: its key, and its value before and after. A Change of a change set is one, and + * so is the ApprovalValueChangeModel of an approval request. + */ +export type ValueChange = Pick; \ No newline at end of file diff --git a/projects/ngx-change-sets/entity-field/change-sets-field-config.model.ts b/projects/ngx-change-sets/entity-field/change-sets-field-config.model.ts new file mode 100644 index 0000000..09e9bfe --- /dev/null +++ b/projects/ngx-change-sets/entity-field/change-sets-field-config.model.ts @@ -0,0 +1,9 @@ +/** + * The texts of the field of the change sets in a form of ngx-entity. + */ +export type ChangeSetsFieldConfig = { + /** + * What shows in place of the change sets of an entity that isn't created yet. + */ + createFirstLabel: string +}; \ No newline at end of file diff --git a/projects/ngx-change-sets/entity-field/change-sets-field-config.provider.ts b/projects/ngx-change-sets/entity-field/change-sets-field-config.provider.ts new file mode 100644 index 0000000..eb9e112 --- /dev/null +++ b/projects/ngx-change-sets/entity-field/change-sets-field-config.provider.ts @@ -0,0 +1,39 @@ +import { inject, InjectionToken, Provider } from '@angular/core'; + +import { ChangeSetsFieldConfig } from './change-sets-field-config.model'; + +/** + * The texts of the field of the change sets when nothing changes them. They are $localize, which an app translates like + * its own texts, and resolved once the config is injected, so translations an app loads at runtime apply as well. + * @returns The default config. + */ +function getDefaultChangeSetsFieldConfig(): ChangeSetsFieldConfig { + return { + createFirstLabel: $localize`:@@ngx-change-sets.entity-field.createFirstLabel:The changes show here once this is saved.` + }; +} + +/** + * The texts of every field of the change sets below this injector. Change them with provideChangeSetsFieldConfig. + */ +export const CHANGE_SETS_FIELD_CONFIG: InjectionToken = new InjectionToken( + 'CHANGE_SETS_FIELD_CONFIG', + { providedIn: 'root', factory: () => getDefaultChangeSetsFieldConfig() } +); + +/** + * Changes the texts of the field of the change sets, like to translate them. + * Provide it in the application config for the whole app, or in a component or route for only that part of it. + * Values you leave out are taken from the parent injector. + * @param config - The values to change. + * @returns The provider for CHANGE_SETS_FIELD_CONFIG. + */ +export function provideChangeSetsFieldConfig(config: Partial): Provider { + return { + provide: CHANGE_SETS_FIELD_CONFIG, + useFactory: (): ChangeSetsFieldConfig => ({ + ...inject(CHANGE_SETS_FIELD_CONFIG, { skipSelf: true, optional: true }) ?? getDefaultChangeSetsFieldConfig(), + ...config + }) + }; +} \ No newline at end of file diff --git a/projects/ngx-change-sets/entity-field/change-sets-field-data.model.ts b/projects/ngx-change-sets/entity-field/change-sets-field-data.model.ts new file mode 100644 index 0000000..03c6880 --- /dev/null +++ b/projects/ngx-change-sets/entity-field/change-sets-field-data.model.ts @@ -0,0 +1,20 @@ +/** + * The `data` of a `@Property.custom` of ngx-entity whose field is the ChangeSetsFieldComponent: where its change sets + * are undone, and what the user may do with them. + */ +export type ChangeSetsFieldData = { + /** + * The url the ChangeSetService sends the requests to, like '/api/orders'. It differs between types of entities. + */ + changeSetsApiBaseUrl: string, + /** + * Whether the user can undo change sets, never while the field is read only. The default comes from + * provideChangeSetsConfig. + */ + canResetAndRollback?: boolean, + /** + * Whether the name of who made a change set opens it, with openCreatedBy of the ChangeSetService. The default comes + * from provideChangeSetsConfig. + */ + canOpenCreatedBy?: boolean +}; \ No newline at end of file diff --git a/projects/ngx-change-sets/entity-field/change-sets-field.component.html b/projects/ngx-change-sets/entity-field/change-sets-field.component.html new file mode 100644 index 0000000..ef8b8e4 --- /dev/null +++ b/projects/ngx-change-sets/entity-field/change-sets-field.component.html @@ -0,0 +1,17 @@ + +

{{ label() }}

+@if (hint(); as hint) { +

{{ hint }}

+} +@if (changeSetEntity(); as changeSetEntity) { + + +} @else { +

{{ labels.createFirstLabel }}

+} diff --git a/projects/ngx-change-sets/entity-field/change-sets-field.component.spec.ts b/projects/ngx-change-sets/entity-field/change-sets-field.component.spec.ts new file mode 100644 index 0000000..2ad558b --- /dev/null +++ b/projects/ngx-change-sets/entity-field/change-sets-field.component.spec.ts @@ -0,0 +1,204 @@ +// the field in the editor of ngx-entity, like an app shows it. The questions before undoing render into the body. +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; +import { Component, inject, input, InputSignal, Service } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ChangeSetService, provideChangeSetService } from '@service-soft/ngx-change-sets/change-sets'; +import { EntityEditorComponent } from '@service-soft/ngx-entity/editor'; +import { EntityClass, Property } from '@service-soft/ngx-entity/entity'; +import { EntityService } from '@service-soft/ngx-entity/service'; +import { DialogTestingUtilities } from 'testing/dialog'; +import { FormTestingUtilities } from 'testing/form'; +import { PopoverTestingUtilities } from 'testing/popover'; +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; +import { ChangeSet, ChangeSetEntity, ChangeSetType, ResetChangeSetResult } from 'zibri-contract'; + +import { ChangeSetsFieldData } from './change-sets-field-data.model'; +import { ChangeSetsFieldComponent } from './change-sets-field.component'; + +class User { + @Property.string({ displayName: 'Id', omitForCreate: true, readonly: true, display: false }) + id!: string; + + @Property.string({ displayName: 'Name' }) + name!: string; + + @Property.custom({ + displayName: 'History', + component: async () => await Promise.resolve(ChangeSetsFieldComponent), + data: { changeSetsApiBaseUrl: '/api/users' } satisfies ChangeSetsFieldData, + position: { tab: 'last', tabName: 'History' } + }) + changeSets?: ChangeSet[]; +} + +@Service() +class UserService extends EntityService { + readonly entity: EntityClass = User; + readonly baseUrl: string = '/api/users'; +} + +@Service({ autoProvided: false }) +class TestChangeSetService extends ChangeSetService { + override openCreatedBy(): void {} +} + +function createChangeSet(id: string, changeSetType: ChangeSetType, createdAt: string, previousName: string | undefined, name: string): ChangeSet { + return { + id, + type: changeSetType, + createdAt: String(BigInt(new Date(createdAt).getTime()) * 1_000_000n), + changeSetEntityId: 'u1', + changes: [{ id: `${id}-0`, changeSetId: id, key: 'name', previousValue: previousName, newValue: name }] + }; +} + +const CREATED: ChangeSet = createChangeSet('1', ChangeSetType.CREATE, '2026-10-01T09:00:00', undefined, 'Jane Doe'); + +// renamed after it was created +const USER: User = { + id: 'u1', + name: 'Jane Smith', + changeSets: [CREATED, createChangeSet('2', ChangeSetType.UPDATE, '2026-10-02T09:00:00', 'Jane Doe', 'Jane Smith')] +}; + +// the renaming undone, as the server answers it +const RESET_USER: User & ChangeSetEntity = { + id: 'u1', + name: 'Jane Doe', + changeSets: [CREATED, createChangeSet('3', ChangeSetType.RESET, '2026-10-03T09:00:00', 'Jane Smith', 'Jane Doe')] +}; + +@Component({ + selector: 'ngx-host', + template: '', + imports: [EntityEditorComponent] +}) +class HostComponent { + readonly service: UserService = inject(UserService); + readonly user: InputSignal = input(); +} + +async function render(user: User | undefined): Promise { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + fixture.componentRef.setInput('user', user); + await fixture.whenStable(); + return fixture.nativeElement as HTMLElement; +} + +// renders, and lets the requests go out, which the tests answer. +async function settle(): Promise { + TestBed.tick(); + await new Promise(resolve => setTimeout(resolve)); + TestBed.tick(); +} + +// the fields load their components first. +async function findInput(root: HTMLElement, label: string): Promise { + return await vi.waitFor(() => { + TestBed.tick(); + const labelled: HTMLInputElement | undefined = FormTestingUtilities.findLabelledInput(root, label); + if (labelled == undefined) { + throw new TypeError(`No input labelled "${label}".`); + } + return labelled; + }); +} + +async function type(root: HTMLElement, label: string, text: string): Promise { + const labelled: HTMLInputElement = await findInput(root, label); + labelled.value = text; + labelled.dispatchEvent(new Event('input')); + await settle(); +} + +async function openHistory(root: HTMLElement): Promise { + await vi.waitFor(() => { + TestBed.tick(); + expect([...root.querySelectorAll('[role="tab"]')].map(tab => tab.textContent.trim())).toEqual(['General', 'History']); + }); + [...root.querySelectorAll('[role="tab"]')].find(tab => tab.textContent.trim() === 'History')?.click(); + await settle(); + const field: HTMLElement | null = root.querySelector('ngx-change-sets-field'); + if (field == undefined) { + throw new Error('The field of the change sets did not render.'); + } + return field; +} + +describe('ChangeSetsFieldComponent', () => { + let removeModalDialogs: () => void; + let removePopovers: () => void; + + beforeEach(() => { + removeModalDialogs = DialogTestingUtilities.addModalDialogs(); + // the menu that undoes a change set + removePopovers = PopoverTestingUtilities.addPopovers(); + TestBed.configureTestingModule({ + providers: [provideHttpClient(), provideHttpClientTesting(), provideChangeSetService(TestChangeSetService)] + }); + }); + + afterEach(() => { + TestBed.inject(HttpTestingController).verify(); + removeModalDialogs(); + removePopovers(); + for (const dialog of document.querySelectorAll('ui-dialog')) { + dialog.remove(); + } + }); + + test('shows the change sets of the entity on the last tab of its form, newest first', async () => { + const field: HTMLElement = await openHistory(await render(USER)); + + const summaries: string[] = [...field.querySelectorAll('summary')].map(summary => summary.textContent.replaceAll(/\s+/g, ' ').trim()); + expect(summaries.map(summary => summary.split(' ')[0])).toEqual(['Updated', 'Created']); + }); + + test('says that a new entity has no change sets yet, and creates it without them', async () => { + const root: HTMLElement = await render(undefined); + const field: HTMLElement = await openHistory(root); + expect(field.querySelector('ngx-change-sets')).toBeNull(); + expect(field.textContent).toContain('The changes show here once this is saved.'); + + await type(root, 'Name', 'Jane Doe'); + FormTestingUtilities.click(root, 'Save'); + await settle(); + const request: TestRequest = TestBed.inject(HttpTestingController).expectOne({ method: 'POST', url: '/api/users' }); + expect(request.request.body).toEqual({ name: 'Jane Doe' }); + request.flush({ id: 'u1', name: 'Jane Doe', changeSets: [CREATED] }); + }); + + test('shows the entity the server answered after a reset in the form, which then saves only what the user changes', async () => { + const root: HTMLElement = await render(USER); + const field: HTMLElement = await openHistory(root); + const http: HttpTestingController = TestBed.inject(HttpTestingController); + + // the menu of the newest change set + FormTestingUtilities.click(field.querySelector('details') ?? field, 'Reset'); + await settle(); + FormTestingUtilities.click(field.querySelector('ui-menu') ?? field, 'This change set'); + await vi.waitFor(() => { + TestBed.tick(); + expect(document.querySelector('dialog[open] h2')?.textContent.trim()).toBe('Reset this change set?'); + }); + FormTestingUtilities.click(document.querySelector('dialog[open]') ?? document, 'Reset'); + await settle(); + const reset: TestRequest = http.expectOne({ method: 'POST', url: '/api/users/u1/reset' }); + expect(reset.request.body).toEqual({ changeSetId: '2' }); + const result: ResetChangeSetResult = { entity: RESET_USER, changedValues: { name: 'Jane Doe' } }; + reset.flush(result); + await settle(); + + expect((await findInput(root, 'Name')).value).toBe('Jane Doe'); + expect([...field.querySelectorAll('summary')].map(summary => summary.textContent.trim().split(/\s/)[0])).toEqual(['Reset', 'Created']); + + await type(root, 'Name', 'Jane Miller'); + FormTestingUtilities.click(root, 'Save'); + await settle(); + const update: TestRequest = http.expectOne({ method: 'PATCH', url: '/api/users/u1' }); + // not the change sets, which differ from the ones the form started with, but not from what the server has + expect(update.request.body).toEqual({ name: 'Jane Miller' }); + update.flush({ ...RESET_USER, name: 'Jane Miller' }); + }); +}); \ No newline at end of file diff --git a/projects/ngx-change-sets/entity-field/change-sets-field.component.ts b/projects/ngx-change-sets/entity-field/change-sets-field.component.ts new file mode 100644 index 0000000..668ced6 --- /dev/null +++ b/projects/ngx-change-sets/entity-field/change-sets-field.component.ts @@ -0,0 +1,71 @@ +import { Component, computed, inject, Signal } from '@angular/core'; +import { CHANGE_SETS_CONFIG, ChangeSetsComponent, ChangeSetsConfig } from '@service-soft/ngx-change-sets/change-sets'; +import { PropertyMetadata } from '@service-soft/ngx-entity/entity'; +import { BaseEntityFieldDirective } from '@service-soft/ngx-entity/field-base'; +import { ChangeSet, ChangeSetEntity } from 'zibri-contract'; + +import { ChangeSetsFieldConfig } from './change-sets-field-config.model'; +import { CHANGE_SETS_FIELD_CONFIG } from './change-sets-field-config.provider'; +import { ChangeSetsFieldData } from './change-sets-field-data.model'; + +/** + * The change sets of an entity as a field of its form in ngx-entity, the component of a `@Property.custom` of its + * `changeSets` whose `data` is ChangeSetsFieldData. Undoing a change set hands the form the entity the server answered, + * which it shows and takes as saved. The user changes nothing else, so the change sets are never sent. An entity that + * isn't created yet has none, so its form says that they show once it is saved. + */ +@Component({ + selector: 'ngx-change-sets-field', + templateUrl: './change-sets-field.component.html', + imports: [ChangeSetsComponent], + host: { class: 'block' } +}) +export class ChangeSetsFieldComponent extends BaseEntityFieldDirective { + private readonly changeSetsConfig: ChangeSetsConfig = inject(CHANGE_SETS_CONFIG); + + /** + * The texts of the field. + */ + protected readonly labels: ChangeSetsFieldConfig = inject(CHANGE_SETS_FIELD_CONFIG); + + /** + * What the property gives the field in its data. + */ + protected readonly data: Signal = computed(() => { + const metadata: PropertyMetadata = this.property().metadata; + if (metadata.type !== 'custom') { + throw this.resolveKindError('custom'); + } + if (!this.isData(metadata.data)) { + throw new TypeError(`The change sets field of "${this.property().key}" needs the changeSetsApiBaseUrl in its data.`); + } + return metadata.data; + }); + + /** + * The entity whose change sets show, undefined while it isn't created yet. + */ + protected readonly changeSetEntity: Signal = computed(() => { + const id: string | undefined = this.entity().id; + return id == undefined ? undefined : { id, changeSets: this.value() ?? [] }; + }); + + /** + * Whether the user can undo change sets: never while the field is read only. + */ + protected readonly canResetAndRollback: Signal = computed(() => { + return !this.readonly() && (this.data().canResetAndRollback ?? this.changeSetsConfig.canResetAndRollback); + }); + + /** + * Whether the name of who made a change set opens it. + */ + protected readonly canOpenCreatedBy: Signal = computed(() => { + return this.data().canOpenCreatedBy ?? this.changeSetsConfig.canOpenCreatedBy; + }); + + // data is whatever the property says, so only its url is required to be there. + private isData(data: unknown): data is ChangeSetsFieldData { + return typeof data === 'object' && data != undefined && typeof Reflect.get(data, 'changeSetsApiBaseUrl') === 'string'; + } +} \ No newline at end of file diff --git a/projects/ngx-change-sets/entity-field/change-sets-field.stories.ts b/projects/ngx-change-sets/entity-field/change-sets-field.stories.ts new file mode 100644 index 0000000..d1f0eac --- /dev/null +++ b/projects/ngx-change-sets/entity-field/change-sets-field.stories.ts @@ -0,0 +1,123 @@ +import { HttpInterceptorFn, HttpRequest, HttpResponse, provideHttpClient, withInterceptors } from '@angular/common/http'; +import { ApplicationConfig, Component, inject, input, InputSignal, Service } from '@angular/core'; +import { ChangeSetService, provideChangeSetService } from '@service-soft/ngx-change-sets/change-sets'; +import { EntityEditorComponent } from '@service-soft/ngx-entity/editor'; +import { EntityClass, Property } from '@service-soft/ngx-entity/entity'; +import { EntityService } from '@service-soft/ngx-entity/service'; +import { applicationConfig, Meta, StoryObj } from '@storybook/angular'; +import { of } from 'rxjs'; +import { ChangeSet, ChangeSetEntity, ChangeSetType, ResetChangeSetResult } from 'zibri-contract'; + +import { ChangeSetsFieldData } from './change-sets-field-data.model'; +import { ChangeSetsFieldComponent } from './change-sets-field.component'; + +class Customer { + @Property.string({ displayName: 'Id', omitForCreate: true, readonly: true, display: false }) + id!: string; + + @Property.string({ displayName: 'Name' }) + name!: string; + + @Property.string({ displayName: 'Email', format: 'email' }) + email!: string; + + @Property.custom({ + displayName: 'History', + component: async () => await Promise.resolve(ChangeSetsFieldComponent), + data: { changeSetsApiBaseUrl: '/api/customers' } satisfies ChangeSetsFieldData, + position: { tab: 'last', tabName: 'History' } + }) + changeSets?: ChangeSet[]; +} + +@Service() +class CustomerService extends EntityService { + readonly entity: EntityClass = Customer; + readonly baseUrl: string = '/api/customers'; +} + +@Service({ autoProvided: false }) +class StoryChangeSetService extends ChangeSetService { + override openCreatedBy(): void {} +} + +function createChangeSet(id: string, type: ChangeSetType, createdAt: string, previousName: string | undefined, name: string): ChangeSet { + return { + id, + type, + createdAt: String(BigInt(new Date(createdAt).getTime()) * 1_000_000n), + changeSetEntityId: 'customer-1', + changes: [{ id: `${id}-0`, changeSetId: id, key: 'name', previousValue: previousName, newValue: name }] + }; +} + +const CREATED: ChangeSet = createChangeSet('1', ChangeSetType.CREATE, '2026-10-01T09:00:00', undefined, 'ACME'); + +const CUSTOMER: Customer & ChangeSetEntity = { + id: 'customer-1', + name: 'ACME Inc.', + email: 'mail@acme.example', + changeSets: [CREATED, createChangeSet('2', ChangeSetType.UPDATE, '2026-10-02T09:00:00', 'ACME', 'ACME Inc.')] +}; + +// the customer after undoing the renaming, which every undo answers here. +const UNDONE: Customer & ChangeSetEntity = { + ...CUSTOMER, + name: 'ACME', + changeSets: [CREATED, createChangeSet('3', ChangeSetType.RESET, '2026-10-03T09:00:00', 'ACME Inc.', 'ACME')] +}; + +// answers like the routes of a zibri api for customers and their change sets. +function answer(request: HttpRequest): object { + if (request.url.endsWith('/reset')) { + const result: ResetChangeSetResult = { entity: UNDONE, changedValues: { name: 'ACME' } }; + return result; + } + if (request.url.endsWith('/rollback')) { + return UNDONE; + } + // a create or a change + return { ...CUSTOMER, ...typeof request.body === 'object' ? request.body : {} }; +} + +const backend: HttpInterceptorFn = request => of(new HttpResponse({ status: 200, body: answer(request) })); + +// a component with the service, which the template of a story doesn't have. +@Component({ + selector: 'ngx-customer-editor', + template: '', + imports: [EntityEditorComponent] +}) +class CustomerEditorComponent { + protected readonly customerService: CustomerService = inject(CustomerService); + + readonly customer: InputSignal = input(); +} + +const providers: ApplicationConfig['providers'] = [ + provideHttpClient(withInterceptors([backend])), + provideChangeSetService(StoryChangeSetService) +]; + +const meta: Meta = { + title: 'Change sets/In an entity form', + component: ChangeSetsFieldComponent, + decorators: [applicationConfig({ providers })] +}; +export default meta; + +type Story = StoryObj; + +// the change sets on the last tab, whose undoing shows in every field. +export const Existing: Story = { + render: () => ({ + props: { customer: CUSTOMER }, + template: '', + moduleMetadata: { imports: [CustomerEditorComponent] } + }) +}; + +// a new entity, which has no change sets yet. +export const New: Story = { + render: () => ({ template: '', moduleMetadata: { imports: [CustomerEditorComponent] } }) +}; \ No newline at end of file diff --git a/projects/ngx-change-sets/entity-field/ng-package.json b/projects/ngx-change-sets/entity-field/ng-package.json new file mode 100644 index 0000000..70e0a80 --- /dev/null +++ b/projects/ngx-change-sets/entity-field/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} \ No newline at end of file diff --git a/projects/ngx-change-sets/entity-field/public-api.ts b/projects/ngx-change-sets/entity-field/public-api.ts new file mode 100644 index 0000000..fb1e007 --- /dev/null +++ b/projects/ngx-change-sets/entity-field/public-api.ts @@ -0,0 +1,4 @@ +export * from './change-sets-field-config.model'; +export * from './change-sets-field-config.provider'; +export * from './change-sets-field-data.model'; +export * from './change-sets-field.component'; \ No newline at end of file diff --git a/projects/ngx-change-sets/locale/messages.de.xlf b/projects/ngx-change-sets/locale/messages.de.xlf new file mode 100644 index 0000000..c06d8f6 --- /dev/null +++ b/projects/ngx-change-sets/locale/messages.de.xlf @@ -0,0 +1,119 @@ + + + + + + Created at + Erstellt am + + + Created by + Erstellt von + + + Property + Eigenschaft + + + New value + Neuer Wert + + + Previous value + Vorheriger Wert + + + Reset + Zurücksetzen + + + This change set + Diese Änderung + + + Cancel + Abbrechen + + + Reset + Zurücksetzen + + + This deletes the change set and can't be undone. The change sets after it are kept. + Dadurch wird die Änderung gelöscht. Das kann nicht rückgängig gemacht werden. Die Änderungen danach bleiben erhalten. + + + Reset this change set? + Diese Änderung zurücksetzen? + + + Cancel + Abbrechen + + + Rollback + Wiederherstellen + + + This undoes and deletes every newer change set and can't be undone. + Dadurch werden alle neueren Änderungen rückgängig gemacht und gelöscht. Das kann nicht rückgängig gemacht werden. + + + Rollback to the state after this change set? + Den Stand nach dieser Änderung wiederherstellen? + + + Rollback all to this state + Diesen Stand wiederherstellen + + + Show more + Mehr anzeigen + + + System + System + + + Created + Erstellt + + + Deleted + Gelöscht + + + Replaced + Ersetzt + + + Reset + Zurückgesetzt + + + Restored + Wiederhergestellt + + + Updated + Aktualisiert + + + Property + Eigenschaft + + + New value + Neuer Wert + + + Previous value + Vorheriger Wert + + + The changes show here once this is saved. + Die Änderungen werden hier angezeigt, sobald gespeichert wurde. + + + + diff --git a/projects/ngx-change-sets/ng-package.json b/projects/ngx-change-sets/ng-package.json index a191674..c98f1e6 100644 --- a/projects/ngx-change-sets/ng-package.json +++ b/projects/ngx-change-sets/ng-package.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/ng-packagr/ng-package.schema.json", - "assets": ["tailwind.css"], + "assets": ["tailwind.css", "locale/messages.de.xlf", "CHANGELOG.md"], "dest": "../../dist/ngx-change-sets", "lib": { "entryFile": "src/public-api.ts" diff --git a/projects/ngx-change-sets/package.json b/projects/ngx-change-sets/package.json index 413f688..fbfe12a 100644 --- a/projects/ngx-change-sets/package.json +++ b/projects/ngx-change-sets/package.json @@ -1,6 +1,6 @@ { "name": "@service-soft/ngx-change-sets", - "version": "22.3.2", + "version": "22.4.0", "license": "MIT", "repository": { "type": "git", @@ -23,9 +23,18 @@ "@angular/core": "^22.2.0", "@angular/localize": "^22.2.0", "@fortawesome/free-solid-svg-icons": "^7.3.1", - "@service-soft/ui": "^22.3.2", + "@service-soft/ngx-entity": "^22.4.0", + "@service-soft/ui": "^22.4.0", "tailwindcss": "^4.3.3", - "zibri-contract": "^3.1.0" + "zibri-contract": "^3.3.0" }, - "sideEffects": false + "peerDependenciesMeta": { + "@service-soft/ngx-entity": { + "optional": true + } + }, + "sideEffects": false, + "translations": { + "de": "./locale/messages.de.xlf" + } } \ No newline at end of file diff --git a/projects/ngx-ecommerce/CHANGELOG.md b/projects/ngx-ecommerce/CHANGELOG.md new file mode 100644 index 0000000..040dd3e --- /dev/null +++ b/projects/ngx-ecommerce/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +## 22.4.0 + +### Features +- The German translation of the texts ships with the package (`locale/messages.de.xlf`). +- Icons are imported from one file each, so a page only loads the icons it shows. diff --git a/projects/ngx-ecommerce/README.md b/projects/ngx-ecommerce/README.md index 13167bc..b4dc5f0 100644 --- a/projects/ngx-ecommerce/README.md +++ b/projects/ngx-ecommerce/README.md @@ -139,5 +139,7 @@ A backend that calculates differently, like the tax per line, can end up a cent # Translating The default texts are `$localize` with an id of their own, like `@@ngx-ecommerce.order-summary.total`, so `ng extract-i18n` puts them into the messages of your app, and you translate them like its own texts. The library needs `@angular/localize` for that, `ng add @angular/localize`, also in an app of one language. A build with `localize` fills the texts in, so no part of `@angular/localize` reaches the browser. The defaults are made once a config is injected, so translations an app loads at runtime with `loadTranslations` apply as well. A text of `provideInputExtrasConfig` or `provideOrderSummaryConfig` replaces the default in every language. So translate a default in your messages, and change it in the config only to say something else: a default the config replaces stays in your messages, though nothing shows it. +German ships with the library: `locale/messages.de.xlf` of the package is an XLIFF 1.2 file with a German target for each of its texts, and its `package.json` names it in `"translations": { "de": "./locale/messages.de.xlf" }`. A merge of the translations of an app's dependencies reads that field and fills these targets into the German messages of the app, so German needs no translation of your own. Only the texts your app uses end up there, since its `ng extract-i18n` decides which units its messages have. Other languages you translate in your messages. + # License MIT. \ No newline at end of file diff --git a/projects/ngx-ecommerce/input-extras/input-extras.component.ts b/projects/ngx-ecommerce/input-extras/input-extras.component.ts index 000a279..05fc0ce 100644 --- a/projects/ngx-ecommerce/input-extras/input-extras.component.ts +++ b/projects/ngx-ecommerce/input-extras/input-extras.component.ts @@ -1,5 +1,7 @@ import { afterEveryRender, afterRenderEffect, booleanAttribute, Component, computed, ElementRef, inject, input, InputSignal, InputSignalWithTransform, LOCALE_ID, model, ModelSignal, Signal, signal, viewChildren, WritableSignal } from '@angular/core'; -import { faCheck, faMinus, faPlus } from '@fortawesome/free-solid-svg-icons'; +import { faCheck } from '@fortawesome/free-solid-svg-icons/faCheck'; +import { faMinus } from '@fortawesome/free-solid-svg-icons/faMinus'; +import { faPlus } from '@fortawesome/free-solid-svg-icons/faPlus'; import { MoneyUtilities } from '@service-soft/ngx-ecommerce/money'; import { ButtonComponent } from '@service-soft/ui/button'; import { IconComponent, IconDefinition } from '@service-soft/ui/icon'; diff --git a/projects/ngx-ecommerce/input-extras/input-extras.stories.ts b/projects/ngx-ecommerce/input-extras/input-extras.stories.ts index 43c48a9..fb41878 100644 --- a/projects/ngx-ecommerce/input-extras/input-extras.stories.ts +++ b/projects/ngx-ecommerce/input-extras/input-extras.stories.ts @@ -1,6 +1,10 @@ import { JsonPipe } from '@angular/common'; import { LOCALE_ID } from '@angular/core'; -import { faBicycle, faCar, faMugHot, faPaw, faSoap } from '@fortawesome/free-solid-svg-icons'; +import { faBicycle } from '@fortawesome/free-solid-svg-icons/faBicycle'; +import { faCar } from '@fortawesome/free-solid-svg-icons/faCar'; +import { faMugHot } from '@fortawesome/free-solid-svg-icons/faMugHot'; +import { faPaw } from '@fortawesome/free-solid-svg-icons/faPaw'; +import { faSoap } from '@fortawesome/free-solid-svg-icons/faSoap'; import { applicationConfig, Meta, moduleMetadata, StoryObj } from '@storybook/angular'; import { ExtraOption } from './extra-option.model'; diff --git a/projects/ngx-ecommerce/locale/messages.de.xlf b/projects/ngx-ecommerce/locale/messages.de.xlf new file mode 100644 index 0000000..bed957e --- /dev/null +++ b/projects/ngx-ecommerce/locale/messages.de.xlf @@ -0,0 +1,71 @@ + + + + + + Remove one + Eins weniger + + + Add one + Eins mehr + + + Extras + Extras + + + once + einmalig + + + per day + pro Tag + + + each + pro Stück + + + Amount + Betrag + + + Order summary + Bestellübersicht + + + Includes VAT + Enthaltene MwSt. + + + Item + Artikel + + + Net total + Nettosumme + + + Quantity + Menge + + + Subtotal + Zwischensumme + + + VAT + MwSt. + + + Total + Gesamt + + + Unit price + Einzelpreis + + + + diff --git a/projects/ngx-ecommerce/ng-package.json b/projects/ngx-ecommerce/ng-package.json index 5093328..59f8d76 100644 --- a/projects/ngx-ecommerce/ng-package.json +++ b/projects/ngx-ecommerce/ng-package.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/ng-packagr/ng-package.schema.json", - "assets": ["tailwind.css"], + "assets": ["tailwind.css", "locale/messages.de.xlf", "CHANGELOG.md"], "dest": "../../dist/ngx-ecommerce", "lib": { "entryFile": "src/public-api.ts" diff --git a/projects/ngx-ecommerce/package.json b/projects/ngx-ecommerce/package.json index 5f473f1..a1d53a9 100644 --- a/projects/ngx-ecommerce/package.json +++ b/projects/ngx-ecommerce/package.json @@ -1,6 +1,6 @@ { "name": "@service-soft/ngx-ecommerce", - "version": "22.3.2", + "version": "22.4.0", "license": "MIT", "repository": { "type": "git", @@ -23,8 +23,11 @@ "@angular/core": "^22.2.0", "@angular/localize": "^22.2.0", "@fortawesome/free-solid-svg-icons": "^7.3.1", - "@service-soft/ui": "^22.3.2", + "@service-soft/ui": "^22.4.0", "tailwindcss": "^4.3.3" }, - "sideEffects": false + "sideEffects": false, + "translations": { + "de": "./locale/messages.de.xlf" + } } \ No newline at end of file diff --git a/projects/ngx-entity/CHANGELOG.md b/projects/ngx-entity/CHANGELOG.md new file mode 100644 index 0000000..7c19c80 --- /dev/null +++ b/projects/ngx-entity/CHANGELOG.md @@ -0,0 +1,27 @@ +# Changelog + +## 22.4.0 + +### Breaking changes +- `@angular/aria` ^22.2.0 is a new peer dependency: install it. +- The peer `zibri-contract` is `^3.3.0`, was `^3.1.0`, like in every library of `@service-soft`. +- `entity` of `BaseEntityFieldDirective` and `EntityFieldComponent` is a `model()` instead of an `input()`, so a field + can replace the whole entity. Bindings keep working; a field that declares `entity` itself has to declare it as a + `model.required()`. +- `PropertyPosition.tab` is `number | 'last'`. Code that reads it as a number has to handle `'last'`. +- The display styles and `EntityFieldKind` have new members, and the metadata of string, number and chips array + properties has the new keys `enumLabels` and `autocomplete`. Exhaustive switches over them, and code that builds the + metadata by hand, have to add them. + +### Features +- `enumLabels` for enums of strings, numbers and chips: the labels show in selects, chips, table cells and filters. + Type `EnumLabels`. +- The display styles `'segmented'` and `'cards'` for enums, the second one with + `@service-soft/ngx-entity/field-cards`. +- `autocomplete` for string properties. +- Every field passes the name of its property to its native control as `name`, for form drafts and the autofill of the + browser. +- `position.tab: 'last'`. +- A field can replace the entity: `(replaced)` of `ngx-entity-form` and `ngx-entity-form-rows`, and the editor treats + the replaced entity as saved. +- The German translation of the texts ships with the package (`locale/messages.de.xlf`). diff --git a/projects/ngx-entity/README.md b/projects/ngx-entity/README.md index 6cc592a..3675e1c 100644 --- a/projects/ngx-entity/README.md +++ b/projects/ngx-entity/README.md @@ -35,10 +35,12 @@ A table shows the entities a page at a time from the server, with the columns, o Angular 22 with `@angular/localize`, which [translates the texts](#translating), and Tailwind CSS 4. The models shared with zibri, like `PaginationResult`, `FilterConfig` and `ValidationProblem`, come from [zibri-contract](https://www.npmjs.com/package/zibri-contract). ```sh -npm install @service-soft/ngx-entity @service-soft/ui @service-soft/ngx-error-handling zibri-contract +npm install @service-soft/ngx-entity @service-soft/ui @service-soft/ngx-error-handling zibri-contract @angular/aria ng add @angular/localize ``` +`@angular/aria` is the select, the autocomplete and the chips of `@service-soft/ui`. Every kind of field is its own chunk, which a page only loads once it shows a property of that kind, but the build resolves all of them, so it needs `@angular/aria` even when your entities have none of those fields. + The decorators need `"experimentalDecorators": true` in your `tsconfig.json`, like zibri. To [work offline](#working-offline), install `@service-soft/ngx-pwa` as well. # Setup @@ -87,16 +89,35 @@ The entities themselves don't have to be instances of the class: the class only | `omitForCreate` | `boolean` | `false` — whether the form that creates an entity leaves the field out, like an id the server sets | | `omitForUpdate` | `boolean` | `false` — whether the form that edits an entity leaves the field out | | `defaultWidths` | `[lg, md, sm]`, each `1` to `12` | `[6, 6, 12]` — the columns the field takes on large, medium and small screens | -| `position` | `{ tab?, tabName?, row?, order? }` | none — see [the form](#the-form-of-an-entity) | +| `position` | `{ tab?, tabName?, row?, order? }`, `tab` a number or `'last'` | none — see [the form](#the-form-of-an-entity) | | `default` | a value, or a function that creates it | none — the value a new entity starts with | ## Strings -`@Property.string` takes `minLength`, `maxLength`, `regex` (a `RegExp` or its source, matching the whole value), `format` (`'uuid'`, `'email'` or `'phone'`, which sets the type of the input), `password` and `enum`, which makes the field a select of the values of the enum. `displayStyle: 'textarea'` gives a field of several lines instead of one. `displayStyle: 'autocomplete'` with `options`, a list of strings or a function of the entity that returns one, suggests the options that contain the text; any text is the value, with the rules of the string, unless `restrictToOptions: true` makes only an option one. +`@Property.string` takes `minLength`, `maxLength`, `regex` (a `RegExp` or its source, matching the whole value), `format` (`'uuid'`, `'email'` or `'phone'`, which sets the type of the input), `password` and `enum`, which makes the field a select of the values of the enum. `displayStyle: 'textarea'` gives a field of several lines instead of one. `displayStyle: 'autocomplete'` with `options`, a list of strings or a function of the entity that returns one, suggests the options that contain the text; any text is the value, with the rules of the string, unless `restrictToOptions: true` makes only an option one. `autocomplete` tells the browser what a field of one line holds, so it fills it in, like `'name'`, `'email'` or `'tel'` of a contact form. + +A member of an `enum` shows its value, unless `enumLabels` gives it a label, by its value. With `displayStyle: 'segmented'` the members are one row of segments instead of a select, for two to five short ones, and with `displayStyle: 'cards'` they are cards; both are the `ui-input-cards` of `@service-soft/ui/input-cards` with that `appearance`, and need an `enum`: + +```ts +@Property.string({ + displayName: $localize`What is it about?`, + enum: ContactTopic, + enumLabels: { + [ContactTopic.SOFTWARE]: $localize`Software`, + [ContactTopic.TAKEOVER]: $localize`Takeover`, + [ContactTopic.WEBSITE]: $localize`Website`, + [ContactTopic.OTHER]: $localize`Something else` + }, + displayStyle: 'segmented' +}) +topic!: ContactTopic; +``` + +The labels show wherever the members do: in the select, the segments or cards, the chips of an array, and the cells and filters of a table. `password: true`, like zibri's password strings, makes it the field of a new password: hidden, with how hard it is to guess (`passwordStrength: false` turns that off) and a second input that has to repeat it (`confirmation: false` turns that off, `confirmationDisplayName` names it). Only the password is sent. The service leaves it out of what the server answers, which would be its hash, so the form of an existing entity starts empty, isn't required there, and keeps the stored password while it stays empty. The texts are `provideEntityPasswordFieldConfig({ confirmationLabel, mismatchMessage })` of `@service-soft/ngx-entity/field-password`; the ones of the strength are `passwordStrengthLabels` of `provideInputConfig`. ## Numbers -`@Property.number` takes `min`, `max`, `format` (`'number'`, or `'integer'` for whole numbers) and `enum`, which makes the field a select that shows the names of the members. `displayStyle: 'slider'` shows a slider between `min` and `max`, which it needs both of; without a `default` it starts at `min`, since it always shows a value. +`@Property.number` takes `min`, `max`, `format` (`'number'`, or `'integer'` for whole numbers) and `enum`, which makes the field a select that shows the names of the members, or the labels `enumLabels` gives them by their values, like `{ [Priority.HIGH]: 'High' }`. `displayStyle: 'segmented'` or `'cards'` shows them as segments or cards, like [a string](#strings). `displayStyle: 'slider'` shows a slider between `min` and `max`, which it needs both of; without a `default` it starts at `min`, since it always shows a value. ## Booleans `@Property.boolean` is `false` by default, as an unchecked checkbox is. `required` only says that the property is sent, which it always is; `mustBeChecked`, a boolean or a function of the entity, makes the user check it, like accepting the terms. `displayStyle` is `'checkbox'` or `'switch'`, by default what the inputs of ui use. @@ -113,7 +134,7 @@ The entities themselves don't have to be instances of the class: the class only ## Arrays `@Property.array({ displayName: 'Tags', items: { type: 'string' } })`, like zibri's, shows by what its items are: -- `type: 'string'` or `'number'`: chips. Typed in and taken with Enter, with the rules of the items (`minLength`, `maxLength`, `regex`; `min`, `max`, `format`), whose error shows at the input while a typed text breaks them. `options` are strings the input suggests, which `restrictToOptions: true` makes the only ones; an `enum` makes its members the only ones. +- `type: 'string'` or `'number'`: chips. Typed in and taken with Enter, with the rules of the items (`minLength`, `maxLength`, `regex`; `min`, `max`, `format`), whose error shows at the input while a typed text breaks them. `options` are strings the input suggests, which `restrictToOptions: true` makes the only ones; an `enum` makes its members the only ones, named by `enumLabels` like [a string](#strings). - `type: 'date'` or `'dateRange'`: a table, each item with a button that removes it, and below it the inputs and the button that add one, between `after` and `before`; `displayStyle: 'datetime'` asks for times as well. A `DateRange` is `{ start, end }`, which on the server is an object with these two dates. - `type: 'object'` with `cls: () => Position`: a table of the objects, each with buttons that edit and remove it, and a button that adds one. Adding and editing happen in a dialog with the fields of the class, which starts with its defaults. `columns` names the properties the table shows, else it shows every one the form displays. @@ -208,7 +229,7 @@ It gets the values of a new entity too, so any of them may still be missing. Rea ``` -The header of a column is the `displayName` of its property, and its text the value formatted by its type: a number and a date in the locale of the app, a boolean as yes or no, an enum by its member, a relation by the label of the other entity, when the read included it (zibri's `defaultRelations`). Give a column as `{ key, label, value, cell }` to change any of them, like a cell with a template of its own. A column can be ordered by when the order config of the service names it, or, when the service has none, unless it is a relation, like zibri's default. Its filter comes from the filter config: a text input for `iLike`, `fuzzy` and `equals` of a string, a select for `oneOf` and `equals` of an enum and for a boolean. A `range` has no input in the table. +The header of a column is the `displayName` of its property, and its text the value formatted by its type: a number and a date in the locale of the app, a boolean as yes or no, an enum by the label of its member, a relation by the label of the other entity, when the read included it (zibri's `defaultRelations`). Give a column as `{ key, label, value, cell }` to change any of them, like a cell with a template of its own. A column can be ordered by when the order config of the service names it, or, when the service has none, unless it is a relation, like zibri's default. Its filter comes from the filter config: a text input for `iLike`, `fuzzy` and `equals` of a string, a select for `oneOf` and `equals` of an enum and for a boolean. A `range` has no input in the table. | Input | Values | Default | |---|---|---| @@ -274,7 +295,9 @@ protected async save(): Promise { | `mode` | `'create'` or `'update'` | `'create'` — which of `omitForCreate` and `omitForUpdate` applies | | `problems` | `ValidationProblem[]` | `[]` — the problems of zibri's error response, shown at the field of their `key` | -`ngx-entity-editor` of `@service-soft/ngx-entity/editor` does all of this for you: a heading, the form, and the buttons that save and cancel. It saves with the service, shows the problems zibri answered at their fields, and emits `(saved)` with the entity the server saved and `(cancelled)`. `hasUnsavedChanges()` says whether to ask before you leave it. The dialogs and pages are built on it; use it for a page of your own: +A field can replace the whole entity, like the history of [@service-soft/ngx-change-sets](https://www.npmjs.com/package/@service-soft/ngx-change-sets) with the entity the server answered after undoing a change set. The form then shows its values in every field, drops the problems, and emits it with `(replaced)`: it is what the server has now, so compare the values with it from then on, like `(replaced)="original = $event"`, and the next `update` sends only what the user changed after it. + +`ngx-entity-editor` of `@service-soft/ngx-entity/editor` does all of this for you: a heading, the form, and the buttons that save and cancel. It saves with the service, shows the problems zibri answered at their fields, and emits `(saved)` with the entity the server saved and `(cancelled)`. `hasUnsavedChanges()` says whether to ask before you leave it. An entity a field replaced the values with is what it compares and saves against from then on, so it is no unsaved change. The dialogs and pages are built on it; use it for a page of your own: ```html @@ -282,7 +305,7 @@ protected async save(): Promise { Without an `entity` it creates one, and without a `title` its heading is the `createTitle` or `editTitle` of `provideEntityFormConfig`. The heading is an `h2`, for a dialog or below the heading of a page; `[headingLevel]="1"` makes it the heading of the page, like the pages of ngx-entity do. -Every row is a grid of 12 columns, in which each field takes the columns of its `defaultWidths`; on a small screen the fields stack, unless their widths say otherwise. `position` places a field: on a `tab` (from 1, the first by default), named by the `tabName` of one of its fields; in a `row` of that tab; and at an `order` inside the row. The fields without a row share one after the others, and the fields without an order come last in their row; otherwise they keep the order of the class. A form whose fields are all on one tab shows no tabs. The fields of every tab belong to the form, also of one the user never opened: when one of them is invalid, saving opens its tab and focuses it. +Every row is a grid of 12 columns, in which each field takes the columns of its `defaultWidths`; on a small screen the fields stack, unless their widths say otherwise. `position` places a field: on a `tab` (from 1, the first by default), named by the `tabName` of one of its fields; in a `row` of that tab; and at an `order` inside the row. `tab: 'last'` is the tab after every numbered one, wherever the property is in the class, like a history: unnamed, its label is the one of the number after the highest tab of the class, `Tab 3` after tab 2. The fields without a row share one after the others, and the fields without an order come last in their row; otherwise they keep the order of the class. A form whose fields are all on one tab shows no tabs. The fields of every tab belong to the form, also of one the user never opened: when one of them is invalid, saving opens its tab and focuses it. # Pages of an entity A table with `edit="page"` creates an entity on the page at `new` below its route, and edits one on the page at its id. `EntityRouteUtilities.resolveRoutes` of `@service-soft/ngx-entity/routes` builds both routes; put them next to the route of the table: @@ -311,7 +334,7 @@ The page loads the entity with the service, shows it in the editor, and goes bac `UnsavedChangesService.askToDiscard()` asks the same question from code, like the dialogs do on Cancel. The dialog it asks in is loaded when it is first asked. # Fields of your own -Each kind of field is a component of its own: `string`, `password`, `textarea`, `autocomplete`, `select`, `number`, `slider`, `boolean`, `date`, `dateRange`, `chips`, `dateArray` and `objectArray`, which a form loads the first time it shows a property of that kind. Replace a kind with your own with `provideEntityFields` of `@service-soft/ngx-entity/field`, as an `import()`, so only the pages that show it load it: +Each kind of field is a component of its own: `string`, `password`, `textarea`, `autocomplete`, `select`, `cards` (the segments or cards of an enum, from `@service-soft/ngx-entity/field-cards`), `number`, `slider`, `boolean`, `date`, `dateRange`, `chips`, `dateArray` and `objectArray`, which a form loads the first time it shows a property of that kind. Replace a kind with your own with `provideEntityFields` of `@service-soft/ngx-entity/field`, as an `import()`, so only the pages that show it load it: ```ts provideEntityFields({ date: async () => (await import('./calendar-field.component')).CalendarFieldComponent }) @@ -319,6 +342,8 @@ provideEntityFields({ date: async () => (await import('./calendar-field.componen Your component extends `BaseEntityFieldDirective` of `@service-soft/ngx-entity/field-base`. It gets the `property`, the values of the whole `entity`, `required`, `readonly` and the `problem` of the server, and binds the `value` two-way. `ngx-entity-field` shows a single field the same way, outside of a form. +The `entity` is bound two-way as well, for a component with an `entityChange`, like one extending `BaseEntityFieldDirective`; one that declares the inputs itself gets it as an input. A field that gets the whole entity from the server, like after undoing a change set, sets it with `this.entity.set(entity)`, as the json the server answered. The form makes its dates like the service does, shows it in every field, and [takes it as saved](#the-form-of-an-entity). Only a field of the entity itself replaces it: a field of an object in it gets the object as its `entity`. + A single property gets a field of its own with `@Property.custom`, loaded the first time a form shows it: ```ts @@ -326,7 +351,7 @@ A single property gets a field of its own with `@Property.custom`, loaded the fi color!: string; ``` -`data` is whatever else the component needs, which it reads from `property().metadata.data`. The value is sent like any other; a table shows it when it is a text, else a column gives its `value`. +`data` is whatever else the component needs, which it reads from `property().metadata.data`. The value is sent like any other: `update` sends it when it changed, `create` when the values have it. So a value the component never changes, like change sets, is never sent. A table shows it when it is a text, else a column gives its `value`. # Configuration | Provider | Changes | @@ -345,6 +370,8 @@ The texts of the fields themselves, like the error messages, come from `provideI ## Translating The default texts are `$localize` with an id of their own, like `@@ngx-entity.table.deleteLabel`, so `ng extract-i18n` puts them into the messages of your app, and you translate them like its own texts. The library needs `@angular/localize` for that, `ng add @angular/localize`, also in an app of one language. A build with `localize` fills the texts in, so no part of `@angular/localize` reaches the browser. The defaults are made once a config is injected, so translations an app loads at runtime with `loadTranslations` apply as well. A text of `provideXConfig` replaces the default in every language. So translate a default in your messages, and change it in the config only to say something else: a default the config replaces stays in your messages, though nothing shows it. +German ships with the library: `locale/messages.de.xlf` of the package is an XLIFF 1.2 file with a German target for each of its texts, and its `package.json` names it in `"translations": { "de": "./locale/messages.de.xlf" }`. A merge of the translations of an app's dependencies reads that field and fills these targets into the German messages of the app, so German needs no translation of your own. Only the texts your app uses end up there, since its `ng extract-i18n` decides which units its messages have. Other languages you translate in your messages, like the texts of your entities. + # Moving from ngx-material-entity It is not finished: many-to-many relations and files (which wait for the next major version of zibri) are still to come. What changed so far: - Import and export are `canImport` and `canExport` of the table instead of `allowJsonImport` and the multi select actions. The import posts to the same `/import` route with the same `import` field. diff --git a/projects/ngx-entity/dialog/entity-dialog.service.spec.ts b/projects/ngx-entity/dialog/entity-dialog.service.spec.ts index f7b0802..269521f 100644 --- a/projects/ngx-entity/dialog/entity-dialog.service.spec.ts +++ b/projects/ngx-entity/dialog/entity-dialog.service.spec.ts @@ -1,9 +1,10 @@ // the DialogService renders the dialogs into the body, so the tests find them there. import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting, TestRequest } from '@angular/common/http/testing'; -import { Injectable } from '@angular/core'; +import { Component, Injectable } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { EntityClass, Property } from '@service-soft/ngx-entity/entity'; +import { BaseEntityFieldDirective } from '@service-soft/ngx-entity/field-base'; import { EntityService } from '@service-soft/ngx-entity/service'; import { DialogTestingUtilities } from 'testing/dialog'; import { FormTestingUtilities } from 'testing/form'; @@ -29,6 +30,31 @@ class TaskService extends EntityService { const TASK: Task = { id: 'a1', title: 'Write the docs' }; +// the task as the server has it after somebody else changed it, which a field loads. +const CHANGED_TASK: Task = { id: 'a1', title: 'Write the README' }; + +@Component({ + selector: 'ngx-reload-field', + template: '' +}) +class ReloadFieldComponent extends BaseEntityFieldDirective { + protected readonly changedTask: Task = CHANGED_TASK; +} + +class NotedTask extends Task { + @Property.string({ displayName: 'Notes', required: false }) + notes?: string; + + @Property.custom({ displayName: 'Server', component: async () => await Promise.resolve(ReloadFieldComponent) }) + server?: unknown; +} + +@Injectable({ providedIn: 'root' }) +class NotedTaskService extends EntityService { + readonly entity: EntityClass = NotedTask; + readonly baseUrl: string = '/api/tasks'; +} + // renders, and lets the requests of the dialog go out, which the tests answer. async function settle(): Promise { TestBed.tick(); @@ -157,6 +183,31 @@ describe('EntityDialogService', () => { expect(await unchanged).toBeUndefined(); }); + test('takes the entity a field replaced the values with as saved, and then sends only what the user changed', async () => { + const service: EntityDialogService = TestBed.inject(EntityDialogService); + const discarded: Promise = service.edit(TestBed.inject(NotedTaskService), TASK); + await type('Title', 'Something else'); + FormTestingUtilities.click(findDialog() ?? document, 'Reload'); + await settle(); + expect((await findInput('Title')).value).toBe('Write the README'); + // nothing to lose, so cancel asks nothing + FormTestingUtilities.click(findDialog() ?? document, 'Cancel'); + expect(await discarded).toBeUndefined(); + + const edited: Promise = service.edit(TestBed.inject(NotedTaskService), TASK); + await findInput('Title'); + FormTestingUtilities.click(findDialog() ?? document, 'Reload'); + await settle(); + await type('Notes', 'Ask the team'); + FormTestingUtilities.click(findDialog() ?? document, 'Save'); + await settle(); + const request: TestRequest = TestBed.inject(HttpTestingController).expectOne({ method: 'PATCH', url: '/api/tasks/a1' }); + // not the title, which the server has already + expect(request.request.body).toEqual({ notes: 'Ask the team' }); + request.flush({ ...CHANGED_TASK, notes: 'Ask the team' }); + expect(await edited).toEqual({ ...CHANGED_TASK, notes: 'Ask the team' }); + }); + test('deletes an entity once the user confirms, and nothing when they cancel', async () => { const service: EntityDialogService = TestBed.inject(EntityDialogService); const http: HttpTestingController = TestBed.inject(HttpTestingController); diff --git a/projects/ngx-entity/editor/entity-editor.component.html b/projects/ngx-entity/editor/entity-editor.component.html index 520807e..0c13fd6 100644 --- a/projects/ngx-entity/editor/entity-editor.component.html +++ b/projects/ngx-entity/editor/entity-editor.component.html @@ -4,7 +4,7 @@

{{ heading() }}

} @else {

{{ heading() }}

} - +
diff --git a/projects/ngx-entity/editor/entity-editor.component.ts b/projects/ngx-entity/editor/entity-editor.component.ts index ac1b7a7..1436e8d 100644 --- a/projects/ngx-entity/editor/entity-editor.component.ts +++ b/projects/ngx-entity/editor/entity-editor.component.ts @@ -83,14 +83,15 @@ export class EntityEditorComponent { }); /** - * The values the form started with: the entity, or the defaults of a new one. + * The values the server has: the entity, or the defaults of a new one, until a field of the form replaces them with + * the entity the server answered, like after undoing a change set. */ - private readonly original: Signal> = computed(() => { + private readonly original: WritableSignal> = linkedSignal(() => { return this.entity() ?? { ...EntityUtilities.resolveDefaults(this.entityClass()), ...this.createValues() }; }); /** - * The values of the form, which start again with every entity it gets. + * The values of the form, which start again with every entity it gets or a field replaces it with. */ protected readonly value: WritableSignal> = linkedSignal(() => this.original()); @@ -116,6 +117,16 @@ export class EntityEditorComponent { return Object.keys(EntityUtilities.resolveChanges(this.entityClass(), saved, this.value())).length > 0; } + /** + * Takes the entity a field of the form replaced the values with as what the server has, so it is no unsaved change + * and saving sends only what the user changes after it. + * @param entity - The entity. + */ + protected replace(entity: Partial): void { + this.original.set(entity); + this.savedValue.set(undefined); + } + /** * Saves the entity and emits it. The problems of values the server refused show at their fields; any other error * goes on to the ErrorHandler. @@ -125,7 +136,10 @@ export class EntityEditorComponent { const entity: T | undefined = this.entity(); this.saving.set(true); try { - const saved: T = entity == undefined ? await service.create(this.value()) : await service.update(entity, this.value()); + // compared with what the server has, which a field may have replaced since the entity came in. + const saved: T = entity == undefined + ? await service.create(this.value()) + : await service.update({ ...entity, ...this.original() }, this.value()); this.savedValue.set(this.value()); this.saved.emit(saved); } diff --git a/projects/ngx-entity/entity/chips-array-item-metadata.model.ts b/projects/ngx-entity/entity/chips-array-item-metadata.model.ts index 43838ce..738ce81 100644 --- a/projects/ngx-entity/entity/chips-array-item-metadata.model.ts +++ b/projects/ngx-entity/entity/chips-array-item-metadata.model.ts @@ -1,3 +1,4 @@ +import { EnumLabels } from './enum-labels.type'; import { NumberFormat } from './number-property-metadata.model'; /** @@ -12,6 +13,10 @@ export type StringArrayItemMetadata = { * The enum the items are of, which makes the chips choose from its values. */ enum: Record | undefined, + /** + * The labels of the members of the enum, by their values. A member without one shows its value. + */ + enumLabels: EnumLabels, /** * Strings the input suggests while the user types, like tags used before. */ @@ -46,6 +51,10 @@ export type NumberArrayItemMetadata = { * The enum the items are of, which makes the chips choose from the names of its members. */ enum: Record | undefined, + /** + * The labels of the members of the enum, by their values as strings. A member without one shows its name. + */ + enumLabels: EnumLabels, /** * Any number, or a whole one. */ diff --git a/projects/ngx-entity/entity/entity-text.utilities.ts b/projects/ngx-entity/entity/entity-text.utilities.ts index 57ecff7..31856f2 100644 --- a/projects/ngx-entity/entity/entity-text.utilities.ts +++ b/projects/ngx-entity/entity/entity-text.utilities.ts @@ -1,4 +1,5 @@ import { ArrayItemMetadata } from './array-property-metadata.model'; +import { NumberArrayItemMetadata, StringArrayItemMetadata } from './chips-array-item-metadata.model'; import { DateDisplayStyle } from './date-property-metadata.model'; import { EntityClass } from './entity-class.type'; import { EntityTextLabels } from './entity-text-labels.model'; @@ -13,7 +14,7 @@ import { PropertyMetadata } from './property-metadata.type'; export abstract class EntityTextUtilities { /** * Resolves the text of a value of a property: a number and a date in the locale, a boolean as yes or no, the - * member of an enum by its name, the other entity of a relation by its label, an object of a select by the label + * member of an enum by its label, the other entity of a relation by its label, an object of a select by the label * of its option, an inline object by the texts of its values, a date range by its start and end, and an array by * the texts of its items. A custom property shows a text as it is, anything else as nothing. * @param metadata - What the property says about itself. @@ -50,7 +51,7 @@ export abstract class EntityTextUtilities { } /** - * Resolves the text of an item of an array: a string, a number in the locale, the member of an enum by its name, a + * Resolves the text of an item of an array: a string, a number in the locale, the member of an enum by its label, a * date or a date range in the locale, an object by the texts of its values. * @param items - What the items of the array say about themselves. * @param item - The item. @@ -62,7 +63,7 @@ export abstract class EntityTextUtilities { switch (items.type) { case 'string': case 'number': { - return this.resolveChipText(items.enum, item, locale); + return this.resolveChipText(items, item, locale); } case 'date': { return item instanceof Date ? this.resolveDateText(item, items.displayStyle, locale) : ''; @@ -88,10 +89,11 @@ export abstract class EntityTextUtilities { return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', ...time }).format(date); } - // a string, a number in the locale, or the member of an enum by its name. - private static resolveChipText(values: Record | undefined, item: unknown, locale: string): string { - if (values != undefined) { - return EntityUtilities.resolveEnumMembers(values).find(member => member.value === item)?.label ?? String(item); + // a string, a number in the locale, or the member of an enum by its label. + private static resolveChipText(items: StringArrayItemMetadata | NumberArrayItemMetadata, item: unknown, locale: string): string { + if (items.enum != undefined) { + return EntityUtilities.resolveEnumMembers(items.enum, items.enumLabels).find(member => member.value === item)?.label + ?? String(item); } if (typeof item === 'number') { return new Intl.NumberFormat(locale).format(item); @@ -147,7 +149,8 @@ export abstract class EntityTextUtilities { locale: string ): string { if ((metadata.type === 'string' || metadata.type === 'number') && metadata.enum != undefined) { - return EntityUtilities.resolveEnumMembers(metadata.enum).find(member => member.value === value)?.label ?? String(value); + return EntityUtilities.resolveEnumMembers(metadata.enum, metadata.enumLabels).find(member => member.value === value)?.label + ?? String(value); } if (metadata.type === 'number' && typeof value === 'number') { return new Intl.NumberFormat(locale).format(value); diff --git a/projects/ngx-entity/entity/entity.utilities.spec.ts b/projects/ngx-entity/entity/entity.utilities.spec.ts index 25382d8..7da77af 100644 --- a/projects/ngx-entity/entity/entity.utilities.spec.ts +++ b/projects/ngx-entity/entity/entity.utilities.spec.ts @@ -2,6 +2,8 @@ import { Injectable } from '@angular/core'; import { describe, expect, test } from 'vitest'; import { EntityProperty } from './entity-property.model'; +import { EntityTextLabels } from './entity-text-labels.model'; +import { EntityTextUtilities } from './entity-text.utilities'; import { EntityUtilities } from './entity.utilities'; import { Property } from './property.decorator'; @@ -10,6 +12,11 @@ enum TaskStatus { DONE = 'done' } +enum TaskPriority { + LOW = 1, + HIGH = 2 +} + class BaseEntity { @Property.string({ displayName: 'Id', format: 'uuid', omitForCreate: true, readonly: true }) id!: string; @@ -62,6 +69,7 @@ describe('Property and EntityUtilities', () => { maxLength: undefined, regex: undefined, enum: undefined, + enumLabels: {}, options: undefined, restrictToOptions: false, password: false, @@ -173,6 +181,38 @@ describe('Property and EntityUtilities', () => { test('refuse a slider without a min and a max', () => { expect(() => Property.number({ displayName: 'Rating', displayStyle: 'slider', min: 1 })).toThrow('The slider "Rating" needs a min and a max.'); }); + + test('refuse segments and cards without an enum, which would have nothing to choose from', () => { + expect(() => Property.string({ displayName: 'Topic', displayStyle: 'segmented' })).toThrow('The segmented field "Topic" needs an enum.'); + expect(() => Property.number({ displayName: 'Plan', displayStyle: 'cards' })).toThrow('The cards field "Plan" needs an enum.'); + }); + + test('name the members of an enum by their labels, the others by the value or the name of a number member', () => { + expect(EntityUtilities.resolveEnumMembers(TaskStatus, { [TaskStatus.DONE]: 'Done' })).toEqual([ + { label: 'open', value: TaskStatus.OPEN }, + { label: 'Done', value: TaskStatus.DONE } + ]); + expect(EntityUtilities.resolveEnumMembers(TaskPriority, { [TaskPriority.HIGH]: 'High' })).toEqual([ + { label: 'LOW', value: TaskPriority.LOW }, + { label: 'High', value: TaskPriority.HIGH } + ]); + }); + + test('show the members of an enum by their labels, also as the items of an array', () => { + class Ticket { + @Property.string({ displayName: 'Status', enum: TaskStatus, enumLabels: { [TaskStatus.DONE]: 'Done' } }) + status!: TaskStatus; + + @Property.array({ displayName: 'Priorities', items: { type: 'number', enum: TaskPriority, enumLabels: { [TaskPriority.LOW]: 'Low' } } }) + priorities!: TaskPriority[]; + } + const labels: EntityTextLabels = { yesLabel: 'Yes', noLabel: 'No' }; + const ticket: Ticket = { status: TaskStatus.DONE, priorities: [TaskPriority.LOW, TaskPriority.HIGH] }; + + expect(EntityUtilities.resolveProperties(Ticket).map(({ key, metadata }) => { + return EntityTextUtilities.resolveText(metadata, Reflect.get(ticket, key), ticket, labels, 'en-US'); + })).toEqual(['Done', 'Low, HIGH']); + }); }); // a stand-in for the services, which only the fields use. diff --git a/projects/ngx-entity/entity/entity.utilities.ts b/projects/ngx-entity/entity/entity.utilities.ts index cd469a0..a8eff3f 100644 --- a/projects/ngx-entity/entity/entity.utilities.ts +++ b/projects/ngx-entity/entity/entity.utilities.ts @@ -2,6 +2,7 @@ import { ArrayItemMetadata } from './array-property-metadata.model'; import { EntityClass } from './entity-class.type'; import { EntityCondition } from './entity-condition.type'; import { EntityProperty } from './entity-property.model'; +import { EnumLabels } from './enum-labels.type'; import { EnumMember } from './enum-member.model'; import { PropertyMetadata } from './property-metadata.type'; import { PropertyRegistryUtilities } from './property-registry.utilities'; @@ -262,18 +263,19 @@ export abstract class EntityUtilities { } /** - * Resolves the members of an enum, with the text that names each: the value of a string enum, the name of the - * member of a number enum. + * Resolves the members of an enum, with the text that names each: its label, else the value of a string enum and + * the name of the member of a number enum. * @param values - The enum. + * @param labels - The labels of the members, by their values as strings. * @returns Its members, in order. */ // a number enum maps its values back to the names of its members as well, which are no members. - static resolveEnumMembers(values: Record): EnumMember[] { + static resolveEnumMembers(values: Record, labels: EnumLabels = {}): EnumMember[] { const entries: [string, string | number][] = Object.entries(values); const numbers: [string, string | number][] = entries.filter(([, value]) => typeof value === 'number'); return numbers.length > 0 - ? numbers.map(([name, value]) => ({ label: name, value })) - : entries.map(([, value]) => ({ label: String(value), value })); + ? numbers.map(([name, value]) => ({ label: labels[String(value)] ?? name, value })) + : entries.map(([, value]) => ({ label: labels[String(value)] ?? String(value), value })); } // relations are read, never written: zibri answers a body that carries one with a 400. diff --git a/projects/ngx-entity/entity/enum-labels.type.ts b/projects/ngx-entity/entity/enum-labels.type.ts new file mode 100644 index 0000000..c6f5daa --- /dev/null +++ b/projects/ngx-entity/entity/enum-labels.type.ts @@ -0,0 +1,5 @@ +/** + * The labels of the members of an enum, by their values as strings, like + * `{ [ContactTopic.OTHER]: $localize\`Something else\` }`. A member without one keeps its default label. + */ +export type EnumLabels = Partial>; \ No newline at end of file diff --git a/projects/ngx-entity/entity/number-property-metadata.model.ts b/projects/ngx-entity/entity/number-property-metadata.model.ts index 568a5f7..e98dfc8 100644 --- a/projects/ngx-entity/entity/number-property-metadata.model.ts +++ b/projects/ngx-entity/entity/number-property-metadata.model.ts @@ -1,4 +1,5 @@ import { BasePropertyMetadata, BasePropertyMetadataInput } from './base-property-metadata.model'; +import { EnumLabels } from './enum-labels.type'; /** * The formats of a number in a form: any number, or a whole one. @@ -7,9 +8,10 @@ export type NumberFormat = 'number' | 'integer'; /** * How the field of a number shows: an input to type it, or a slider between min and max. A number with an enum is a - * select. + * select, or its members as one row of segments or as cards to choose from with 'segmented' or 'cards', which need an + * enum. */ -export type NumberDisplayStyle = 'line' | 'slider'; +export type NumberDisplayStyle = 'line' | 'slider' | 'segmented' | 'cards'; /** * What a number property says about itself, with every value set. @@ -36,9 +38,14 @@ export type NumberPropertyMetadata = BasePropertyMetadata & { */ max: number | undefined, /** - * The enum the value is one of, which makes the field a select of its values. + * The enum the value is one of, which makes the field a select of its values, or its choices with the display style + * 'segmented' or 'cards'. */ - enum: Record | undefined + enum: Record | undefined, + /** + * The labels of the members of the enum, by their values as strings. A member without one shows its name. + */ + enumLabels: EnumLabels }; /** diff --git a/projects/ngx-entity/entity/property-position.model.ts b/projects/ngx-entity/entity/property-position.model.ts index ec63b4e..ba69843 100644 --- a/projects/ngx-entity/entity/property-position.model.ts +++ b/projects/ngx-entity/entity/property-position.model.ts @@ -4,9 +4,10 @@ */ export type PropertyPosition = { /** - * The tab, from 1 on. A form whose fields are all on one tab shows no tabs. + * The tab, from 1 on, or 'last' for the tab after every numbered one, like a history. A form whose fields are all + * on one tab shows no tabs. */ - tab?: number, + tab?: number | 'last', /** * The label of the tab. One field of a tab is enough to name it. */ diff --git a/projects/ngx-entity/entity/property.decorator.ts b/projects/ngx-entity/entity/property.decorator.ts index affa84b..5a43e9f 100644 --- a/projects/ngx-entity/entity/property.decorator.ts +++ b/projects/ngx-entity/entity/property.decorator.ts @@ -11,7 +11,7 @@ import { ObjectPropertyMetadataInput } from './object-property-metadata.model'; import { OneToManyPropertyMetadataInput } from './one-to-many-property-metadata.model'; import { PropertyMetadata } from './property-metadata.type'; import { PropertyRegistryUtilities } from './property-registry.utilities'; -import { StringPropertyMetadataInput } from './string-property-metadata.model'; +import { StringPropertyMetadata, StringPropertyMetadataInput } from './string-property-metadata.model'; import { ToOnePropertyMetadataInput } from './to-one-property-metadata.model'; /** @@ -31,9 +31,10 @@ export abstract class Property { * Describes a string property. * @param data - The label, and every other value that differs from its default. * @returns The decorator. + * @throws {Error} When it shows segmented or as cards without an enum. */ static string(data: StringPropertyMetadataInput): EntityPropertyDecorator { - return this.resolveDecorator({ + const metadata: StringPropertyMetadata = { ...this.resolveBase(data), type: 'string', displayStyle: 'line', @@ -42,21 +43,25 @@ export abstract class Property { maxLength: undefined, regex: undefined, enum: undefined, + enumLabels: {}, options: undefined, restrictToOptions: false, password: false, confirmation: true, confirmationDisplayName: undefined, passwordStrength: true, + autocomplete: undefined, ...data - }); + }; + this.validateChoices(metadata); + return this.resolveDecorator(metadata); } /** * Describes a number property. A slider without a default starts at its min. * @param data - The label, and every other value that differs from its default. * @returns The decorator. - * @throws {Error} When it is a slider without a min and a max. + * @throws {Error} When it is a slider without a min and a max, or shows segmented or as cards without an enum. */ static number(data: NumberPropertyMetadataInput): EntityPropertyDecorator { const metadata: NumberPropertyMetadata = { @@ -67,8 +72,10 @@ export abstract class Property { min: undefined, max: undefined, enum: undefined, + enumLabels: {}, ...data }; + this.validateChoices(metadata); if (metadata.displayStyle !== 'slider') { return this.resolveDecorator(metadata); } @@ -246,6 +253,7 @@ export abstract class Property { case 'string': { return { enum: undefined, + enumLabels: {}, options: undefined, restrictToOptions: false, minLength: undefined, @@ -255,7 +263,7 @@ export abstract class Property { }; } case 'number': { - return { enum: undefined, format: 'number', min: undefined, max: undefined, ...items }; + return { enum: undefined, enumLabels: {}, format: 'number', min: undefined, max: undefined, ...items }; } case 'date': case 'dateRange': { @@ -267,6 +275,13 @@ export abstract class Property { } } + // segments and cards show the members of an enum, without one they would have nothing to choose from. + private static validateChoices(metadata: StringPropertyMetadata | NumberPropertyMetadata): void { + if ((metadata.displayStyle === 'segmented' || metadata.displayStyle === 'cards') && metadata.enum == undefined) { + throw new Error(`The ${metadata.displayStyle} field "${metadata.displayName}" needs an enum.`); + } + } + private static resolveDecorator(metadata: PropertyMetadata): EntityPropertyDecorator { return (prototype, key) => PropertyRegistryUtilities.register(prototype, key, metadata); } diff --git a/projects/ngx-entity/entity/public-api.ts b/projects/ngx-entity/entity/public-api.ts index b6a93a6..02a98f2 100644 --- a/projects/ngx-entity/entity/public-api.ts +++ b/projects/ngx-entity/entity/public-api.ts @@ -14,6 +14,7 @@ export * from './entity-property.model'; export * from './entity-text-labels.model'; export * from './entity-text.utilities'; export * from './entity.utilities'; +export * from './enum-labels.type'; export * from './enum-member.model'; export * from './grid-width.type'; export * from './number-property-metadata.model'; diff --git a/projects/ngx-entity/entity/string-property-metadata.model.ts b/projects/ngx-entity/entity/string-property-metadata.model.ts index 6d3ca85..d873839 100644 --- a/projects/ngx-entity/entity/string-property-metadata.model.ts +++ b/projects/ngx-entity/entity/string-property-metadata.model.ts @@ -1,4 +1,5 @@ import { BasePropertyMetadata, BasePropertyMetadataInput } from './base-property-metadata.model'; +import { EnumLabels } from './enum-labels.type'; /** * The formats of a string, like in zibri. `phone` is a number in international format, like '+4915112345678'. @@ -7,9 +8,10 @@ export type StringFormat = 'uuid' | 'email' | 'phone'; /** * How the field of a string shows: one line, several for a longer text, or one line that suggests its options. A string - * with an enum is a select. + * with an enum is a select, or its members as one row of segments or as cards to choose from with 'segmented' or + * 'cards', which need an enum. */ -export type StringDisplayStyle = 'line' | 'textarea' | 'autocomplete'; +export type StringDisplayStyle = 'line' | 'textarea' | 'autocomplete' | 'segmented' | 'cards'; /** * The texts the field of a string suggests: a list, or a function of the entity that resolves it. @@ -45,9 +47,14 @@ export type StringPropertyMetadata = BasePropertyMetadata & { */ regex: RegExp | string | undefined, /** - * The enum the value is one of, which makes the field a select of its values. + * The enum the value is one of, which makes the field a select of its values, or its choices with the display style + * 'segmented' or 'cards'. */ enum: Record | undefined, + /** + * The labels of the members of the enum, by their values. A member without one shows its value. + */ + enumLabels: EnumLabels, /** * The texts the field suggests while the user types, with the display style 'autocomplete'. */ @@ -72,7 +79,11 @@ export type StringPropertyMetadata = BasePropertyMetadata & { /** * Whether the field of a password shows how hard it is to guess. */ - passwordStrength: boolean + passwordStrength: boolean, + /** + * What a field of one line holds, for the browser to fill it in, like 'name', 'email' or 'tel'. + */ + autocomplete: string | undefined }; /** diff --git a/projects/ngx-entity/field-autocomplete/entity-autocomplete-field.component.html b/projects/ngx-entity/field-autocomplete/entity-autocomplete-field.component.html index 8835007..33c504f 100644 --- a/projects/ngx-entity/field-autocomplete/entity-autocomplete-field.component.html +++ b/projects/ngx-entity/field-autocomplete/entity-autocomplete-field.component.html @@ -2,6 +2,7 @@ { @@ -13,9 +14,12 @@ export abstract class BaseEntityFieldDirective { readonly property: InputSignal> = input.required>(); /** - * The values of the whole entity, which conditions of the property depend on. + * The values of the whole entity, which conditions of the property depend on, or of the object the property is in. + * Set it to replace the entity with one the server answered, like after undoing a change set: the form shows its + * values in every field and takes it as saved, so it has no unsaved changes, and saving sends only what the user + * changes after it. Only a field of the entity itself replaces it, not one of an object in it. */ - readonly entity: InputSignal> = input.required>(); + readonly entity: ModelSignal> = model.required>(); /** * Whether the field needs a value. @@ -42,6 +46,12 @@ export abstract class BaseEntityFieldDirective { */ protected readonly label: Signal = computed(() => this.property().metadata.displayName); + /** + * The name of the native field: the key of the property, which is unique in the form. A form draft of ui keeps the + * fields by it, and a browser fills them in by it. + */ + protected readonly name: Signal = computed(() => String(this.property().key)); + /** * The hint below the field. */ diff --git a/projects/ngx-entity/field-boolean/entity-boolean-field.component.html b/projects/ngx-entity/field-boolean/entity-boolean-field.component.html index cc68a1b..23813ee 100644 --- a/projects/ngx-entity/field-boolean/entity-boolean-field.component.html +++ b/projects/ngx-entity/field-boolean/entity-boolean-field.component.html @@ -1,5 +1,6 @@ \ No newline at end of file diff --git a/projects/ngx-entity/field-cards/entity-cards-field.component.spec.ts b/projects/ngx-entity/field-cards/entity-cards-field.component.spec.ts new file mode 100644 index 0000000..81151a4 --- /dev/null +++ b/projects/ngx-entity/field-cards/entity-cards-field.component.spec.ts @@ -0,0 +1,179 @@ +import { Component, signal, WritableSignal } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { EntityClass, EntityUtilities, Property } from '@service-soft/ngx-entity/entity'; +import { EntityFormComponent } from '@service-soft/ngx-entity/form'; +import { FormComponent } from '@service-soft/ui/form'; +import { describe, expect, test } from 'vitest'; +import { ValidationProblem } from 'zibri-contract'; + +enum Plan { + BASIC = 'basic', + PRO = 'pro', + TEAM = 'team' +} + +enum Priority { + LOW = 1, + HIGH = 2 +} + +class Subscription { + @Property.string({ + displayName: 'Plan', + description: 'You can change it any time', + enum: Plan, + // a member without a label shows its value + enumLabels: { [Plan.BASIC]: 'Basic', [Plan.PRO]: 'Professional' }, + displayStyle: 'cards' + }) + plan!: Plan; + + // a member of a number enum without a label shows its name + @Property.number({ displayName: 'Priority', enum: Priority, enumLabels: { [Priority.HIGH]: 'Urgent' }, displayStyle: 'segmented', required: false }) + priority?: Priority; +} + +@Component({ + selector: 'ngx-host', + template: ` + + + + `, + imports: [FormComponent, EntityFormComponent] +}) +class HostComponent { + readonly entity: EntityClass = Subscription; + readonly value: WritableSignal> = signal(EntityUtilities.resolveDefaults(Subscription)); + readonly problems: WritableSignal = signal([]); + readonly submits: WritableSignal = signal(0); +} + +async function render(): Promise<[ComponentFixture, HTMLElement]> { + const fixture: ComponentFixture = TestBed.createComponent(HostComponent); + // the fields load their components first. + await fixture.whenStable(); + return [fixture, fixture.nativeElement as HTMLElement]; +} + +function findFieldset(root: HTMLElement, legend: string): HTMLFieldSetElement { + const fieldset: HTMLFieldSetElement | undefined = [...root.querySelectorAll('fieldset')] + .find(candidate => candidate.querySelector('legend')?.textContent.trim().startsWith(legend) === true); + if (fieldset == undefined) { + throw new Error(`No fieldset with the legend "${legend}".`); + } + return fieldset; +} + +function findRadios(fieldset: HTMLFieldSetElement): HTMLInputElement[] { + return [...fieldset.querySelectorAll('input[type="radio"]')]; +} + +function findText(ids: string | null): string | undefined { + return ids?.split(' ').map(id => document.getElementById(id)?.textContent.trim()) + .join(' '); +} + +describe('EntityCardsFieldComponent', () => { + test('shows the members of an enum with the display style cards as cards, named by their labels', async () => { + const [, root] = await render(); + const plan: HTMLFieldSetElement = findFieldset(root, 'Plan'); + const radios: HTMLInputElement[] = findRadios(plan); + + expect(root.querySelector('select')).toBeNull(); + expect(plan.querySelector('legend')?.textContent).toBe('Plan *'); + expect(findText(plan.getAttribute('aria-describedby'))).toBe('You can change it any time'); + expect(radios.map(radio => findText(radio.getAttribute('aria-labelledby')))).toEqual(['Basic', 'Professional', 'team']); + // cards show their radio buttons, segments hide them + expect(radios.some(radio => radio.classList.contains('sr-only'))).toBe(false); + expect(radios.every(radio => radio.name === 'plan')).toBe(true); + }); + + test('shows the members of a number enum with the display style segmented as segments', async () => { + const [, root] = await render(); + const priority: HTMLFieldSetElement = findFieldset(root, 'Priority'); + const radios: HTMLInputElement[] = findRadios(priority); + + expect(priority.querySelector('legend')?.textContent).toBe('Priority'); + expect(radios.map(radio => radio.closest('label')?.textContent.trim())).toEqual(['LOW', 'Urgent']); + expect(radios.every(radio => radio.classList.contains('sr-only') && radio.name === 'priority')).toBe(true); + }); + + test('sets the value of the chosen member in the entity, and checks the member of a value set from outside', async () => { + const [fixture, root] = await render(); + const plans: HTMLInputElement[] = findRadios(findFieldset(root, 'Plan')); + const priorities: HTMLInputElement[] = findRadios(findFieldset(root, 'Priority')); + + plans[1]?.click(); + priorities[1]?.click(); + await fixture.whenStable(); + // the number of a number enum, not the text of its radio button + expect(fixture.componentInstance.value()).toEqual({ plan: Plan.PRO, priority: Priority.HIGH }); + expect(plans.map(radio => radio.checked)).toEqual([false, true, false]); + expect(priorities[1]?.closest('label')?.dataset['selected']).toBe('true'); + + fixture.componentInstance.value.set({ plan: Plan.TEAM, priority: Priority.LOW }); + await fixture.whenStable(); + expect(plans.map(radio => radio.checked)).toEqual([false, false, true]); + expect(priorities.map(radio => radio.checked)).toEqual([true, false]); + }); + + test('needs a member of a required property before the form submits, and shows its error until one is chosen', async () => { + const [fixture, root] = await render(); + const plan: HTMLFieldSetElement = findFieldset(root, 'Plan'); + const plans: HTMLInputElement[] = findRadios(plan); + expect(plans.every(radio => radio.required)).toBe(true); + expect(findRadios(findFieldset(root, 'Priority')).some(radio => radio.required)).toBe(false); + + root.querySelector('form')?.requestSubmit(); + await fixture.whenStable(); + expect(fixture.componentInstance.submits()).toBe(0); + expect(plans[0]?.getAttribute('aria-invalid')).toBe('true'); + expect(findText(plan.getAttribute('aria-describedby'))).toContain('This field is required.'); + + plans[2]?.click(); + await fixture.whenStable(); + expect(plans[0]?.hasAttribute('aria-invalid')).toBe(false); + root.querySelector('form')?.requestSubmit(); + await fixture.whenStable(); + expect(fixture.componentInstance.submits()).toBe(1); + expect(fixture.componentInstance.value()).toEqual({ plan: Plan.TEAM }); + }); + + test('shows the problem the server found right away, until another member is chosen', async () => { + const [fixture, root] = await render(); + const plan: HTMLFieldSetElement = findFieldset(root, 'Plan'); + const plans: HTMLInputElement[] = findRadios(plan); + plans[0]?.click(); + await fixture.whenStable(); + + fixture.componentInstance.problems.set([{ key: 'plan', code: 'unavailable', message: 'This plan is sold out.' }]); + await fixture.whenStable(); + expect(plans[0]?.getAttribute('aria-invalid')).toBe('true'); + expect(findText(plan.getAttribute('aria-describedby'))).toContain('This plan is sold out.'); + expect(plans[0]?.validity.valid).toBe(false); + + plans[1]?.click(); + await fixture.whenStable(); + expect(plans[0]?.validity.valid).toBe(true); + expect(plans[0]?.hasAttribute('aria-invalid')).toBe(false); + }); + + test('is a group of focusable native radio buttons, which shows its error once the keyboard leaves it', async () => { + const [fixture, root] = await render(); + const plan: HTMLFieldSetElement = findFieldset(root, 'Plan'); + const plans: HTMLInputElement[] = findRadios(plan); + // one name makes them one group, which the browser moves through with the arrow keys + expect(new Set(plans.map(radio => radio.name)).size).toBe(1); + expect(plans.every(radio => !radio.disabled && radio.tabIndex === 0)).toBe(true); + + plans[0]?.focus(); + expect(document.activeElement).toBe(plans[0]); + expect(plans[0]?.hasAttribute('aria-invalid')).toBe(false); + + plans[0]?.blur(); + await fixture.whenStable(); + expect(plans[0]?.getAttribute('aria-invalid')).toBe('true'); + expect(findText(plan.getAttribute('aria-describedby'))).toContain('This field is required.'); + }); +}); diff --git a/projects/ngx-entity/field-cards/entity-cards-field.component.ts b/projects/ngx-entity/field-cards/entity-cards-field.component.ts new file mode 100644 index 0000000..f4145b4 --- /dev/null +++ b/projects/ngx-entity/field-cards/entity-cards-field.component.ts @@ -0,0 +1,44 @@ +import { Component, computed, Signal } from '@angular/core'; +import { EntityUtilities, NumberPropertyMetadata, PropertyMetadata, StringPropertyMetadata } from '@service-soft/ngx-entity/entity'; +import { BaseEntityFieldDirective } from '@service-soft/ngx-entity/field-base'; +import { InputCardsAppearance } from '@service-soft/ui/input'; +import { InputCardOption, InputCardsComponent } from '@service-soft/ui/input-cards'; + +/** + * The field of a string or number property with an enum and the display style 'segmented' or 'cards': its members as + * one row of segments or as cards to choose one of. A member shows its label, else a string enum its value and a number + * enum the name of the member. + */ +@Component({ + selector: 'ngx-entity-cards-field', + templateUrl: './entity-cards-field.component.html', + imports: [InputCardsComponent], + host: { class: 'contents' } +}) +export class EntityCardsFieldComponent extends BaseEntityFieldDirective { + /** + * What the string or number property says about itself. + */ + protected readonly metadata: Signal | NumberPropertyMetadata> = computed(() => { + const metadata: PropertyMetadata = this.property().metadata; + if (metadata.type !== 'string' && metadata.type !== 'number') { + throw this.resolveKindError('string'); + } + return metadata; + }); + + /** + * Whether the members are one row of segments or cards. + */ + protected readonly appearance: Signal = computed(() => { + return this.metadata().displayStyle === 'segmented' ? 'segmented' : 'cards'; + }); + + /** + * The members of the enum to choose from. + */ + protected readonly options: Signal[]> = computed(() => { + const metadata: StringPropertyMetadata | NumberPropertyMetadata = this.metadata(); + return EntityUtilities.resolveEnumMembers(metadata.enum ?? {}, metadata.enumLabels); + }); +} \ No newline at end of file diff --git a/projects/ngx-entity/field-cards/entity-cards-field.stories.html b/projects/ngx-entity/field-cards/entity-cards-field.stories.html new file mode 100644 index 0000000..97bdcea --- /dev/null +++ b/projects/ngx-entity/field-cards/entity-cards-field.stories.html @@ -0,0 +1,6 @@ + + +
+ +
+
diff --git a/projects/ngx-entity/field-cards/entity-cards-field.stories.ts b/projects/ngx-entity/field-cards/entity-cards-field.stories.ts new file mode 100644 index 0000000..c3c658b --- /dev/null +++ b/projects/ngx-entity/field-cards/entity-cards-field.stories.ts @@ -0,0 +1,104 @@ +import { Component, input, InputSignal, linkedSignal, WritableSignal } from '@angular/core'; +import { EntityClass, EntityUtilities, Property } from '@service-soft/ngx-entity/entity'; +import { EntityFormComponent } from '@service-soft/ngx-entity/form'; +import { ButtonComponent } from '@service-soft/ui/button'; +import { FormComponent } from '@service-soft/ui/form'; +import { Meta, StoryObj } from '@storybook/angular'; +import { ValidationProblem } from 'zibri-contract'; + +import { EntityCardsFieldComponent } from './entity-cards-field.component'; + +enum Plan { + BASIC = 'basic', + PRO = 'pro', + TEAM = 'team' +} + +enum ShirtSize { + S = 'S', + M = 'M', + L = 'L', + XL = 'XL' +} + +enum Priority { + LOW = 1, + NORMAL = 2, + HIGH = 3 +} + +// an enum as cards and as segments, of strings and of numbers. +class Order { + @Property.string({ + displayName: 'Plan', + description: 'You can change it any time', + enum: Plan, + enumLabels: { [Plan.BASIC]: 'Basic', [Plan.PRO]: 'Professional', [Plan.TEAM]: 'Team' }, + displayStyle: 'cards', + defaultWidths: [12, 12, 12] + }) + plan!: Plan; + + @Property.string({ displayName: 'Shirt size', enum: ShirtSize, displayStyle: 'segmented' }) + size!: ShirtSize; + + @Property.number({ + displayName: 'Priority', + enum: Priority, + enumLabels: { [Priority.LOW]: 'Low', [Priority.NORMAL]: 'Normal', [Priority.HIGH]: 'High' }, + displayStyle: 'segmented', + required: false + }) + priority?: Priority; +} + +@Component({ + selector: 'ngx-order-form', + templateUrl: './entity-cards-field.stories.html', + imports: [FormComponent, EntityFormComponent, ButtonComponent] +}) +class OrderFormComponent { + readonly problems: InputSignal = input([]); + readonly initial: InputSignal> = input(EntityUtilities.resolveDefaults(Order)); + + readonly entity: EntityClass = Order; + readonly value: WritableSignal> = linkedSignal(() => this.initial()); +} + +const FILLED: Partial = { plan: Plan.PRO, size: ShirtSize.M, priority: Priority.HIGH }; + +const meta: Meta> = { + title: 'Entity/Cards', + component: EntityCardsFieldComponent +}; +export default meta; + +type Story = StoryObj>; + +// nothing chosen yet: Save shows the errors of the required ones. +export const Empty: Story = { + render: () => ({ template: '', moduleMetadata: { imports: [OrderFormComponent] } }) +}; + +export const Filled: Story = { + render: () => ({ + props: { filled: FILLED }, + template: '', + moduleMetadata: { imports: [OrderFormComponent] } + }) +}; + +// what the server refused, shown as the errors of the cards and the segments right away. +export const WithProblems: Story = { + render: () => ({ + props: { + filled: FILLED, + problems: [ + { key: 'plan', code: 'unavailable', message: 'This plan is sold out.' }, + { key: 'size', code: 'unavailable', message: 'This size is out of stock.' } + ] + }, + template: '', + moduleMetadata: { imports: [OrderFormComponent] } + }) +}; diff --git a/projects/ngx-entity/field-cards/ng-package.json b/projects/ngx-entity/field-cards/ng-package.json new file mode 100644 index 0000000..70e0a80 --- /dev/null +++ b/projects/ngx-entity/field-cards/ng-package.json @@ -0,0 +1,5 @@ +{ + "lib": { + "entryFile": "public-api.ts" + } +} \ No newline at end of file diff --git a/projects/ngx-entity/field-cards/public-api.ts b/projects/ngx-entity/field-cards/public-api.ts new file mode 100644 index 0000000..055d59b --- /dev/null +++ b/projects/ngx-entity/field-cards/public-api.ts @@ -0,0 +1 @@ +export * from './entity-cards-field.component'; \ No newline at end of file diff --git a/projects/ngx-entity/field-chips/entity-chips-field.component.html b/projects/ngx-entity/field-chips/entity-chips-field.component.html index a12a92d..0ed2cc4 100644 --- a/projects/ngx-entity/field-chips/entity-chips-field.component.html +++ b/projects/ngx-entity/field-chips/entity-chips-field.component.html @@ -1,5 +1,6 @@ extends BaseEntityField protected readonly options: Signal[]> = computed(() => { const items: EntityChipsItemMetadata = this.items(); if (items.enum != undefined) { - return EntityUtilities.resolveEnumMembers(items.enum); + return EntityUtilities.resolveEnumMembers(items.enum, items.enumLabels); } return items.type === 'string' ? (items.options ?? []).map(option => ({ label: option, value: option })) : []; }); diff --git a/projects/ngx-entity/field-date/entity-date-field.component.html b/projects/ngx-entity/field-date/entity-date-field.component.html index 251d110..058465f 100644 --- a/projects/ngx-entity/field-date/entity-date-field.component.html +++ b/projects/ngx-entity/field-date/entity-date-field.component.html @@ -1,5 +1,6 @@ extends BaseEntityFiel protected readonly options: Signal[]> = computed(() => { const metadata: PropertyMetadata = this.property().metadata; if (metadata.type === 'string' || metadata.type === 'number') { - return EntityUtilities.resolveEnumMembers(metadata.enum ?? {}); + return EntityUtilities.resolveEnumMembers(metadata.enum ?? {}, metadata.enumLabels); } if (metadata.type !== 'object') { throw this.resolveKindError('string'); diff --git a/projects/ngx-entity/field-slider/entity-slider-field.component.html b/projects/ngx-entity/field-slider/entity-slider-field.component.html index 30e97ec..44b2246 100644 --- a/projects/ngx-entity/field-slider/entity-slider-field.component.html +++ b/projects/ngx-entity/field-slider/entity-slider-field.component.html @@ -1,5 +1,6 @@ await Promise.resolve(ColorFieldComponent) }) color?: string; + + // a field of its own that takes the inputs without extending BaseEntityFieldDirective, so it can't replace the entity + @Property.custom({ displayName: 'Rating', required: false, component: async () => await Promise.resolve(RatingFieldComponent) }) + rating?: number; +} + +@Component({ + selector: 'ngx-rating-field', + template: '' +}) +class RatingFieldComponent { + readonly property: InputSignal> = input.required>(); + readonly entity: InputSignal> = input.required>(); + readonly required: InputSignal = input(false); + readonly readonly: InputSignal = input(false); + readonly problem: InputSignal = input(); + readonly value: ModelSignal = model(); } @Component({ @@ -124,8 +141,8 @@ describe('EntityFieldComponent', () => { expect([estimate.type, estimate.step, estimate.min]).toEqual(['number', '1', '0']); const progress: HTMLInputElement = findControl(root, 'Progress', HTMLInputElement); expect([progress.type, progress.step, progress.value]).toEqual(['range', '0.01', '0']); - // a date with its time, its example in the placeholder shows that - expect(findControl(root, 'Due', HTMLInputElement).placeholder).toMatch(/^12\/31\/\d{4}, 06:30\sPM$/); + // a date with its time, the parts in the placeholder show that + expect(findControl(root, 'Due', HTMLInputElement).placeholder).toMatch(/^MM\/DD\/YYYY, hh:mm\sAM\/PM$/); }); test('allows a date only from the one its decorator says on', async () => { @@ -187,6 +204,19 @@ describe('EntityFieldComponent', () => { expect(buttons[1]?.getAttribute('aria-pressed')).toBe('true'); }); + // the entity became two-way so a field can replace it, which broke the fields that only take the inputs + test('shows a custom component that takes the inputs without extending the directive, and binds its value', async () => { + const [fixture, root] = await render(); + fixture.componentInstance.setValue('title', 'Write'); + await fixture.whenStable(); + const button: HTMLButtonElement | null = root.querySelector('ngx-rating-field button'); + expect(button?.textContent.trim()).toBe('Rating of Write'); + + button?.click(); + await fixture.whenStable(); + expect(fixture.componentInstance.values().rating).toBe(5); + }); + test('shows a kind with the component the app gives for it', async () => { TestBed.configureTestingModule({ providers: [provideEntityFields({ date: () => Promise.resolve(OwnDateFieldComponent) })] }); const [, root] = await render(); diff --git a/projects/ngx-entity/field/entity-field.component.ts b/projects/ngx-entity/field/entity-field.component.ts index 20338e3..d178748 100644 --- a/projects/ngx-entity/field/entity-field.component.ts +++ b/projects/ngx-entity/field/entity-field.component.ts @@ -1,4 +1,4 @@ -import { booleanAttribute, Component, computed, effect, inject, input, InputSignal, InputSignalWithTransform, inputBinding, model, ModelSignal, resource, ResourceRef, Signal, twoWayBinding, Type, untracked, viewChild, ViewContainerRef } from '@angular/core'; +import { booleanAttribute, Component, computed, effect, inject, input, InputSignal, InputSignalWithTransform, inputBinding, model, ModelSignal, reflectComponentType, resource, ResourceRef, Signal, twoWayBinding, Type, untracked, viewChild, ViewContainerRef } from '@angular/core'; import { EntityProperty } from '@service-soft/ngx-entity/entity'; import { EntityFieldLoader, EntityFieldLoaders } from './entity-field-loaders.model'; @@ -7,7 +7,8 @@ import { ENTITY_FIELDS } from './entity-fields.provider'; /** * The field of a property of an entity: it loads the component of the kind of the property, see provideEntityFields, - * and hands it what it takes. Bind the value two-way with [(value)]. + * and hands it what it takes. Bind the value two-way with [(value)], and the entity with [(entity)] to take the one a + * field replaces it with. */ @Component({ selector: 'ngx-entity-field', @@ -25,9 +26,10 @@ export class EntityFieldComponent { readonly property: InputSignal> = input.required>(); /** - * The values of the whole entity, which conditions of the property depend on. + * The values of the whole entity, which conditions of the property depend on. The field sets it to replace the + * entity, like with one the server answered, bind it with [(entity)] to take it. */ - readonly entity: InputSignal> = input.required>(); + readonly entity: ModelSignal> = model.required>(); /** * Whether the field needs a value. @@ -74,10 +76,14 @@ export class EntityFieldComponent { // the bindings read the signals from now on, which must not recreate the component on every change. untracked(() => { outlet.clear(); + // two-way only for a component that can replace the entity, like one extending BaseEntityFieldDirective: a + // field of its own that only takes the inputs has no entityChange, which a two-way binding requires + const replacesEntity: boolean = reflectComponentType(component)?.outputs + .some(output => output.templateName === 'entityChange') === true; outlet.createComponent(component, { bindings: [ inputBinding('property', this.property), - inputBinding('entity', this.entity), + replacesEntity ? twoWayBinding('entity', this.entity) : inputBinding('entity', this.entity), inputBinding('required', this.required), inputBinding('readonly', this.readonly), inputBinding('problem', this.problem), diff --git a/projects/ngx-entity/field/entity-field.utilities.ts b/projects/ngx-entity/field/entity-field.utilities.ts index 86a0465..433e705 100644 --- a/projects/ngx-entity/field/entity-field.utilities.ts +++ b/projects/ngx-entity/field/entity-field.utilities.ts @@ -19,8 +19,8 @@ export abstract class EntityFieldUtilities { } /** - * Resolves the kind of the field of a property: a select for an enum, else by its type and display style. A - * custom property has a component of its own instead. + * Resolves the kind of the field of a property: cards for an enum that shows segmented or as cards, a select for + * any other enum, else by its type and display style. A custom property has a component of its own instead. * @param metadata - What the property says about itself. * @returns The kind. */ @@ -30,6 +30,10 @@ export abstract class EntityFieldUtilities { return this.resolveStringKind(metadata); } case 'number': { + // the decorator makes sure they have an enum. + if (metadata.displayStyle === 'segmented' || metadata.displayStyle === 'cards') { + return 'cards'; + } if (metadata.enum != undefined) { return 'select'; } @@ -65,6 +69,10 @@ export abstract class EntityFieldUtilities { if (metadata.password) { return 'password'; } + // the decorator makes sure they have an enum. + if (metadata.displayStyle === 'segmented' || metadata.displayStyle === 'cards') { + return 'cards'; + } if (metadata.enum != undefined) { return 'select'; } diff --git a/projects/ngx-entity/field/entity-fields.provider.ts b/projects/ngx-entity/field/entity-fields.provider.ts index ffde770..49654d7 100644 --- a/projects/ngx-entity/field/entity-fields.provider.ts +++ b/projects/ngx-entity/field/entity-fields.provider.ts @@ -10,6 +10,7 @@ const DEFAULT_ENTITY_FIELDS: EntityFieldLoaders = { autocomplete: async () => (await import('@service-soft/ngx-entity/field-autocomplete')).EntityAutocompleteFieldComponent, dateRange: async () => (await import('@service-soft/ngx-entity/field-date-range')).EntityDateRangeFieldComponent, select: async () => (await import('@service-soft/ngx-entity/field-select')).EntitySelectFieldComponent, + cards: async () => (await import('@service-soft/ngx-entity/field-cards')).EntityCardsFieldComponent, number: async () => (await import('@service-soft/ngx-entity/field-number')).EntityNumberFieldComponent, slider: async () => (await import('@service-soft/ngx-entity/field-slider')).EntitySliderFieldComponent, boolean: async () => (await import('@service-soft/ngx-entity/field-boolean')).EntityBooleanFieldComponent, diff --git a/projects/ngx-entity/form/entity-form-rows.component.html b/projects/ngx-entity/form/entity-form-rows.component.html index b4c44a0..192f624 100644 --- a/projects/ngx-entity/form/entity-form-rows.component.html +++ b/projects/ngx-entity/form/entity-form-rows.component.html @@ -27,6 +27,7 @@ [problem]="problems()[field.valueKey]" [value]="getValue(field.valueKey)" (valueChange)="changed.emit({ key: field.valueKey, value: $event })" + (entityChange)="replace(field, $event)" /> }
diff --git a/projects/ngx-entity/form/entity-form-rows.component.ts b/projects/ngx-entity/form/entity-form-rows.component.ts index 4188d07..6665f2b 100644 --- a/projects/ngx-entity/form/entity-form-rows.component.ts +++ b/projects/ngx-entity/form/entity-form-rows.component.ts @@ -3,7 +3,7 @@ import { EntityUtilities } from '@service-soft/ngx-entity/entity'; import { EntityFieldComponent } from '@service-soft/ngx-entity/field'; import { EntityFormChange } from './entity-form-change.model'; -import { EntityFormRow } from './entity-form-layout.model'; +import { EntityFormField, EntityFormRow } from './entity-form-layout.model'; /** * The rows of a tab of an entity form, each a grid of 12 columns. Internal to the form. @@ -35,6 +35,23 @@ export class EntityFormRowsComponent { */ readonly changed: OutputEmitterRef = output(); + /** + * Emits the entity a field replaced the values with, like one the server answered. + */ + readonly replaced: OutputEmitterRef> = output>(); + + /** + * Takes the entity a field replaced the values with. + * @param field - The field. + * @param entity - The new entity. + */ + // a field of an object gets the object as its entity, which is no entity the form could take as saved. + protected replace(field: EntityFormField, entity: Partial): void { + if (field.path == undefined) { + this.replaced.emit(entity); + } + } + /** * Gets the value of a field. * @param path - The path of its value, like 'address.city'. diff --git a/projects/ngx-entity/form/entity-form.component.html b/projects/ngx-entity/form/entity-form.component.html index e698148..2339528 100644 --- a/projects/ngx-entity/form/entity-form.component.html +++ b/projects/ngx-entity/form/entity-form.component.html @@ -10,12 +10,19 @@ [values]="value()" [problems]="problemMessages()" (changed)="change($event)" + (replaced)="replace($event)" /> } } @else { @for (tab of tabs(); track tab.tab) { - + } } diff --git a/projects/ngx-entity/form/entity-form.component.spec.ts b/projects/ngx-entity/form/entity-form.component.spec.ts index ee4c88b..97ff7bb 100644 --- a/projects/ngx-entity/form/entity-form.component.spec.ts +++ b/projects/ngx-entity/form/entity-form.component.spec.ts @@ -1,7 +1,10 @@ import { Component, signal, WritableSignal } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { EntityClass, EntityUtilities, Property } from '@service-soft/ngx-entity/entity'; +import { BaseEntityFieldDirective } from '@service-soft/ngx-entity/field-base'; import { FormComponent } from '@service-soft/ui/form'; +import { FormDraftDirective } from '@service-soft/ui/form-draft'; +import { FormTestingUtilities } from 'testing/form'; import { describe, expect, test } from 'vitest'; import { ValidationProblem } from 'zibri-contract'; @@ -12,7 +15,7 @@ class Contact { @Property.string({ displayName: 'Name' }) name!: string; - @Property.string({ displayName: 'Email', format: 'email' }) + @Property.string({ displayName: 'Email', format: 'email', autocomplete: 'email' }) email!: string; } @@ -64,11 +67,55 @@ class Delivery { address?: Address; } +enum ContactTopic { + SOFTWARE = 'software', + TAKEOVER = 'takeover', + WEBSITE = 'website', + OTHER = 'other' +} + +class ContactRequest { + @Property.string({ + displayName: 'What is it about?', + enum: ContactTopic, + // a member without a label shows its value + enumLabels: { [ContactTopic.SOFTWARE]: 'Software', [ContactTopic.TAKEOVER]: 'Takeover', [ContactTopic.OTHER]: 'Something else' }, + displayStyle: 'segmented' + }) + topic!: ContactTopic; +} + +// like a field that loads the entity again, which the server answers as json. +@Component({ + selector: 'ngx-reload-field', + template: '' +}) +class ReloadFieldComponent extends BaseEntityFieldDirective { + protected reload(): void { + const json: Partial = JSON.parse('{ "id": "t1", "title": "Write the README", "dueAt": "2026-12-01T00:00:00.000Z" }') as Partial; + this.entity.set(json); + } +} + +class Ticket { + @Property.string({ displayName: 'Id', omitForCreate: true, readonly: true }) + id!: string; + + @Property.string({ displayName: 'Title' }) + title!: string; + + @Property.date({ displayName: 'Due', required: false }) + dueAt?: Date; + + @Property.custom({ displayName: 'Server', component: async () => await Promise.resolve(ReloadFieldComponent) }) + server?: unknown; +} + @Component({ selector: 'ngx-host', template: ` - + `, imports: [FormComponent, EntityFormComponent] @@ -79,6 +126,17 @@ class HostComponent { readonly value: WritableSignal> = signal(EntityUtilities.resolveDefaults(Contact)); readonly problems: WritableSignal = signal([]); readonly submits: WritableSignal = signal(0); + readonly replaced: WritableSignal | undefined> = signal(undefined); +} + +@Component({ + selector: 'ngx-draft-host', + template: '', + imports: [FormComponent, FormDraftDirective, EntityFormComponent] +}) +class DraftHostComponent { + readonly entity: EntityClass = Contact; + readonly value: WritableSignal> = signal({}); } async function render( @@ -118,6 +176,29 @@ describe('EntityFormComponent', () => { expect(fixture.componentInstance.value()).toEqual({ name: 'Ada', email: 'ada@example.com' }); }); + test('names every field by its property, so a form draft keeps what was typed and fills it in again', async () => { + sessionStorage.clear(); + const fixture: ComponentFixture = TestBed.createComponent(DraftHostComponent); + await fixture.whenStable(); + const root: HTMLElement = fixture.nativeElement as HTMLElement; + for (const [label, text] of [['Name', 'Ada'], ['Email', 'ada@example.com']]) { + const input: HTMLInputElement = findInput(root, label); + input.value = text; + input.dispatchEvent(new Event('input', { bubbles: true })); + } + await fixture.whenStable(); + expect(findInput(root, 'Name').name).toBe('name'); + // which the browser fills in by what the property says it holds + expect(findInput(root, 'Email').autocomplete).toBe('email'); + fixture.destroy(); + + // back on the page, like after a reload: the fields load their components after the first render + const again: ComponentFixture = TestBed.createComponent(DraftHostComponent); + await again.whenStable(); + expect(again.componentInstance.value()).toEqual({ name: 'Ada', email: 'ada@example.com' }); + sessionStorage.clear(); + }); + test('shows the properties of every tab in tabs, named by the property that names them, the first one General', async () => { const [, root] = await render(Customer); @@ -223,6 +304,34 @@ describe('EntityFormComponent', () => { expect(fixture.componentInstance.value()).toEqual({ billing: HEAD_OFFICE }); }); + test('shows a segmented enum as segments named by the labels of its members, and chooses one', async () => { + const [fixture, root] = await render(ContactRequest); + const radios: HTMLInputElement[] = [...root.querySelectorAll('input[type="radio"]')]; + expect(root.querySelector('select')).toBeNull(); + expect(root.querySelector('fieldset legend')?.textContent).toContain('What is it about?'); + expect(radios.map(radio => radio.closest('label')?.textContent?.trim())).toEqual(['Software', 'Takeover', 'website', 'Something else']); + expect(radios.every(radio => radio.name === 'topic' && radio.required)).toBe(true); + + radios[1]?.click(); + await fixture.whenStable(); + expect(fixture.componentInstance.value()).toEqual({ topic: ContactTopic.TAKEOVER }); + expect(radios[1]?.checked).toBe(true); + }); + + test('shows the entity a field replaced the values with in every field, made from its json, and emits it', async () => { + const [fixture, root] = await render(Ticket, 'update'); + fixture.componentInstance.value.set({ id: 't1', title: 'Write the docs' }); + await fixture.whenStable(); + await type(fixture, findInput(root, 'Title'), 'Something else'); + + FormTestingUtilities.click(root, 'Reload'); + await fixture.whenStable(); + const replaced: Partial = { id: 't1', title: 'Write the README', dueAt: new Date('2026-12-01T00:00:00.000Z') }; + expect(findInput(root, 'Title').value).toBe('Write the README'); + expect(fixture.componentInstance.value()).toEqual(replaced); + expect(fixture.componentInstance.replaced()).toEqual(replaced); + }); + test('keeps the password of an existing entity while its field stays empty', async () => { const [fixture, root] = await render(Account, 'update'); fixture.componentInstance.value.set({ email: 'ada@example.com' }); diff --git a/projects/ngx-entity/form/entity-form.component.ts b/projects/ngx-entity/form/entity-form.component.ts index 6cd0ead..0f3be2a 100644 --- a/projects/ngx-entity/form/entity-form.component.ts +++ b/projects/ngx-entity/form/entity-form.component.ts @@ -1,4 +1,4 @@ -import { afterNextRender, Component, computed, DestroyRef, ElementRef, inject, Injector, input, InputSignal, linkedSignal, model, ModelSignal, signal, Signal, WritableSignal } from '@angular/core'; +import { afterNextRender, Component, computed, DestroyRef, ElementRef, inject, Injector, input, InputSignal, linkedSignal, model, ModelSignal, output, OutputEmitterRef, signal, Signal, WritableSignal } from '@angular/core'; import { EntityClass, EntityProperty, EntityUtilities } from '@service-soft/ngx-entity/entity'; import { ENTITY_FORM_COMPONENT } from '@service-soft/ngx-entity/field-base'; import { TabComponent, TabsComponent } from '@service-soft/ui/tabs'; @@ -17,7 +17,8 @@ import { EntityFormUtilities } from './entity-form.utilities'; * positions of the properties. Bind the values two-way with [(value)], and put it inside a ui-form with the button that * saves, which only submits while every field is valid. Give it the problems the server answered, which show at their * fields until the user changes them. An invalid field on a tab that isn't shown opens its tab when the form is - * submitted. + * submitted. A field may replace the whole entity, like with the one the server answered after undoing a change set, + * which (replaced) emits. */ @Component({ selector: 'ngx-entity-form', @@ -56,6 +57,13 @@ export class EntityFormComponent { */ readonly value: ModelSignal> = model.required>(); + /** + * Emits the entity a field replaced the values with, like the one the server answered after undoing a change set, + * which the form shows from then on. It is what the server has now: compare the values with it, not with the entity + * the form started with, to know what the user changed. + */ + readonly replaced: OutputEmitterRef> = output>(); + /** * The tabs of the form, with their rows and fields. */ @@ -109,6 +117,19 @@ export class EntityFormComponent { this.openProblems.update(problems => problems.filter(problem => problem.key !== change.key)); } + /** + * Takes the entity a field replaced the values with, and emits it. + * @param entity - The entity, as json like the server answers it. + */ + protected replace(entity: Partial): void { + // the json of a server, like the service makes an entity of it: with dates, without passwords. + const values: Partial = EntityUtilities.resolveFromJson>(this.entity(), entity); + this.value.set(values); + // the problems were the ones of values that are gone now. + this.openProblems.set([]); + this.replaced.emit(values); + } + // the browser can't focus an invalid field on a hidden tab, so ui-form's focus doesn't reach it: the first one of a // submit opens its tab and gets focus once it shows. private openTabOfInvalid(event: Event): void { diff --git a/projects/ngx-entity/form/entity-form.utilities.spec.ts b/projects/ngx-entity/form/entity-form.utilities.spec.ts index 2685ef4..843a4e4 100644 --- a/projects/ngx-entity/form/entity-form.utilities.spec.ts +++ b/projects/ngx-entity/form/entity-form.utilities.spec.ts @@ -27,6 +27,18 @@ class Customer { company?: string; } +class Order { + // declared first, shown last + @Property.string({ displayName: 'History', position: { tab: 'last' } }) + history!: string; + + @Property.string({ displayName: 'Number' }) + number!: string; + + @Property.string({ displayName: 'Note', position: { tab: 3, tabName: 'Notes' }, display: order => order.number !== 'draft' }) + note!: string; +} + function resolveLayout(mode: 'create' | 'update', values: Partial = {}): EntityFormTab[] { return EntityFormUtilities.resolveTabs(EntityUtilities.resolveProperties(Customer), mode, values, tab => `Part ${tab}`); } @@ -47,6 +59,16 @@ describe('EntityFormUtilities', () => { ]); }); + test('puts the tab "last" after every numbered one, with the number after the highest of the class', () => { + const resolveOrderTabs: (values: Partial) => EntityFormTab[] = values => { + return EntityFormUtilities.resolveTabs(EntityUtilities.resolveProperties(Order), 'create', values, tab => `Part ${tab}`); + }; + + expect(resolveOrderTabs({}).map(tab => [tab.tab, tab.label])).toEqual([[1, 'Part 1'], [3, 'Notes'], [4, 'Part 4']]); + // keeps its number, which is its value in the tabs, while the tab before it is hidden + expect(resolveOrderTabs({ number: 'draft' }).map(tab => tab.tab)).toEqual([1, 4]); + }); + test('leaves out what the form doesn\'t display, or leaves out when creating or editing', () => { expect(resolveKeys(resolveLayout('update'))[0]).toEqual([['firstName', 'lastName'], ['id', 'notes', 'company']]); expect(resolveKeys(resolveLayout('create', { notes: 'private' }))[0]).toEqual([['firstName', 'lastName'], ['notes']]); diff --git a/projects/ngx-entity/form/entity-form.utilities.ts b/projects/ngx-entity/form/entity-form.utilities.ts index 24ed17e..2d73186 100644 --- a/projects/ngx-entity/form/entity-form.utilities.ts +++ b/projects/ngx-entity/form/entity-form.utilities.ts @@ -35,10 +35,11 @@ type LayoutContext = { export abstract class EntityFormUtilities { /** * Resolves the tabs of a form, their rows and the fields in them, from the positions of the properties. A property - * without a tab is on the first, the properties without a row share one after the others, and the ones without an - * order come last in their row; otherwise they keep the order of the class. A property the form doesn't display, - * or leaves out when creating or editing, is left out. An inline object gets the rows of the properties of its - * class, laid out the same way, whose values are at the path of the object. + * without a tab is on the first, and a tab 'last' comes after every numbered one, with the number after the highest + * of the class. The properties without a row share one after the others, and the ones without an order come last in + * their row; otherwise they keep the order of the class. A property the form doesn't display, or leaves out when + * creating or editing, is left out. An inline object gets the rows of the properties of its class, laid out the + * same way, whose values are at the path of the object. * @param properties - The properties of the entity. * @param mode - Whether the form creates an entity or edits one. * @param values - The values of the form, which conditions depend on. @@ -52,13 +53,28 @@ export abstract class EntityFormUtilities { tabLabel: (tab: number) => string ): EntityFormTab[] { const shown: EntityProperty[] = this.resolveShown(properties, mode, values); - return this.resolveGroups(shown, property => property.metadata.position.tab ?? 1).map(([tab, inTab]) => ({ + const lastTab: number = this.resolveLastTab(properties); + return this.resolveGroups(shown, property => this.resolveTab(property, lastTab)).map(([tab, inTab]) => ({ tab, label: inTab.find(property => property.metadata.position.tabName != undefined)?.metadata.position.tabName ?? tabLabel(tab), rows: this.resolveRows(inTab, { mode, values, path: undefined, optional: false }) })); } + // counted from every property, also the ones the form doesn't show right now: the last tab keeps its number, which + // is its value in the tabs, when a condition hides another tab. Never 1, whose default label is the first tab's. + private static resolveLastTab(properties: EntityProperty[]): number { + const tabs: number[] = properties.flatMap(({ metadata }) => { + return typeof metadata.position.tab === 'number' ? [metadata.position.tab] : []; + }); + return Math.max(1, ...tabs) + 1; + } + + private static resolveTab(property: EntityProperty, lastTab: number): number { + const tab: number | 'last' | undefined = property.metadata.position.tab; + return tab === 'last' ? lastTab : tab ?? 1; + } + private static resolveShown(properties: EntityProperty[], mode: EntityFormMode, values: Partial): EntityProperty[] { // the field of a relation edits its joinColumn, which needs no field of its own. const joinColumns: Set = new Set(properties.flatMap(({ metadata }) => { diff --git a/projects/ngx-entity/locale/messages.de.xlf b/projects/ngx-entity/locale/messages.de.xlf new file mode 100644 index 0000000..e77c7a6 --- /dev/null +++ b/projects/ngx-entity/locale/messages.de.xlf @@ -0,0 +1,179 @@ + + + + + + Delete + Löschen + + + This can't be undone. + Das kann nicht rückgängig gemacht werden. + + + Delete this? + Wirklich löschen? + + + Cancel + Abbrechen + + + Add + Hinzufügen + + + Add to + Zu hinzufügen + + + Cancel + Abbrechen + + + Date + Datum + + + Edit + Bearbeiten + + + Edit in + In bearbeiten + + + End + Ende + + + No + Nein + + + Remove + Entfernen + + + Save + Speichern + + + Start + Beginn + + + Yes + Ja + + + + + + + End + Ende + + + Start + Beginn + + + + + + + Repeat + wiederholen + + + The passwords differ. + Die Passwörter stimmen nicht überein. + + + Cancel + Abbrechen + + + Create + Erstellen + + + Edit + Bearbeiten + + + Save + Speichern + + + General + Allgemein + + + Tab + Reiter + + + These can be added once this is saved. + Diese können hinzugefügt werden, sobald gespeichert wurde. + + + Create + Erstellen + + + Delete + Löschen + + + + + + + export + Export + + + Export as CSV + Als CSV exportieren + + + Export as JSON + Als JSON exportieren + + + Export as XML + Als XML exportieren + + + Import + Importieren + + + No + Nein + + + Yes + Ja + + + Discard + Verwerfen + + + Keep editing + Weiter bearbeiten + + + What you changed hasn't been saved and will be lost. + Ihre Änderungen wurden nicht gespeichert und gehen verloren. + + + Discard your changes? + Änderungen verwerfen? + + + + diff --git a/projects/ngx-entity/ng-package.json b/projects/ngx-entity/ng-package.json index 30d02c3..fb28f1b 100644 --- a/projects/ngx-entity/ng-package.json +++ b/projects/ngx-entity/ng-package.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/ng-packagr/ng-package.schema.json", - "assets": ["tailwind.css"], + "assets": ["tailwind.css", "locale/messages.de.xlf", "CHANGELOG.md"], "dest": "../../dist/ngx-entity", "lib": { "entryFile": "src/public-api.ts" diff --git a/projects/ngx-entity/package.json b/projects/ngx-entity/package.json index 095c5c2..823849a 100644 --- a/projects/ngx-entity/package.json +++ b/projects/ngx-entity/package.json @@ -1,6 +1,6 @@ { "name": "@service-soft/ngx-entity", - "version": "22.3.2", + "version": "22.4.0", "license": "MIT", "repository": { "type": "git", @@ -19,20 +19,24 @@ } }, "peerDependencies": { + "@angular/aria": "^22.2.0", "@angular/common": "^22.2.0", "@angular/core": "^22.2.0", "@angular/localize": "^22.2.0", "@angular/router": "^22.2.0", - "@service-soft/ngx-error-handling": "^22.3.2", - "@service-soft/ngx-pwa": "^22.3.2", - "@service-soft/ui": "^22.3.2", + "@service-soft/ngx-error-handling": "^22.4.0", + "@service-soft/ngx-pwa": "^22.4.0", + "@service-soft/ui": "^22.4.0", "tailwindcss": "^4.3.3", - "zibri-contract": "^3.1.0" + "zibri-contract": "^3.3.0" }, "peerDependenciesMeta": { "@service-soft/ngx-pwa": { "optional": true } }, - "sideEffects": false + "sideEffects": false, + "translations": { + "de": "./locale/messages.de.xlf" + } } \ No newline at end of file diff --git a/projects/ngx-entity/page/entity-page.component.spec.ts b/projects/ngx-entity/page/entity-page.component.spec.ts index bff8336..f0646e7 100644 --- a/projects/ngx-entity/page/entity-page.component.spec.ts +++ b/projects/ngx-entity/page/entity-page.component.spec.ts @@ -6,18 +6,29 @@ import { TestBed } from '@angular/core/testing'; import { provideRouter, Router } from '@angular/router'; import { RouterTestingHarness } from '@angular/router/testing'; import { EntityClass, Property } from '@service-soft/ngx-entity/entity'; +import { BaseEntityFieldDirective } from '@service-soft/ngx-entity/field-base'; import { EntityRouteUtilities } from '@service-soft/ngx-entity/routes'; import { EntityService } from '@service-soft/ngx-entity/service'; import { DialogTestingUtilities } from 'testing/dialog'; import { FormTestingUtilities } from 'testing/form'; import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; +// like a field that loads the task again, after somebody else changed it. +@Component({ + selector: 'ngx-reload-field', + template: '' +}) +class ReloadFieldComponent extends BaseEntityFieldDirective {} + class Task { @Property.string({ displayName: 'Id', omitForCreate: true, readonly: true }) id!: string; @Property.string({ displayName: 'Title' }) title!: string; + + @Property.custom({ displayName: 'Server', component: async () => await Promise.resolve(ReloadFieldComponent) }) + server?: unknown; } @Injectable({ providedIn: 'root' }) @@ -128,4 +139,20 @@ describe('EntityPageComponent', () => { // saved, so leaving asks nothing await waitForUrl('/tasks'); }); + + test('takes the entity a field replaced the values with as saved, so leaving asks nothing', async () => { + const [harness, http] = await open('/tasks/a1'); + await vi.waitFor(() => http.expectOne({ method: 'GET', url: '/api/tasks/a1' })).then(request => request.flush(TASK)); + const page: HTMLElement = await vi.waitFor(() => { + TestBed.tick(); + return harness.routeNativeElement ?? document.body; + }); + await type(page, 'Title', 'Something else'); + + FormTestingUtilities.click(page, 'Reload'); + TestBed.tick(); + expect((await findInput(page, 'Title')).value).toBe('Write the README'); + FormTestingUtilities.click(page, 'Cancel'); + await waitForUrl('/tasks'); + }); }); \ No newline at end of file diff --git a/projects/ngx-entity/table/entity-table.component.spec.ts b/projects/ngx-entity/table/entity-table.component.spec.ts index f422536..fecc2c0 100644 --- a/projects/ngx-entity/table/entity-table.component.spec.ts +++ b/projects/ngx-entity/table/entity-table.component.spec.ts @@ -26,7 +26,7 @@ class Task { @Property.string({ displayName: 'Title' }) title!: string; - @Property.string({ displayName: 'Status', enum: TaskStatus }) + @Property.string({ displayName: 'Status', enum: TaskStatus, enumLabels: { [TaskStatus.DONE]: 'Done' } }) status!: TaskStatus; @Property.number({ displayName: 'Hours' }) @@ -135,7 +135,7 @@ describe('EntityTableComponent', () => { .join('') .trim()); expect(headers).toEqual(['Title', 'Status', 'Hours', 'Billable', 'Due', 'Code']); - expect(findCells(root)).toEqual(['Write the docs', 'done', '1,234.5', 'Yes', 'Mar 1, 2026', 'A1']); + expect(findCells(root)).toEqual(['Write the docs', 'Done', '1,234.5', 'Yes', 'Mar 1, 2026', 'A1']); }); test('orders by the columns of the order config, and asks the server for that order', async () => { @@ -156,6 +156,8 @@ describe('EntityTableComponent', () => { const billable: HTMLSelectElement | undefined = findFilterSelect(root, 'Filter Billable'); // a range has no input in the table expect(root.querySelector('[aria-label="Filter Hours"]')).toBeNull(); + // the members of an enum by their labels, a member without one by its value + expect([...status?.options ?? []].map(option => option.text.trim())).toEqual(expect.arrayContaining(['open', 'Done'])); if (title != undefined && status != undefined && billable != undefined) { title.value = 'docs'; diff --git a/projects/ngx-entity/table/entity-table.utilities.ts b/projects/ngx-entity/table/entity-table.utilities.ts index a6fac97..6d3def4 100644 --- a/projects/ngx-entity/table/entity-table.utilities.ts +++ b/projects/ngx-entity/table/entity-table.utilities.ts @@ -101,7 +101,9 @@ export abstract class EntityTableUtilities { return { type: 'select', options: [{ label: config.yesLabel, value: true }, { label: config.noLabel, value: false }] }; } if ((metadata.type === 'string' || metadata.type === 'number') && metadata.enum != undefined) { - return SELECT_MATCHES.has(match) ? { type: 'select', options: EntityUtilities.resolveEnumMembers(metadata.enum) } : undefined; + return SELECT_MATCHES.has(match) + ? { type: 'select', options: EntityUtilities.resolveEnumMembers(metadata.enum, metadata.enumLabels) } + : undefined; } return metadata.type === 'string' && TEXT_MATCHES.has(match) ? { type: 'text' } : undefined; } diff --git a/projects/ngx-error-handling/CHANGELOG.md b/projects/ngx-error-handling/CHANGELOG.md new file mode 100644 index 0000000..a6fd6d3 --- /dev/null +++ b/projects/ngx-error-handling/CHANGELOG.md @@ -0,0 +1,11 @@ +# Changelog + +## 22.4.0 + +### Breaking changes +- The peer `zibri-contract` is `^3.3.0`, was `^3.1.0`, like in every library of `@service-soft`. + +### Features +- `ErrorResponseUtilities.findMessage(error)`: the message of an error response, its paragraphs one per line, or + `undefined` when it has none. +- The German translation of the texts ships with the package (`locale/messages.de.xlf`). diff --git a/projects/ngx-error-handling/README.md b/projects/ngx-error-handling/README.md index af88140..00b5d77 100644 --- a/projects/ngx-error-handling/README.md +++ b/projects/ngx-error-handling/README.md @@ -68,6 +68,8 @@ Errors your code catches show none, like the ones the forms of [@service-soft/ng ## Translating The default texts are `$localize` with an id of their own, like `@@ngx-error-handling.error-dialog.failedTitle`, so `ng extract-i18n` puts them into the messages of your app, and you translate them like its own texts. The dialog needs `@angular/localize` for that, `ng add @angular/localize`, also in an app of one language. A build with `localize` fills the texts in, so no part of `@angular/localize` reaches the browser. The defaults are made once an error is handled, so translations an app loads at runtime with `loadTranslations` apply as well. A text of `showDialogErrorHandler` replaces the default in every language. So translate a default in your messages, and change it in the config only to say something else: a default the config replaces stays in your messages, though nothing shows it. +German ships with the library: `locale/messages.de.xlf` of the package is an XLIFF 1.2 file with a German target for each of its texts, and its `package.json` names it in `"translations": { "de": "./locale/messages.de.xlf" }`. A merge of the translations of an app's dependencies reads that field and fills these targets into the German messages of the app, so German needs no translation of your own. Only the texts your app uses end up there, since its `ng extract-i18n` decides which units its messages have. Other languages you translate in your messages. + # The error body of zibri `@service-soft/ngx-error-handling/error-response` reads what zibri answers a refused or failed request with, without any ui: @@ -75,7 +77,7 @@ The default texts are `$localize` with an id of their own, like `@@ngx-error-han const body: ErrorResponseBody | undefined = ErrorResponseUtilities.findErrorResponseBody(error); ``` -It has the `status`, `name`, `message` and `paragraphs` of the error, the `problems` of a request that failed validation, and the `traceId`. +It has the `status`, `name`, `message` and `paragraphs` of the error, the `problems` of a request that failed validation, and the `traceId`. `findMessage(error)` answers the message to show the user, its paragraphs one per line, or `undefined` for an error without a body of zibri, like without a connection. # Moving from ngx-material-auth The `HttpErrorInterceptor` of ngx-material-auth showed an error dialog for every failed request, the ones the app handled itself as well. `provideErrorHandler(showDialogErrorHandler())` shows the errors nothing caught, read from the error body of zibri. diff --git a/projects/ngx-error-handling/error-response/error-response.utilities.spec.ts b/projects/ngx-error-handling/error-response/error-response.utilities.spec.ts index cdf0592..cb9e10f 100644 --- a/projects/ngx-error-handling/error-response/error-response.utilities.spec.ts +++ b/projects/ngx-error-handling/error-response/error-response.utilities.spec.ts @@ -32,4 +32,23 @@ describe('ErrorResponseUtilities', () => { expect(ErrorResponseUtilities.findErrorResponseBody(new HttpErrorResponse({ status: 502, error: 'Bad Gateway' }))).toBeUndefined(); expect(ErrorResponseUtilities.findErrorResponseBody(new Error('A mistake of the app.'))).toBeUndefined(); }); + + test('finds the message of zibri, its paragraphs one per line', () => { + const error: HttpErrorResponse = new HttpErrorResponse({ + status: 409, + error: { + status: 409, + name: 'ConflictError', + message: 'The fiscal year is closed. Post into an open one.', + paragraphs: ['The fiscal year is closed.', 'Post into an open one.'] + } + }); + + expect(ErrorResponseUtilities.findMessage(error)).toBe('The fiscal year is closed.\nPost into an open one.'); + expect(ErrorResponseUtilities.findMessage(new HttpErrorResponse({ + status: 400, + error: { status: 400, name: 'BadRequestError', message: 'Invalid data.', paragraphs: [] } + }))).toBe('Invalid data.'); + expect(ErrorResponseUtilities.findMessage(new HttpErrorResponse({ status: 0, error: new ProgressEvent('error') }))).toBeUndefined(); + }); }); \ No newline at end of file diff --git a/projects/ngx-error-handling/error-response/error-response.utilities.ts b/projects/ngx-error-handling/error-response/error-response.utilities.ts index af67b3f..78697b0 100644 --- a/projects/ngx-error-handling/error-response/error-response.utilities.ts +++ b/projects/ngx-error-handling/error-response/error-response.utilities.ts @@ -32,6 +32,19 @@ export abstract class ErrorResponseUtilities { }; } + /** + * Finds the message of zibri in what a request failed with, to show it to the user, like why a request was refused. + * @param error - What the request failed with. + * @returns The paragraphs of the message, one per line, or undefined for an error that isn't one of zibri's. + */ + static findMessage(error: unknown): string | undefined { + const body: ErrorResponseBody | undefined = this.findErrorResponseBody(error); + if (body == undefined) { + return undefined; + } + return body.paragraphs.length ? body.paragraphs.join('\n') : body.message; + } + private static findProblems(problems: unknown): ValidationProblem[] | undefined { return Array.isArray(problems) ? problems.filter((problem: unknown) => this.isProblem(problem)) : undefined; } diff --git a/projects/ngx-error-handling/locale/messages.de.xlf b/projects/ngx-error-handling/locale/messages.de.xlf new file mode 100644 index 0000000..7a47ddf --- /dev/null +++ b/projects/ngx-error-handling/locale/messages.de.xlf @@ -0,0 +1,39 @@ + + + + + + OK + OK + + + Something went wrong. Please try again later. + Etwas ist schiefgelaufen. Bitte versuchen Sie es später erneut. + + + Something went wrong + Etwas ist schiefgelaufen + + + Check your connection and try again. + Prüfen Sie Ihre Verbindung und versuchen Sie es erneut. + + + No connection + Keine Verbindung + + + : + : + + + Reference: + Referenz: + + + That didn't work + Das hat nicht funktioniert + + + + diff --git a/projects/ngx-error-handling/ng-package.json b/projects/ngx-error-handling/ng-package.json index d11b4d0..8f97100 100644 --- a/projects/ngx-error-handling/ng-package.json +++ b/projects/ngx-error-handling/ng-package.json @@ -1,6 +1,6 @@ { "$schema": "../../node_modules/ng-packagr/ng-package.schema.json", - "assets": ["tailwind.css"], + "assets": ["tailwind.css", "locale/messages.de.xlf", "CHANGELOG.md"], "dest": "../../dist/ngx-error-handling", "lib": { "entryFile": "src/public-api.ts" diff --git a/projects/ngx-error-handling/package.json b/projects/ngx-error-handling/package.json index f8a32c6..f13d76a 100644 --- a/projects/ngx-error-handling/package.json +++ b/projects/ngx-error-handling/package.json @@ -1,6 +1,6 @@ { "name": "@service-soft/ngx-error-handling", - "version": "22.3.2", + "version": "22.4.0", "license": "MIT", "repository": { "type": "git", @@ -22,9 +22,9 @@ "@angular/common": "^22.2.0", "@angular/core": "^22.2.0", "@angular/localize": "^22.2.0", - "@service-soft/ui": "^22.3.2", + "@service-soft/ui": "^22.4.0", "tailwindcss": "^4.3.3", - "zibri-contract": "^3.1.0" + "zibri-contract": "^3.3.0" }, "peerDependenciesMeta": { "@angular/localize": { @@ -37,5 +37,8 @@ "optional": true } }, - "sideEffects": false + "sideEffects": false, + "translations": { + "de": "./locale/messages.de.xlf" + } } \ No newline at end of file diff --git a/projects/ngx-navigation/CHANGELOG.md b/projects/ngx-navigation/CHANGELOG.md new file mode 100644 index 0000000..1d39944 --- /dev/null +++ b/projects/ngx-navigation/CHANGELOG.md @@ -0,0 +1,20 @@ +# Changelog + +## 22.4.0 + +### Breaking changes +- The navbar starts with a "Skip to content" button, shown on focus, which moves the focus to `NavbarConfig.content` + (`'main'` by default). Give the main content of your app that selector, or configure another one. +- `NavbarConfig.content`, `NavbarLabels.skipToContent` and `NavigationConfig.rowWidth` are new keys. Code that builds + one of these configs completely by hand has to add them; the providers take partial configs as before. + +### Features +- `NavigationConfig.rowWidth` (`'full'` or `'content'`, type `NavRowWidth`), and the inputs `width` and `stacked` of + `ngx-nav-row`. +- The footer stacks its groups, centered, on phones. +- The German translation of the texts ships with the package (`locale/messages.de.xlf`). +- Icons are imported from one file each, so a page only loads the icons it shows. + +### Fixes +- The language switcher replaces a language prefix that is already in the url, instead of adding a second one, like + `/de/de/…`. diff --git a/projects/ngx-navigation/README.md b/projects/ngx-navigation/README.md index 2ea9830..4bd189e 100644 --- a/projects/ngx-navigation/README.md +++ b/projects/ngx-navigation/README.md @@ -88,7 +88,7 @@ export const navbarComponents: Partial = { ``` -The navbar is a `
` with a `