exchangealgebra 0.6.1.1 → 0.7.0.0
raw patch · 192 files changed
+16580/−10592 lines, 192 filesdep −numeric-prelude
Dependencies removed: numeric-prelude
Files
- ChangeLog.md +459/−0
- LICENSE +0/−39
- LICENSE.txt +21/−0
- README.md +230/−165
- docs/admission-api-design-notes.md +0/−163
- exchangealgebra.cabal +20/−56
- src/ExchangeAlgebra.hs +38/−36
- src/ExchangeAlgebra/Accounting.hs +13/−10
- src/ExchangeAlgebra/Accounting/Account.hs +3/−15
- src/ExchangeAlgebra/Accounting/Account/Aliases.hs +0/−217
- src/ExchangeAlgebra/Accounting/Account/Jcci.hs +1037/−0
- src/ExchangeAlgebra/Accounting/Account/PostingPolicy.hs +1/−1
- src/ExchangeAlgebra/Accounting/Account/Registry.hs +58/−4041
- src/ExchangeAlgebra/Accounting/Account/Spec.hs +54/−0
- src/ExchangeAlgebra/Accounting/Account/Title.hs +5949/−573
- src/ExchangeAlgebra/Accounting/Account/Vocabulary.hs +95/−0
- src/ExchangeAlgebra/Accounting/Adjustment.hs +1/−1
- src/ExchangeAlgebra/Accounting/Audit.hs +437/−0
- src/ExchangeAlgebra/Accounting/Catalog.hs +8/−2
- src/ExchangeAlgebra/Accounting/Closing.hs +173/−41
- src/ExchangeAlgebra/Accounting/Consolidation.hs +109/−57
- src/ExchangeAlgebra/Accounting/Entries.hs +5/−3
- src/ExchangeAlgebra/Accounting/Exchange.hs +123/−53
- src/ExchangeAlgebra/Accounting/PostingPolicy.hs +0/−5
- src/ExchangeAlgebra/Accounting/Statements.hs +36/−21
- src/ExchangeAlgebra/Accounting/Statements/Group.hs +44/−22
- src/ExchangeAlgebra/Accounting/Statements/Metric.hs +23/−32
- src/ExchangeAlgebra/Accounting/Statements/Presentation.hs +279/−202
- src/ExchangeAlgebra/Accounting/Transfer.hs +2/−2
- src/ExchangeAlgebra/Accounting/TrialBalance.hs +3/−17
- src/ExchangeAlgebra/Accounting/TrialBalance/Accum.hs +33/−9
- src/ExchangeAlgebra/Accounting/TrialBalance/Balance.hs +13/−5
- src/ExchangeAlgebra/Accounting/TrialBalance/Validation.hs +5/−331
- src/ExchangeAlgebra/Algebra.hs +4/−4
- src/ExchangeAlgebra/Algebra/Base.hs +7/−7
- src/ExchangeAlgebra/Algebra/Base/Account/JcciAliases.hs +0/−4
- src/ExchangeAlgebra/Algebra/Base/Account/Registry.hs +0/−8
- src/ExchangeAlgebra/Algebra/Base/Account/Types.hs +0/−8
- src/ExchangeAlgebra/Algebra/Base/Element.hs +0/−10
- src/ExchangeAlgebra/Algebra/Base/Representation.hs +3/−10
- src/ExchangeAlgebra/Algebra/Core/Representation.hs +495/−213
- src/ExchangeAlgebra/Algebra/Element.hs +6/−7
- src/ExchangeAlgebra/Algebra/Element/Representation.hs +47/−55
- src/ExchangeAlgebra/Algebra/Internal.hs +11/−5
- src/ExchangeAlgebra/Algebra/Posting.hs +7/−8
- src/ExchangeAlgebra/Algebra/Transfer/Representation.hs +28/−56
- src/ExchangeAlgebra/Algebra/Transfer/Rule.hs +0/−119
- src/ExchangeAlgebra/Algebra/Value.hs +71/−23
- src/ExchangeAlgebra/Algebra/Value/Class.hs +2/−2
- src/ExchangeAlgebra/Assist.hs +0/−14
- src/ExchangeAlgebra/Assist/Descriptions.hs +0/−9
- src/ExchangeAlgebra/Bookkeeping.hs +0/−33
- src/ExchangeAlgebra/Consolidation/Worksheet.hs +0/−22
- src/ExchangeAlgebra/Convert.hs +0/−24
- src/ExchangeAlgebra/Convert/Checked.hs +0/−31
- src/ExchangeAlgebra/Convert/Csv.hs +0/−17
- src/ExchangeAlgebra/IO/Input.hs +26/−8
- src/ExchangeAlgebra/IO/Input/Admission.hs +7/−6
- src/ExchangeAlgebra/IO/Input/Admission/Engine.hs +3/−2
- src/ExchangeAlgebra/IO/Input/Assist.hs +12/−7
- src/ExchangeAlgebra/IO/Input/Checked.hs +205/−178
- src/ExchangeAlgebra/IO/Input/Conversion.hs +177/−50
- src/ExchangeAlgebra/IO/Input/Csv.hs +88/−31
- src/ExchangeAlgebra/IO/Output/Statements.hs +65/−45
- src/ExchangeAlgebra/Journal.hs +10/−10
- src/ExchangeAlgebra/Journal/Core.hs +9/−9
- src/ExchangeAlgebra/Journal/Core/Representation.hs +194/−216
- src/ExchangeAlgebra/Journal/Transfer/Rule.hs +2/−24
- src/ExchangeAlgebra/Posting.hs +0/−8
- src/ExchangeAlgebra/Render/Bookkeeping.hs +0/−32
- src/ExchangeAlgebra/Render/Csv.hs +0/−26
- src/ExchangeAlgebra/Render/Simulation.hs +1/−1
- src/ExchangeAlgebra/Reporting/Group.hs +0/−23
- src/ExchangeAlgebra/Reporting/Metric.hs +0/−16
- src/ExchangeAlgebra/Reporting/Presentation.hs +0/−28
- src/ExchangeAlgebra/Simulate.hs +3/−3
- src/ExchangeAlgebra/Simulate/Analysis.hs +1/−1
- src/ExchangeAlgebra/Simulate/Engine.hs +3/−3
- src/ExchangeAlgebra/Simulate/Lite.hs +12/−12
- src/ExchangeAlgebra/Simulate/Policy.hs +20/−20
- src/ExchangeAlgebra/Simulate/Random.hs +3/−3
- src/ExchangeAlgebra/Simulate/Spill.hs +2/−2
- src/ExchangeAlgebra/Simulate/Visualize.hs +2/−2
- src/ExchangeAlgebra/Simulation/Analysis.hs +1/−1
- src/ExchangeAlgebra/Simulation/Network/Csv.hs +1/−1
- src/ExchangeAlgebra/Simulation/Network/Representation.hs +116/−69
- src/ExchangeAlgebra/Simulation/Output.hs +1/−1
- src/ExchangeAlgebra/TrialBalance/Balance.hs +0/−15
- src/ExchangeAlgebra/TrialBalance/Validation.hs +0/−12
- src/ExchangeAlgebra/Value.hs +0/−74
- test/Accounting/AuditSpec.hs +172/−0
- test/Accounting/ClosingTargetSpec.hs +285/−0
- test/Accounting/ConsolidationVocabularySpec.hs +482/−0
- test/Accounting/JcciSpec.hs +175/−0
- test/Accounting/PresentationVocabularySpec.hs +288/−0
- test/Accounting/ProcedureLawSpec.hs +294/−0
- test/Accounting/RegistrySpec.hs +162/−338
- test/Accounting/VocabularyLawSpec.hs +705/−0
- test/Algebra/CoreSpec.hs +289/−52
- test/Algebra/ExactReadoutSpec.hs +95/−0
- test/Algebra/PairSpec.hs +500/−0
- test/Algebra/ProjWildcardSpec.hs +33/−28
- test/Golden/ReadoutBaseline.hs +18/−8
- test/Golden/WireFormat.hs +58/−32
- test/Golden/WriteRows.hs +11/−4
- test/IO/AccountNamesSpec.hs +334/−0
- test/IO/InputOutputSpec.hs +16/−11
- test/Journal/JournalSpec.hs +131/−10
- test/Journal/NormalFormSpec.hs +1/−1
- test/Posting/PostingSpec.hs +3/−3
- test/Simulate/SimulateSpec.hs +11/−10
- test/Simulation/NetworkSpec.hs +134/−4
- test/Spec.hs +18/−0
- test/Surface/Accounting.hs +2/−4
- test/Surface/Render/Bookkeeping.hs +2/−2
- test/Surface/Render/Csv.hs +2/−2
- test/Surface/Simulate/Engine.hs +3/−3
- test/Transfer/RuleSpec.hs +57/−116
- test/Value/MoneyDoubleBinarySpec.hs +60/−0
- test/compat-clients/MixedPath.hs +7/−13
- test/compat-clients/NewPath.hs +62/−2
- test/compat-clients/OldPath.hs +5/−5
- test/compat-clients/README.md +4/−6
- test/compat-clients/check.sh +1/−1
- test/compile-fail/DeprecatedTransfer.hs +0/−9
- test/compile-fail/JcciHiddenConstructor.hs +7/−0
- test/compile-fail/JcciMacroTitle.hs +6/−0
- test/compile-fail/check.sh +39/−20
- test/doctests.hs +6/−7
- test/fixtures/account-algebra-behavior/presentation.tsv +1/−1
- test/fixtures/account-algebra-behavior/projection-membership.tsv +1/−1
- test/fixtures/account-algebra-behavior/semantics.tsv +244/−244
- test/fixtures/account-semantics-050/account-info.tsv +16/−16
- test/fixtures/account-semantics-050/metadata.tsv +1/−1
- test/fixtures/account-semantics-050/suggest.tsv +263/−257
- test/fixtures/export-surface-p2/ExchangeAlgebra.Accounting.Account.Jcci.txt +234/−0
- test/fixtures/export-surface-p2/ExchangeAlgebra.Accounting.PostingPolicy.txt +0/−7
- test/fixtures/export-surface-p2/ExchangeAlgebra.Accounting.txt +14/−8
- test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Base.Account.JcciAliases.txt +0/−1
- test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Base.Account.Registry.txt +0/−23
- test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Base.Account.Types.txt +0/−46
- test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Base.Element.txt +0/−277
- test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Base.txt +4/−4
- test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Internal.txt +7/−4
- test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Transfer.Rule.txt +0/−36
- test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Transfer.txt +0/−1
- test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.txt +4/−4
- test/fixtures/export-surface-p2/ExchangeAlgebra.Assist.Descriptions.txt +0/−1
- test/fixtures/export-surface-p2/ExchangeAlgebra.Assist.txt +0/−16
- test/fixtures/export-surface-p2/ExchangeAlgebra.Bookkeeping.txt +0/−19
- test/fixtures/export-surface-p2/ExchangeAlgebra.Consolidation.Worksheet.txt +0/−73
- test/fixtures/export-surface-p2/ExchangeAlgebra.Convert.Checked.txt +0/−40
- test/fixtures/export-surface-p2/ExchangeAlgebra.Convert.Csv.txt +0/−5
- test/fixtures/export-surface-p2/ExchangeAlgebra.Convert.txt +0/−13
- test/fixtures/export-surface-p2/ExchangeAlgebra.Journal.Transfer.Rule.txt +0/−1
- test/fixtures/export-surface-p2/ExchangeAlgebra.Journal.txt +8/−8
- test/fixtures/export-surface-p2/ExchangeAlgebra.Posting.txt +0/−13
- test/fixtures/export-surface-p2/ExchangeAlgebra.Render.Bookkeeping.txt +0/−12
- test/fixtures/export-surface-p2/ExchangeAlgebra.Render.Csv.txt +0/−2
- test/fixtures/export-surface-p2/ExchangeAlgebra.Reporting.Group.txt +0/−36
- test/fixtures/export-surface-p2/ExchangeAlgebra.Reporting.Metric.txt +0/−22
- test/fixtures/export-surface-p2/ExchangeAlgebra.Reporting.Presentation.txt +0/−111
- test/fixtures/export-surface-p2/ExchangeAlgebra.Simulate.Policy.txt +3/−3
- test/fixtures/export-surface-p2/ExchangeAlgebra.TrialBalance.Balance.txt +0/−12
- test/fixtures/export-surface-p2/ExchangeAlgebra.TrialBalance.Validation.txt +0/−35
- test/fixtures/export-surface-p2/ExchangeAlgebra.Value.txt +0/−13
- test/fixtures/export-surface-p2/ExchangeAlgebra.txt +24/−40
- test/fixtures/export-surface-p2/counts.tsv +6/−27
- test/fixtures/export-surface-p2/orphans.txt +7/−2
- test/fixtures/jcci-2022/README.md +9/−9
- test/fixtures/jcci-2022/queries.tsv +1/−1
- test/fixtures/jcci-2022/source.tsv +1/−1
- test/fixtures/post-vocab/README.md +5/−4
- test/fixtures/post-vocab/account-info.tsv +14/−14
- test/fixtures/post-vocab/ordinals.tsv +0/−245
- test/fixtures/post-vocab/semantics.tsv +1/−1
- test/fixtures/post-vocab/suggest.tsv +278/−272
- test/fixtures/pre-vland2/ordinals.tsv +0/−118
- test/fixtures/readout-baseline-p1/README.md +2/−2
- test/fixtures/readout-baseline-p1/alg-decimal-f-dec2.tsv +0/−3
- test/fixtures/readout-baseline-p1/alg-decimal-f-int.tsv +0/−3
- test/fixtures/readout-baseline-p1/alg-double-f-cancel.tsv +0/−3
- test/fixtures/readout-baseline-p1/alg-double-f-dec2.tsv +0/−3
- test/fixtures/readout-baseline-p1/alg-double-f-exp.tsv +0/−3
- test/fixtures/readout-baseline-p1/alg-double-f-int.tsv +0/−3
- test/fixtures/readout-baseline-p1/alg-double-f-sub.tsv +0/−3
- test/fixtures/registry-aliases/alias-resolution.tsv +2/−6
- test/fixtures/statement-presentation/presentation.txt +5/−5
- test/fixtures/wire-format-p2/decode-boundaries.tsv +2/−2
- test/fixtures/wire-format-p2/wire-format.tsv +3/−6
- test/fixtures/write-rows-0510/ebex8-journal.tsv +2/−2
- tools/check-orphans.py +23/−10
ChangeLog.md view
@@ -1,5 +1,464 @@ # Changelog for ExchangeAlgebra +## 0.7.0.0 - 2026-11-27++### Added++- Import `ExchangeAlgebra.Accounting.Account.Jcci` to use `JcciTitles` in+ ledgers limited to JCCI account titles. Use `widen` to embed a title in+ `AccountTitles`, and `narrow` or `narrowAlg` to restrict a title or ledger+ to the JCCI vocabulary.++- Closing supports caller-defined account title types through `AccountVocabulary`.+ `closingEntries` and `settleEntries` close to the vocabulary's `closingTarget`,+ preserving every non-account coordinate. `ExchangeAlgebra.Accounting.Closing`+ exports `ClosingTargetViolation`, `closingTargetViolation`, and `ClosingError`.+ The target check rejects wildcard titles, titles without a specification,+ non-equity titles, and contra titles before reading the ledger or settlement nets.++- Journal input accepts caller-defined account names. Build a table with+ `accountNameTable`, start from `defaultAccountNames` or `vocabularyNames`,+ and add local names with `extendAccountNames`. Pass `resolveWith table` to+ `parseJournalCsvBy`, `parseNotedJournalCsvBy`, `checkedEntryTextBy`, or+ `certifyJournalTextBy`. Shared names report all distinct candidates in insertion order.+ The checked readers report `MissingPostingSemantics` when a concrete title's+ vocabulary omits its posting capability.++- Random-input property tests (`test/Accounting/ProcedureLawSpec.hs`, 200 cases each for+ `Double` and `MoneyDecimal`, exact `Rational` observation) for two procedures derived from+ the journal. No library code changed.+ - `closingEntries`, on ledgers over every account in two units:+ CL1 the entries have equal exact debit and credit totals;+ CL2 after adding them, every account with a `closingSide` has net zero;+ CL3 every other account except `RetainedEarnings` keeps its net and receives no posting;+ CL4 per unit, the change of `RetainedEarnings` equals the nets of `ClosingKeep` accounts+ (revenue, contra cost) minus the nets of `ClosingFlip` accounts (cost, contra revenue),+ that is, the period's net income.+ - Consolidation worksheet (`validateConsolidationWorksheet`, `combinedWorksheet`):+ CW1 balanced source trial balances and adjustments are accepted and their combination is+ balanced; CW2 the combination has the same exact net on every base as the inputs added in+ reverse order and keeps every input posting; CW3 one unbalanced adjustment or source is+ rejected with an error naming it.+ These complement the existing closing laws L2, L3, L5 and C1-C3, C5+ (`test/Transfer/RuleSpec.hs`), which use three or four accounts.++- `hatForSide`, `postingForSide`, and `journalForSides` in+ `ExchangeAlgebra.Accounting.Exchange` construct debit/credit postings for any unmarked base+ with an `ExBaseClass` instance, including multi-axis bases. The input-conversion helpers keep+ their account-only types and delegate to these functions. Repeated postings remain separate.++- `ExchangeAlgebra.Accounting.Audit` provides audits that report one type of+ accounting anomaly each, without blocking any computation. Every audit+ returns `AuditResult`: `NoProblem`, `Warning` for findings with legitimate+ exceptions, or `Error` for findings without one and for structure issues+ (invalid values and wildcard bases, which every audit checks first).+ - `impossibleBalances`: credit balance of cash or petty cash, debit balance+ of capital stock or accumulated depreciation (`Error`).+ - `abnormalBalances`: balance opposite to a fixed home side, except the+ accounts above (`Warning`).+ - `temporaryAccountBalances`: balance of suspense payments, suspense+ receipts, or the suspense account after adjustment (`Warning`).+ - `closingResiduals`: balance that closing must clear, in a trial balance+ after closing (`Error`).+ - `duplicateTransactions`: notes with identical postings (`Warning`).+ - `contraryNominalPostings`: revenue or expense posting opposite to its+ home side, outside closing transactions (`Warning`).++- `AccountVocabulary` (`ExchangeAlgebra.Accounting.Account`): `vocabSpec`,+ `vocabSemantics`, `closingTarget`, `vocabDivision`, `vocabContra`, with laws in the Haddock+ (the closing target is concrete, has an `Equity` spec and is not a contra account). The+ `AccountTitles` instance reads the existing registry and closes to `RetainedEarnings`.++### Changed++- **Breaking (0.7).** Update imports, uses, and instance definitions for the+ renamed base element keys, note fields, note periods, and equity projection.++ | Previous name | New name |+ | --- | --- |+ | `AxisKey` | `ElementKey` |+ | `axisIsWildcard` | `elementKeyIsWildcard` |+ | `AxisDecompose` | `HasElementKeys` |+ | `toAxisKeys` | `toElementKeys` |+ | `NoteAxisKey` | `NoteFieldKey` |+ | `NoteAxisPosting` | `NoteFieldIndex` |+ | `emptyNoteAxisPosting` | `emptyNoteFieldIndex` |+ | `insertNoteAxisPosting` | `insertNoteFieldIndex` |+ | `queryNoteAxisPosting` | `queryNoteFieldIndex` |+ | `buildNoteAxisPosting` | `buildNoteFieldIndex` |+ | `toNoteAxisKeys` | `toNoteFieldKeys` |+ | `filterByAxis` | `filterByNoteField` |+ | `HasTermAxis` | `HasNotePeriod` |+ | `TermOf` | `PeriodOf` |+ | `termOf` | `periodOf` |+ | `projCapitalStock` | `projNonContraCreditEquity` |++- **English account names (0.7 output change).** Financial statements+ in English now show the equity row for `RetainedEarnings` as+ `Retained earnings brought forward`. For CSV rows that use an old English+ name to refer to one of these accounts, use the corresponding new name+ with `vocabularyNames` or use the constructor name.++ | Account | Old English name | New English name |+ | --- | --- | --- |+ | `AllowanceForBonuses` | Provision for bonuses | Allowance for bonuses |+ | `AllowanceForRepairs` | Provision for repairs | Allowance for repairs |+ | `AllowanceForProductWarranties` | Provision for warranties | Allowance for warranties |+ | `ReversalOfAllowanceForBonuses` | Reversal of provision for bonuses | Reversal of allowance for bonuses |+ | `ReversalOfAllowanceForRepairs` | Reversal of provision for repairs | Reversal of allowance for repairs |+ | `ReversalOfAllowanceForProductWarranties` | Reversal of provision for warranties | Reversal of allowance for warranties |+ | `SuppliesExpenses` | Supplies | Supplies expense |+ | `SuppliesOnHand` | Supplies | Supplies on hand |+ | `CentralBankPaymentExpense` | Central bank payment to treasury | Payment to national treasury |+ | `CentralBankPaymentIncome` | Central bank payment to treasury | Central bank payment received |+ | `RetainedEarnings` | Retained earnings | Retained earnings brought forward |+ | `Building` | Real estate | Buildings |++- `journalRows` and journal CSV output list each day's debit and credit+ terms in account-title order, then by hat base. The built-in chart uses+ the declaration order of `AccountTitles`. Earlier versions left the+ order within each side of a date unspecified.++- **Breaking (0.7).** The `Element` and `BaseClass` instances for `Day` and+ `TimeOfDay` are removed, along with the three built-in `ExBaseClass`+ instances that used either type directly. Use `Wild Day` and+ `Wild TimeOfDay` in bases. Wrap concrete dates and times in `Exactly`+ and use `Wild` where the old value meant a wildcard.+ For example, change `HatBase (AccountTitles, Day)` to+ `HatBase (AccountTitles, Wild Day)` and write `Not :< (Cash, Exactly d)`+ for a cash entry dated `d`. The date 1858-11-17 and midnight (00:00)+ are ordinary elements when wrapped in `Exactly`.++- The move of simulation into the separate `exchangealgebra-simulation`+ package, and the removal of the classic engine (`Simulate`,+ `Simulate.Engine`, `Simulate.Random`), `Simulate.Lite`, and+ `Simulate.Policy` without a compatibility module, are postponed from 0.7 to+ 0.8. Version 0.7 keeps the simulation modules of 0.6. The README section+ "Planned changes to simulation modules" and the module documentation are+ updated.++- **Consolidation worksheets (0.7 migration).** `validateConsolidationWorksheet`+ accepts trial balances and adjustments over a caller-defined account title+ type. The original worksheet type names specialize to `AccountTitles`+ and preserve the built-in chart's validation and results.+ - To import constructors and record fields, change `TrialBalanceSource(..)`,+ `WorksheetAdjustment(..)`, `WorksheetInput(..)`, and `WorksheetError(..)`+ to `TrialBalanceSourceOf(..)`, `WorksheetAdjustmentOf(..)`,+ `WorksheetInputOf(..)`, and `WorksheetErrorOf(..)`, respectively.+ `ValidatedWorksheetOf` exposes only its type name.+ - An expression such as+ `show [DuplicateSourceId (), EmptyAdjustment (), InvalidSourceValue () (1 :: Double)]`+ now leaves the title type ambiguous. Annotate the list with+ `:: [WorksheetError () () Double]` to select the built-in chart.+ - Supply a posting capability through `vocabSemantics` for each concrete+ title used in an adjustment. Validation rejects a title with missing+ semantics as `NotPostable`.+ - The `ExBaseClass` law now states that `whichSide` returns `Debit` or+ `Credit` for concrete titles under `Hat` or `Not`. Under `Not`, the+ base's `whatDiv` and `isContra` determine the home side. Under `Hat`,+ the side is reversed. The default implementation already follows this+ law. Worksheets total postings by the base's `whichSide`. Use the+ vocabulary's division and contra flag in the base instance to obtain+ totals consistent with that vocabulary.++- **Financial statements and presentation groups (0.7 migration).** Use+ `present` with a trial balance over your own account titles and+ `presentGroups` with a grouping for those titles. Supply `vocabSemantics`+ for each nonzero balance that the report must display. The default is+ `Nothing`. A statement-eligible title needs a statement division.+ - Start a context with `reportingContext framework scope profile` or+ `jcciSecondGradeContext scope`. When constructing `ReportingContext`+ directly, supply the new field `_labelOverrides` (use an empty map for+ no overrides). Omitting it can compile with a warning and fail when the+ field is read. Only `JcciSecondGradeReport` uses these labels.+ - Keep the original type names in annotations for `AccountTitles`.+ Import constructors and record fields through the corresponding+ `XOf(..)`, for example `StatementLineOf(..)`. A standalone expression+ such as `show (PresentGross :: MaterialityTreatment)` needs a title type+ annotation to resolve `Show`.+ - `Combined` eliminates the pairs in `vocabReciprocalPairs` (default+ `[]`). A wildcard endpoint, an endpoint without the `ReciprocalAccount`+ role, or a revenue or cost endpoint yields+ `ConflictingPresentationInstruction`. The built-in branch and head-office+ accounts satisfy these checks.+ - Each elimination records `ReciprocalPairEliminated left leftBalance right+ rightBalance`. The two-argument `ReciprocalAccountsEliminated` pattern+ still constructs and matches the built-in pair. Its `show` output now uses+ `ReciprocalPairEliminated BranchCurrentAccount ... HeadOfficeCurrentAccount ...`,+ including inside `FinancialStatements`. Statement amounts and ledger+ readouts retain their existing values.++- Account balances, accounting transfers, journal audits, period results from+ an algebra, and ledger and trial-balance rows now accept custom account+ titles. The four trial-balance audits accept a single account axis. A+ vocabulary can specify impossible balance sides, suspense accounts, and+ additional accounts that closing must clear. All three lists default to+ empty. The built-in chart retains its existing checks.+- **Breaking (0.7).** The constructors and record fields of+ `ImpossibleBalance`, `AbnormalBalance`, `TemporaryAccountBalance`,+ `ClosingResidual`, and `MetricError` now belong to the corresponding+ `*Of` types. The old type names still specialize to `AccountTitles`.+ Replace imports such as `ImpossibleBalance(..)` with both names when+ using the old type in an annotation.++ ```haskell+ import ExchangeAlgebra.Accounting.Audit (ImpossibleBalance, ImpossibleBalanceOf(..))+ import ExchangeAlgebra.Accounting.Statements.Metric (MetricError, MetricErrorOf(..))+ ```++ A constructor without a title argument needs a type when the context+ leaves the vocabulary open, for example+ `show (WildcardMetricAccount :: MetricError)`.++- **Breaking (0.7).** `AccountTitles` has a new constructor+ `DirectorsCompensations` (役員報酬, remuneration for directors and other+ officers), a cost account distinct from `WageExpenditure`. The Japanese name+ `役員報酬` resolves to it on import. A `case` on `AccountTitles` that lists+ every constructor without a wildcard pattern is no longer exhaustive; add a+ case for `DirectorsCompensations`. The wildcard `AccountTitle` keeps the last+ ordinal, so its `fromEnum` value increases by one. The `Binary` encoding+ writes a fixed code for each title, so the bytes for existing titles do not+ change.++- **Breaking.** `closingEntries` returns `Either (ClosingError v b) (Alg v b)`.+ Match a former transfer failure `Left e` as `Left (ClosingTransferError e)`.+ For example, change `Left (NonFiniteBalance b)` to+ `Left (ClosingTransferError (NonFiniteBalance b))` and add a case for+ `Left (InvalidClosingTarget title violation)`.+ `closingSide` now has type `AccountVocabulary t => t -> Maybe ClosingSide`.+ The base constraint on `closingEntries` and `settleEntries` changes from+ `StandardBase b` to `ExBaseClass b`. `closingEntries` still requires `HatVal v`.+ `SettleError` adds `InvalidSettleTarget title violation`, so a case that handles+ only `NonFiniteNet` is no longer exhaustive. Its `Eq` and `Show` instances also+ require `Eq (TitleOf b)` and `Show (TitleOf b)`, respectively, in addition to+ the existing constraints on `BasePart b`. Add those constraints to standalone+ deriving declarations for polymorphic wrappers around `SettleError b`.+ Include the new `ClosingTargetRejected title violation` case in exhaustive+ matches on `CatalogExecutionProblem`.++- **Breaking.** `ConvError`, `EntryError`, `JournalError`, and `JournalCert`+ are now type synonyms for the built-in chart. A former `T(..)` import leaves+ the constructors out of scope. Import the corresponding `TOf(..)` alongside+ the synonym, for example `import ExchangeAlgebra.IO.Input (ConvErrorOf(..), ConvError)`.+ `scientificAmount` now returns errors of type `ConvErrorOf acct`. When comparing+ or printing its result in isolation, specify the account type, for example+ `scientificAmount "10" :: Either ConvError Double`.++- **Breaking:** `ExBaseClass` has an associated type `TitleOf` (default `AccountTitles`), and+ `getAccountTitle`, `setAccountTitle`, `(.~)` and `projByAccountTitle` now use `TitleOf b`+ instead of `AccountTitles`. `ExBaseClass a` has the new superclass+ `AccountVocabulary (TitleOf a)`. Instances that do not set `TitleOf` keep the default and+ need no change. Code that names `AccountTitles` where the base type is polymorphic now needs+ the constraint `StandardBase b` (that is, `(ExBaseClass b, TitleOf b ~ AccountTitles)`); the+ functions that need the built-in chart (transfers, audit, trial balance, admission+ and the statement writers) now carry this constraint. GHC reports `-Worphans` for the+ generated `type instance TitleOf X = AccountTitles` next to an orphan `ExBaseClass` instance;+ this warning is expected. Behaviour is unchanged for `AccountTitles`.++- **Breaking:** `(.|)` is now `infix 5` (previously `infixr 2`), so it binds more+ tightly than `(.+)` (`infixr 3`), as in the mathematical notation where each term+ carries its note. Several journals can be added without parentheses, and a+ multi-term algebra needs parentheses before its note:++ ```haskell+ -- before+ (10 .@ Not :< Cash .| "a") .+ (20 .@ Hat :< Cash .| "b")+ 10 .@ Not :< Cash .+ 10 .@ Not :< Sales .| "sale"+ -- after+ 10 .@ Not :< Cash .| "a" .+ 20 .@ Hat :< Cash .| "b"+ (10 .@ Not :< Cash .+ 10 .@ Not :< Sales) .| "sale"+ ```++ An expression written for the old fixity that no longer parses as intended is a+ type error, so the compiler reports every place to change. Code that already+ parenthesized each `(alg .| note)` keeps working. `Show` for `Journal` follows the+ new fixity: `(a .+ b) .| "N" .+ c .| "M"`. Code examples published with earlier+ versions need parentheses around the algebra sum when built against this version.+- `(.*)` now has an explicit fixity, `infixr 7` (previously the default `infixl 9`).+ It still binds more tightly than `(.+)`, `(<>)` and `(.|)`. No operator of this+ library or of base with precedence 7 to 9 takes and returns an algebra, so an+ expression that compiled before keeps its meaning unless it mixes `(.*)` with such a+ user-defined operator without parentheses. `2 .* 3 .* x` now means `2 .* (3 .* x)` instead+ of a type error. `(.@)` is weaker, so `2 .* (10 .@ Not :< Cash)` still needs the+ parentheses.+- Change the license to MIT alone (previously MIT with Open World License conditions),+ and rename the license file from `LICENSE` to `LICENSE.txt`.+- Reduce allocation in `MoneyDouble` Binary encoding without changing its bytes.+- Build the Journal delta note-axis index only when an axis query needs it.+- Store one-sided singleton algebra pairs without a `Seq` node, preserving posting order,+ public APIs, and Binary encodings. `ExchangeAlgebra.Algebra.Internal` (outside the PVP+ contract) now exports the `HatOne`, `NotOne`, and `PairSeq` constructors of `Pair`; the+ `Pair hs ns` pattern and its field selectors remain.+- Addition now appends terms on the same base and side in input order.+ In an `Alg`, adding a singleton on the right with `(.+)` or using `fromList`+ can change `[3,1,2]` to `[1,2,3]`. `sigma` and `unionsMerge` change+ `[3,2,1]` to `[1,2,3]` for the same three singleton terms. Both+ associations of `(.+)` now agree under `Eq`. A `Journal` retains the+ addition order within each note even when other notes trigger compaction.+ `Journal.sigma` changes `[3,2,1]` to `[1,2,3]` for three singletons on+ one note. `toAlg` merges each note before traversing the merged note map.++ - `extendBy (.@)` on a term sequence `[1,2,3]` changes its output from+ `[3,1,2]` to `[1,2,3]`. `Journal.fromList` makes the same change+ when adding three singleton terms to one note. So does `Journal.sigmaM`+ when it combines `[1,2]` and `[3]` as algebras or on one note.+ - `sigma2When`, `sigmaFromMap`, `Journal.sigma2When`, `Journal.sigmaOn`,+ and `Journal.sigmaOnFromMap` change `[3,2,1]` to `[1,2,3]` when+ they visit three singleton terms in that order on one base and side+ and, for the journal functions, on one note.+ - Reading a note with `toMap` after `filterWithNote` changes+ `[3,1,2]` to `[1,2,3]` when its original layer holds `[1,2]` and+ its pending layer holds `[3]`. The same applies when `Journal.map`+ uses the identity function, `replaceNotes` retains that note, or+ `projWithNote`, `projWithBase`, `projWithNoteBase`, or+ `filterByNoteField` selects all three terms. Journal `(.^)` and+ `1 .*` carry the new order into their results.+ - `toAlg` and `gather` follow the merged note map's traversal order.+ If that traversal visits three notes holding same-base singletons+ `[1,2,3]` in one layer, the result changes from `[3,2,1]` to `[1,2,3]`.++ `Eq` and the encoded `Binary` bytes may change. `Show` displays sorted+ terms and can hide this difference. Previously encoded bytes still decode.+ The exact readouts `norm`, `bar`, `projNetNorm`, and closing give the+ same values for finite terms. `barWithin` sums each side in sequence order, so the last+ digit can change for `Double`. For example, with zero tolerance,+ `[2^53,1,1]` gives `2^53` and `[1,1,2^53]` gives `2^53+2`.++### Fixed++- Performance: Building the index on the first wildcard query against an `Alg`,+ such as with `proj` or `projNetNorm`, took quadratic time in the number of+ distinct bases because assigning each ID called the linear-time `IntMap.size`.+ A running counter now assigns the same IDs in the same order and preserves query results.+ Building an `Alg` with 100,000 distinct bases and running one wildcard query+ took 9.2 s before the fix and 0.10 s after it (10,000 bases: 92 ms and 6.5 ms).++- Performance: `kRegular` and `scaleFree` avoid scanning all candidates on each+ supplier draw. Both generators preserve the edges for a given seed and keys+ with lawful `Eq` and `Ord` instances. With 10,000 nodes, `kRegular` (k = 10)+ took 18 s before the fix and 67 ms after it, and `scaleFree` (m = 3) took+ 6.3 s and 21 ms (100,000 nodes after the fix: 1.27 s and 0.32 s).++- Performance: Wildcard queries in `proj` and `projNetNorm` called the+ linear-time `IntSet.size` on each candidate set of base IDs to order+ intersections, so each query took time proportional to the number of bases+ sharing a concrete element rather than to the matches. The index now supplies+ each set's size in constant time and preserves query results. Querying the+ inventory and gross profit of every company in one term of the+ `sparse-trade-model` benchmark (100,000 companies, 7.5 million postings) took+ 67.5 s before the fix and 5.4 s after it (10,000 companies: 0.79 s and+ 0.37 s). The `Liner` field `_axisPosting` in+ `ExchangeAlgebra.Algebra.Internal` (outside the PVP contract) now stores each+ ID set with its cardinality.++- Journal CSV readers, including the built-in readers, return `BadAmount` with the+ trimmed amount field when the amount parser returns a negative or non-finite value.+ Previously the row passed parsing and `(.@)` raised an exception during term construction.++- `Alg` equality now treats a one-term table returned by `bar`, `(.-)`,+ `(.*)`, or `filter` as equal to the same term built with `(.@)`.+ Ordering uses the same rule, so `compare` returns `EQ` exactly when+ `(==)` returns `True`. One-term tables now sort with singletons.+ The ordering among singletons and among members with multiple terms+ is unchanged. The `Binary` encoding is unchanged.++- `filterWithNote` now applies its predicate to the whole algebra for each+ note, as returned by `toMap`. Previously, a predicate that read the algebra+ could retain only some terms for a note stored in both journal layers.+ Predicates that read only the note produce the same results as before.++### Removed++- **Accounting and algebra compatibility modules.** Replace imports from+ the following modules. For `AccountTitles`, import+ `ExchangeAlgebra.Accounting.Account`. For `PeriodResult` and+ `AccountBalance` formerly supplied by the worksheet module, use+ `ExchangeAlgebra.Accounting.Statements.Metric` and+ `ExchangeAlgebra.Accounting.TrialBalance.Balance`.++ | Removed import | Replacement |+ | --- | --- |+ | `ExchangeAlgebra.Algebra.Base.Element` | `ExchangeAlgebra.Algebra.Element` |+ | `ExchangeAlgebra.Value` | `ExchangeAlgebra.Algebra.Value` |+ | `ExchangeAlgebra.Posting` | `ExchangeAlgebra.Algebra.Posting` |+ | `ExchangeAlgebra.Algebra.Base.Account.Types` | `ExchangeAlgebra.Accounting.Account` |+ | `ExchangeAlgebra.Algebra.Base.Account.Registry` | `ExchangeAlgebra.Accounting.Account` |+ | `ExchangeAlgebra.Algebra.Base.Account.JcciAliases` | `ExchangeAlgebra.Accounting.Account` |+ | `ExchangeAlgebra.Accounting.PostingPolicy` | `ExchangeAlgebra.Accounting.Account` |+ | `ExchangeAlgebra.Assist.Descriptions` | `ExchangeAlgebra.Accounting.Account` |+ | `ExchangeAlgebra.Bookkeeping` | `ExchangeAlgebra.Accounting.Entries` |+ | `ExchangeAlgebra.TrialBalance.Balance` | `ExchangeAlgebra.Accounting.TrialBalance.Balance` |+ | `ExchangeAlgebra.TrialBalance.Validation` | `ExchangeAlgebra.Accounting.TrialBalance.Validation` |+ | `ExchangeAlgebra.Reporting.Group` | `ExchangeAlgebra.Accounting.Statements.Group` |+ | `ExchangeAlgebra.Reporting.Metric` | `ExchangeAlgebra.Accounting.Statements.Metric` |+ | `ExchangeAlgebra.Reporting.Presentation` | `ExchangeAlgebra.Accounting.Statements.Presentation` |+ | `ExchangeAlgebra.Consolidation.Worksheet` | `ExchangeAlgebra.Accounting.Consolidation` |+ | `ExchangeAlgebra.Convert` | `ExchangeAlgebra.IO.Input` and `ExchangeAlgebra.Accounting.Account` for `concreteAccountTitles` |+ | `ExchangeAlgebra.Convert.Checked` | `ExchangeAlgebra.IO.Input.Checked` and `ExchangeAlgebra.Accounting.Account` for posting policy |+ | `ExchangeAlgebra.Convert.Csv` | `ExchangeAlgebra.IO.Input.Csv` |+ | `ExchangeAlgebra.Assist` | `ExchangeAlgebra.IO.Input.Assist` |+ | `ExchangeAlgebra.Render.Csv` | `ExchangeAlgebra.IO.Output.Csv` |+ | `ExchangeAlgebra.Render.Bookkeeping` | `ExchangeAlgebra.IO.Output.Statements` |+ | `ExchangeAlgebra.Algebra.Transfer.Rule` | `ExchangeAlgebra.Algebra.Transfer` for generic rules and `ExchangeAlgebra.Accounting.Closing` for closing and settlement |++- **Journal transfers.** Replace+ `ExchangeAlgebra.Journal.Transfer.Rule.transferEntries` with+ `ExchangeAlgebra.Accounting.Transfer.transferEntriesBy`, which computes+ transfers from exact balances grouped by destination note.+- **Communication expenses.** Replace `Commutation` with+ `CommunicationExpenses`. The account name `通信費` resolves to+ `CommunicationExpenses`. The removal lowers `fromEnum` by one for each+ account title declared after `Commutation`. The `Binary` codes of surviving+ titles keep their values, and the decoder rejects the retired code `0x8023`.+- **Transfer rules.** Replace `relabel` with `TransferRule from to Relabel`+ for generic base rules or `from .-> to |% Relabel` for an accounting+ transfer. Replace `MulBy`, `DivBy`, `scaleBy`, and `divideBy` with+ `mapPosting` for unit conversion or `Portion n d` for moving an equal+ share on both sides. Remove branches that match the `InvalidCoefficient`+ constructor of `TransferRuleError`. The remaining generic transfer+ operation has no coefficient.++- `TBFinding`, `trialBalanceFindings`, `TrialBalanceInput`, and+ `ReclassificationRule` of `ExchangeAlgebra.Accounting.TrialBalance.Validation`+ have been removed. Use `impossibleBalances`,+ `abnormalBalances`, `temporaryAccountBalances`, and `closingResiduals` of+ `ExchangeAlgebra.Accounting.Audit` instead. They take the trial balance+ directly and return `AuditResult`. Migrate each finding as follows.+ - `InvalidTrialBalanceValue`, `WildcardTrialBalanceAccount`,+ `WildcardTrialBalanceSide`: a structure issue, reported as `Error` by+ every audit.+ - `UnexplainedAbnormalBalance`: `impossibleBalances` or `abnormalBalances`.+ - `UnresolvedTemporaryBalance`: `temporaryAccountBalances`. Use+ `closingResiduals` to check `CashOverShort` after closing.+ - `ClosingDeviceResidual`, `DerivedCoordinateResidual`,+ `UnclosedNominalBalance`: `closingResiduals`.+ - The following have no successor among the audits.+ `UnbalancedTrialBalance`: `admit` rejects an unbalanced transaction, and+ `present` fails with `UnbalancedStatementInput`.+ `ReciprocalMismatch` and `StandaloneReciprocalBalance`: in the combined+ scope `present` eliminates the head-office and branch current accounts,+ records both balances in a `ReciprocalAccountsEliminated` audit event, and+ fails with `UnreconciledPresentation` when the statements do not+ reconcile. In the standalone scope no audit reports a balance in these+ accounts: the books of each office normally keep it after closing, and+ the pair cancels only in combined statements. To keep the old check, pass+ a trial balance that holds the books of both offices to `present` in the+ combined scope. `ExplainedTemporaryBalance` and `BlankTemporaryExplanation`:+ `temporaryAccountBalances` reports eligible balances as a `Warning`+ with no explanation field. `AbnormalBalanceWithReclassificationRule`,+ `AmbiguousReclassification`, and `InapplicableReclassificationRule`: a+ reclassification rule is an instruction for a correction, not an audit;+ `abnormalBalances` reports the balance and its documentation lists the+ legitimate exceptions. `MissingMaturityEvidence`: the maturity split is+ the presentation setting `_maturitySensitiveTitles` (since 0.6.0.0).++- The source distribution no longer contains+ `docs/admission-api-design-notes.md`, an internal design note. The behavior+ of `ExchangeAlgebra.IO.Input.Admission` is documented in its Haddock.++- The unused dependency on `numeric-prelude`. No module has imported it since the `NN.Double`+ instances were removed in 0.6.0.0. The public API is unchanged.+ ## 0.6.1.1 - 2026-11-20 ### Fixed
− LICENSE
@@ -1,39 +0,0 @@-Open World License--Copyright 2019 Kaya Akagi--We require the following additional license in addition to the MIT license.-We believe that open source software should contribute to promoting more openness-and more diversity of societies.-When you check yes of all the following checklist then you can use this software-under the MIT license. This Open World License should be included in this software.--(1) I love the diversity of societies.-(2) I hate dictatorship. -(3) I love the openness of societies.-(4) I can access the Internet freely in a place where this software is used.-(5) The customer can access the Internet freely in the place where the- application system, that is developed by this software, will be used.---MIT License--Copyright (c) 2019 Kaya Akagi--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.
+ LICENSE.txt view
@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2019 Kaya Akagi++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.
README.md view
@@ -2,7 +2,7 @@ `exchangealgebra` is a Haskell library for [Exchange Algebra](https://www.springer.com/gp/book/9784431209850), an algebraic description of bookkeeping systems developed by Hiroshi Deguchi. It treats bookkeeping entries-as elements of a scaled basis algebra, so journaling, closing, transfer, and simulation can be written as+as members of a redundant algebra, so journaling, closing, transfer, and simulation can be written as function composition and projection. The library is used in the preprint@@ -13,6 +13,7 @@ - Book: <https://www.springer.com/gp/book/9784431209850> - Paper: <https://repository.kulib.kyoto-u.ac.jp/dspace/bitstream/2433/82987/1/0809-7.pdf> - Haddock: <https://hackage.haskell.org/package/exchangealgebra>+- Manual (English and Japanese): <https://yakagika.github.io/ExchangeAlgebra/> ## Installation @@ -21,7 +22,7 @@ ```yaml # stack.yaml extra-deps:- - exchangealgebra-0.6.1.0+ - exchangealgebra-0.6.1.1 ``` ```yaml@@ -105,19 +106,18 @@ balances and findings, financial-statement presentation, CSV and bookkeeping output, and value types. - `ExchangeAlgebra.Accounting` — re-exports the- Definitions 7-9 accounting basis, exchange decomposition, and transfer core.+ Definitions 7-9 accounting bases, exchange decomposition, and transfer core. ### Account vocabulary -These modules define basis elements and the canonical account metadata vocabulary.+These modules define element types for bases and the canonical account metadata vocabulary. - `ExchangeAlgebra.Accounting.Account` — defines account titles, classifications, registry metadata, posting eligibility, and PIMO direction helpers. - `ExchangeAlgebra.Accounting.Exchange` — defines `ExBaseClass`, `AccountBase`, `Exchange`, debit/credit decomposition, balance checks, and account projections.-- `ExchangeAlgebra.Algebra.Element` — defines generic wildcard-aware basis components.-- `ExchangeAlgebra.Algebra.Base` — defines generic basis classes, Hat/Not bases,- and basis display helpers.+- `ExchangeAlgebra.Algebra.Element` — defines element types with wildcard matching.+- `ExchangeAlgebra.Algebra.Base` — defines base classes, hat bases, and display helpers for bases. ### Core algebra @@ -164,70 +164,6 @@ - `ExchangeAlgebra.Journal.Transfer` — carries entries across notes and reads side totals. Use `Accounting.Transfer.transferEntriesBy` for accounting transfers. -### Simulation: `Simulation.*` and `Simulate.*`--Simulation code lives under two module prefixes with different futures.--- `ExchangeAlgebra.Simulation.*` holds components that a model uses besides- the runner: trade networks, matrix analysis, optimization, and CSV output of- results. These modules are kept after 0.6.-- `ExchangeAlgebra.Simulate.*` holds the simulation runners and their support:- the classic state-space engine, the Lite front-end, ledger policies, spill- files, random helpers, and Chart plotting.--Components (`Simulation.*`):--- `ExchangeAlgebra.Simulation.Network` — separates sparse trade-network topology from input coefficients;- `.Flows`, `.Csv`, and `.Journal` generate industrial flows, read network CSV- files, and sum flows into a `Journal`.-- `ExchangeAlgebra.Simulation.Analysis` — computes a Leontief inverse and ripple effects.-- `ExchangeAlgebra.Simulation.Output` — writes simulation results as CSV- without Chart. `writeFuncResults` and `writeFuncResultsWithContext` take the- classic engine's `StateTime`.-- `ExchangeAlgebra.Simulation.Optimize` — see **Optimization** below.--Runners (`Simulate.*`):--- `ExchangeAlgebra.Simulate` — provides the classic state-space engine, spill support, and scenario execution, and re-exports the ripple utilities.-- `ExchangeAlgebra.Simulate.Engine` — re-exports the- classic state-space protocol and runners without spill configuration or- analysis helpers.-- `ExchangeAlgebra.Simulate.Lite` — provides the product-HKD, BSP front-end with declarative field rules and stages.-- `ExchangeAlgebra.Simulate.Policy` — declares retention, spill, and compaction policy for long simulations.-- `ExchangeAlgebra.Simulate.Spill` — provides spill chunk writers, checked readers, and ledger restoration shared by simulation and reporting layers.-- `ExchangeAlgebra.Simulate.Random` — re-exports- simulation random-number helpers.-- `ExchangeAlgebra.Simulate.Visualize` — renders simulation grids and time series with Chart/Cairo.--### Planned changes to simulation modules--The next major version (0.7) is planned to move simulation into a separate-package, `exchangealgebra-simulation`, whose runner is a new model evaluator.-The plan affects the 0.6 modules as follows:--- `Simulation.*` and `Simulate.Spill` move to the new package. The writers- that take `StateTime` (`writeFuncResults`, `writeFuncResultsWithContext`)- are redesigned for the evaluator or removed.-- The classic engine (`Simulate`, `Simulate.Engine`, `Simulate.Random`),- `Simulate.Lite`, and `Simulate.Policy` are removed and not moved. Their- successor is the model evaluator.-- `Simulate.Visualize` either moves to the new package behind Chart or is- removed; the choice is made in 0.7.--The 0.6 modules do not emit deprecation warnings, because the successor package-has not been released. Changes to this plan will be recorded in the changelog.--### Which simulation runner to use in 0.6--`ExchangeAlgebra.Simulate.Lite` provides `Generic`-derived world records,-term-boundary field rules, stages, and `runLite` / `runLiteWithPolicy`.-`ExchangeAlgebra.Simulate.Engine` is the lower-level classic state-space API-(`StateTime`, `Updatable`, `UpdatePattern`, and the `runSimulation` family),-retained for existing models and reproducibility. Both runners are planned for-removal in 0.7 (see above). For a new model built on 0.6, Lite needs less code;-keep model logic separate from runner code so that it can be moved to the-successor evaluator.- ### Bookkeeping and reporting These modules build adjustments, validate reporting boundaries, and produce statements and output.@@ -280,11 +216,11 @@ | Distinct money type | ✗ — a bare numeric type | ✓ — can't be silently mixed with coefficients / draws | ✓ | | Decimal prices / ratios | approximate | approximate | **exact** | | Tax / proration (`*`, `/`) | rounding noise | rounding noise | exact intermediates; round explicitly with `bankersRound` / `ceilingRound` |-| Construction-order independence | ✗ — addition is non-associative, so the order same-base terms are summed shifts the last-ULP of `norm` / `bar` | ✗ — identical to `Double` | ✓ — addition is exact & associative, so `norm` / `bar` / balance are identical regardless of build order |-| Determinism / auditability | not bit-reproducible across reorderings | not bit-reproducible | bit-reproducible |+| Construction-order independence | ✓ for `norm` / `bar` / balance on finite terms, which work from exact sums (`norm` and `bar` round once; balance compares the exact sums); ✗ for the sequential sums of `barWithin` / `balanceWithin` / `diffRLWithin`, whose last digit can shift with the order same-base terms were added | identical to `Double` | ✓ — addition is exact & associative, so every readout, including the sequential sums, is identical regardless of build order |+| Determinism / auditability | `norm` / `bar` / balance are bit-reproducible across reorderings; the sequential sums are not | identical to `Double` | bit-reproducible | | Memory per value | ~16 B | ~16 B (zero-cost wrapper) | ~40 B + indirection (~2.5×) | | Speed | fastest | fastest (= `Double`) | slower (boxed `Integer` mantissa arithmetic) |-| Typical use | numeric methods (Leontief inverse, optimization), quick ABM | ABM where you want a *typed* money value distinct from raw `Double` | audited ledgers, bookkeeping, anywhere a total must be reproducible |+| Typical use | numeric methods (Leontief inverse, optimization), quick ABM | ABM where you want a *typed* money value distinct from raw `Double` | audited ledgers, bookkeeping, anywhere a total must match decimal arithmetic exactly | ```haskell import ExchangeAlgebra@@ -325,77 +261,15 @@ on top. For very large simulations weigh exactness against that overhead — or use the spill-to-disk path (below) to keep memory constant. -**`fromList` ordering contract.** `EJ.fromList` is a strict `O(N)` left fold. It-preserves the *multiset* of terms exactly. When two terms share the-same note **and** base, they land in one ordered sequence; that sequence's order is-observable through `Eq` / `Show` / `toAlg` / `Binary`, and for `Double` through the-last-ULP of `norm` / `bar`. For `MoneyDecimal` the order never affects-`norm` / `bar` / balance. (`Integer` is intentionally not offered — it cannot-represent the fractional relative prices the ABM work depends on.)--### Migrating to 0.6.0.0--`0.6.0.0` is a major (breaking) release. Update imports, transfer composition,-value instances, and plotting configuration as described here. See the-[changelog](https://hackage.haskell.org/package/exchangealgebra/changelog) for the full per-name migration tables.--- **Transfers add entries.** Transfer and closing functions return additional- entries without rewriting the original terms. Add the returned entries- with `(.+)`. `ExchangeAlgebra.Algebra.Transfer` and- `ExchangeAlgebra.Journal.Transfer` replace their contents under the same- module names; see **Removed** in the changelog.-- **Root exports are explicit.** `ExchangeAlgebra` has an explicit export- list. Import names such as `writeTermIO` from their owning modules; see- **Breaking changes without a compatibility shim** in the changelog.-- **Accounting names moved.** `ExchangeAlgebra.Algebra`,- `ExchangeAlgebra.Algebra.Base`, `ExchangeAlgebra.Algebra.Internal`, and- `ExchangeAlgebra.Journal` no longer re-export accounting names. Import their- accounting owners, or use `import ExchangeAlgebra`, which still provides- all these accounting names.-- **Module moves.** Deprecated compatibility modules remain in 0.6 and are- removed in 0.7.0.0. See **Deprecated** in the changelog for the new paths.-- **Exact variants are merged.** The `*Exact` functions and- `ExchangeAlgebra.Algebra.Exact` and `ExchangeAlgebra.Journal.Exact` modules- are removed. Ordinary functions provide the same readouts; for example,- replace `normExact` with `norm`, which returns the value directly.-- **Text instead of String.** Public API fields carrying human-readable text- now use `Text`. Enable `OverloadedStrings` or pass text with `Data.Text.pack`;- see the changelog for the affected fields and the exceptions.-- **Plotting is opt-in.** The `visualize` flag is off by default. Enable it to- use `ExchangeAlgebra.Simulate.Visualize` as described in **Installation**.-- **Custom `HatVal` instances.** Implement `valueError`, `Accum`, all eight- accumulator methods, and `roundRational`. Missing methods fail at run time.- See the **Custom `HatVal` instances implement** item in the changelog for- the signatures, helper functions, and laws.--### Migrating to 0.5.0.0--`0.5.0.0` is a major (breaking) release. Most users need no changes — `Double`-ledgers keep working and render identically. Four things to know:--- **Custom `HatVal` instances**: `HatVal` dropped its `RealFloat` superclass and- added `showValue :: n -> String`. If you defined your own `HatVal` instance, add- a `showValue` (how the value prints inside `Alg`'s `Show`). If you relied on- `HatVal n => RealFloat n` in a signature, add the `RealFloat` constraint- explicitly. The built-in `Double` / `NN.Double` instances are unchanged.-- **`fromList` accumulation order**: now a strict left fold. The multiset is- preserved, but if you compared `Show` / `Eq` / serialized output of a- `fromList`-built journal byte-for-byte, the same-(note,base) sequence order may- differ. Switch such ledgers to `MoneyDecimal` for order-independent results, or- compare via `norm` / `bar` / `balanceBy` rather than raw structure.-- **Abstract `Alg` / `Journal`**: pattern-match `Alg` on `Zero`- and `(:@)` only and build values with `(.@)`, `(.+)`, `fromList`, `mkJournal`,- and `(.|)`. Code that constructed `Liner` directly must import- `ExchangeAlgebra.Algebra.Internal` (the exposed `Alg` representation module,- which carries no stability guarantee). Rebuild journals with `mkJournal`,- `(.|)`, or `fromList`.-- **Spill files are validated**: `readBinarySpillFile` and- `restoreJournalFromBinarySpill` now raise on a truncated, stale or gapped- file instead of merging a partial ledger; use the `...Checked` variants for an- `Either`. `Simulate.Lite` truncates its spill file when a run opens it.--(`0.5.0.0` also includes the `union` zero-base correctness fix first shipped in-`0.4.1.1`; see the changelog.)+**`fromList` ordering contract.** `EJ.fromList` is a strict `O(N)` left fold. When+two terms share the same note **and** base, they land in one sequence in input+order. `Eq` on the results of `toMap` and `toAlg`, `Binary`, and the sequential sums+of `barWithin`, `balanceWithin`, and `diffRLWithin` observe that order; `Show`+displays sorted terms. For finite terms,+`norm`, `bar`, and balance do not depend on the order for any value type. For+`MoneyDecimal`, the sequential sums do not depend on it either. (`Integer` is+intentionally not offered — it cannot represent the fractional relative prices the+ABM work depends on.) ## Recommended import patterns @@ -453,8 +327,100 @@ import qualified ExchangeAlgebra.Simulate.Lite as Lite ``` -## Large-scale simulations (constant memory)+## Examples +Runnable usage examples are collected in the `examples/` sub-package on GitHub.+See the [examples directory](https://github.com/yakagika/ExchangeAlgebra/tree/master/examples)+and its [README](https://github.com/yakagika/ExchangeAlgebra/blob/master/examples/README.md) for details.++```bash+stack build+stack exec -- ebex1 # Introductory bookkeeping example+stack exec -- fixed-price-io # 100-term simulation (+ Python visualization)+stack exec -- fixed-price-io-spill # spill-to-disk simulation (constant memory, binary spill + restore)+```++The repository also keeps short executable samples under `test/api-samples/`; CI compiles and+runs each of them and checks their hand-computed results. Two of them show the core accounting+features in a few dozen lines:++- `test/api-samples/Consolidation.hs`: a consolidation worksheet for a parent and its wholly+ owned subsidiary, with the investment-capital and intercompany-sale eliminations.+- `test/api-samples/InvoiceJournal.hs`: a buyer's journal entry from a Japanese qualified invoice+ with 10% and 8% tax-rate summaries.++## Simulation++The core accounting layers above do not depend on the simulation modules. This section+describes the simulation entry points, their planned move in 0.8, and how to run large simulations.++### Simulation: `Simulation.*` and `Simulate.*`++Simulation code lives under two module prefixes with different futures.++- `ExchangeAlgebra.Simulation.*` holds components that a model uses besides+ the runner: trade networks, matrix analysis, optimization, and CSV output of+ results. These modules are kept after 0.6.+- `ExchangeAlgebra.Simulate.*` holds the simulation runners and their support:+ the classic state-space engine, the Lite front-end, ledger policies, spill+ files, random helpers, and Chart plotting.++Components (`Simulation.*`):++- `ExchangeAlgebra.Simulation.Network` — separates sparse trade-network topology from input coefficients;+ `.Flows`, `.Csv`, and `.Journal` generate industrial flows, read network CSV+ files, and sum flows into a `Journal`.+- `ExchangeAlgebra.Simulation.Analysis` — computes a Leontief inverse and ripple effects.+- `ExchangeAlgebra.Simulation.Output` — writes simulation results as CSV+ without Chart. `writeFuncResults` and `writeFuncResultsWithContext` take the+ classic engine's `StateTime`.+- `ExchangeAlgebra.Simulation.Optimize` — see **Optimization** below.++Runners (`Simulate.*`):++- `ExchangeAlgebra.Simulate` — provides the classic state-space engine, spill support, and scenario execution, and re-exports the ripple utilities.+- `ExchangeAlgebra.Simulate.Engine` — re-exports the+ classic state-space protocol and runners without spill configuration or+ analysis helpers.+- `ExchangeAlgebra.Simulate.Lite` — provides the product-HKD, BSP front-end with declarative field rules and stages.+- `ExchangeAlgebra.Simulate.Policy` — declares retention, spill, and compaction policy for long simulations.+- `ExchangeAlgebra.Simulate.Spill` — provides spill chunk writers, checked readers, and ledger restoration shared by simulation and reporting layers.+- `ExchangeAlgebra.Simulate.Random` — re-exports+ simulation random-number helpers.+- `ExchangeAlgebra.Simulate.Visualize` — renders simulation grids and time series with Chart/Cairo.++### Planned changes to simulation modules++Version 0.8 is planned to move simulation into a separate+package, `exchangealgebra-simulation`, whose runner is a new model evaluator.+The move was planned for 0.7 until November 2026; 0.7 keeps the simulation+modules of 0.6. The plan affects these modules as follows:++- `Simulation.*` and `Simulate.Spill` move to the new package. The writers+ that take `StateTime` (`writeFuncResults`, `writeFuncResultsWithContext`)+ are redesigned for the evaluator or removed.+- The classic engine (`Simulate`, `Simulate.Engine`, `Simulate.Random`),+ `Simulate.Lite`, and `Simulate.Policy` are removed and not moved. Their+ successor is the model evaluator.+- `Simulate.Visualize` either moves to the new package behind Chart or is+ removed; the choice is made in 0.8.++The simulation modules do not emit deprecation warnings in 0.6 or 0.7, because+the successor package has not been released. Changes to this plan will be recorded in the changelog.++### Which simulation runner to use in 0.6++`ExchangeAlgebra.Simulate.Lite` provides `Generic`-derived world records,+term-boundary field rules, stages, and `runLite` / `runLiteWithPolicy`.+`ExchangeAlgebra.Simulate.Engine` is the lower-level classic state-space API+(`StateTime`, `Updatable`, `UpdatePattern`, and the `runSimulation` family),+retained for existing models and reproducibility. Both runners are planned for+removal in 0.8 (see above). For a new model built on 0.6, Lite needs less code;+keep model logic separate from runner code so that it can be moved to the+successor evaluator.++### Large-scale simulations (constant memory)+ For new Lite simulations, set `spillTo` in a `LedgerPolicy` and run with `runLiteWithPolicy`. `runSimulation` keeps the entire world state in memory for the whole run, so peak memory@@ -497,13 +463,13 @@ A runnable end-to-end example (multi-scenario run with binary spill, `KeepRecentTerms`, and restore) is `examples/basic/fixedPriceIOSpill.hs` (the `fixed-price-io-spill` executable). -## A note on visualization+### A note on visualization `ExchangeAlgebra.Simulate.Visualize` provides Chart-based PNG rendering, but **we recommend writing CSV output and visualizing it from a separate Python script** for production-quality plotting. -### Why+#### Why - Chart / Chart-cairo transitively pull in cairo / pango / freetype system libraries, which makes the build environment heavier to set up.@@ -511,7 +477,7 @@ - Using CSV as an intermediate format cleanly separates "compute" from "plot". - The same CSVs can be reused with R / Julia / Excel if you need them. -### Recommended workflow+#### Recommended workflow ```haskell -- Haskell side: write the simulation outputs to CSV@@ -544,33 +510,132 @@ Concrete runnable examples of this pattern live under the `examples/` sub-package (see [the examples directory on GitHub](https://github.com/yakagika/ExchangeAlgebra/tree/master/examples)). -### If you still want to plot from Haskell+#### If you still want to plot from Haskell If keeping everything in Haskell is important to your workflow, `plotLineVector`, `plotMultiLines`, and `plotWldsDiffLine` in `ExchangeAlgebra.Simulate.Visualize` write PNGs directly and work without any Python setup. -## Examples+## Migrating between major versions -Runnable usage examples are collected in the `examples/` sub-package on GitHub.-See the [examples directory](https://github.com/yakagika/ExchangeAlgebra/tree/master/examples)-and its [README](https://github.com/yakagika/ExchangeAlgebra/blob/master/examples/README.md) for details.+### Migrating to 0.7.0.0 -```bash-stack build-stack exec -- ebex1 # Introductory bookkeeping example-stack exec -- fixed-price-io # 100-term simulation (+ Python visualization)-stack exec -- fixed-price-io-spill # spill-to-disk simulation (constant memory, binary spill + restore)-```+`0.7.0.0` is a major (breaking) release. It lets closing, audits, financial+statements, and consolidation worksheets take your own account title type.+Update renamed names, error-type imports, and exhaustive matches as described+here. See the+[changelog](https://hackage.haskell.org/package/exchangealgebra/changelog) for+the full per-name migration tables. +- **Renamed names.** `AxisKey` becomes `ElementKey`, `filterByAxis` becomes+ `filterByNoteField`, `HasTermAxis` and `termOf` become `HasNotePeriod` and+ `periodOf`, and `projCapitalStock` becomes `projNonContraCreditEquity`. The+ changelog lists all 16 renamed names.+- **Account title types.** `ExBaseClass` has an associated type `TitleOf`+ (default `AccountTitles`). Instances that keep the default need no change.+ Error, audit, worksheet, and statement types have `*Of` versions over the+ title type. Import constructors through the `*Of(..)` name next to the old+ type name, for example `import ExchangeAlgebra.IO.Input (ConvErrorOf(..), ConvError)`.+- **Closing errors.** `closingEntries` returns `Either (ClosingError v b) (Alg v b)`.+ Match a transfer failure as `Left (ClosingTransferError e)` and add a case+ for `Left (InvalidClosingTarget title violation)`.+- **Note operator.** `(.|)` is `infix 5` and binds more tightly than `(.+)`.+ Put parentheses around an algebra sum before its note, as in+ `(10 .@ Not :< Cash .+ 10 .@ Not :< Sales) .| "sale"`. An expression written+ for the old fixity that no longer parses as intended is a type error.+- **Dates in bases.** Replace `Day` with `Wild Day` in base types and write a+ concrete date as `Exactly d`.+- **Account titles.** Exhaustive `case` expressions on `AccountTitles` need a+ case for the new `DirectorsCompensations`. Replace `Commutation` with+ `CommunicationExpenses`.+- **Removed modules and audits.** The deprecated accounting and algebra+ compatibility modules are removed; the changelog maps each to its+ replacement. Replace `trialBalanceFindings` with the audits in+ `ExchangeAlgebra.Accounting.Audit`.+- **Output changes.** Twelve English account names change, for example+ `Retained earnings` becomes `Retained earnings brought forward`. Addition+ keeps terms on the same base in input order, so `Eq` and the `Binary` bytes+ can differ from 0.6. `norm`, `bar`, and closing return the same values for+ finite terms.++The simulation modules of 0.6 are unchanged in 0.7; see+[Planned changes to simulation modules](#planned-changes-to-simulation-modules).++### Migrating to 0.6.0.0++`0.6.0.0` is a major (breaking) release. Update imports, transfer composition,+value instances, and plotting configuration as described here. See the+[changelog](https://hackage.haskell.org/package/exchangealgebra/changelog) for the full per-name migration tables.++- **Transfers add entries.** Transfer and closing functions return additional+ entries without rewriting the original terms. Add the returned entries+ with `(.+)`. `ExchangeAlgebra.Algebra.Transfer` and+ `ExchangeAlgebra.Journal.Transfer` replace their contents under the same+ module names; see **Removed** in the changelog.+- **Root exports are explicit.** `ExchangeAlgebra` has an explicit export+ list. Import names such as `writeTermIO` from their owning modules; see+ **Breaking changes without a compatibility shim** in the changelog.+- **Accounting names moved.** `ExchangeAlgebra.Algebra`,+ `ExchangeAlgebra.Algebra.Base`, `ExchangeAlgebra.Algebra.Internal`, and+ `ExchangeAlgebra.Journal` no longer re-export accounting names. Import their+ accounting owners, or use `import ExchangeAlgebra`, which still provides+ all these accounting names.+- **Module moves.** Version 0.7.0.0 removes the deprecated accounting and+ algebra compatibility modules. See [Removed in the changelog](ChangeLog.md#removed)+ for replacement imports. The five deprecated simulation compatibility+ modules remain until simulation moves to a separate package in 0.8.0.0.+- **Exact variants are merged.** The `*Exact` functions and+ `ExchangeAlgebra.Algebra.Exact` and `ExchangeAlgebra.Journal.Exact` modules+ are removed. Ordinary functions provide the same readouts; for example,+ replace `normExact` with `norm`, which returns the value directly.+- **Text instead of String.** Public API fields carrying human-readable text+ now use `Text`. Enable `OverloadedStrings` or pass text with `Data.Text.pack`;+ see the changelog for the affected fields and the exceptions.+- **Plotting is opt-in.** The `visualize` flag is off by default. Enable it to+ use `ExchangeAlgebra.Simulate.Visualize` as described in **Installation**.+- **Custom `HatVal` instances.** Implement `valueError`, `Accum`, all eight+ accumulator methods, and `roundRational`. Missing methods fail at run time.+ See the **Custom `HatVal` instances implement** item in the changelog for+ the signatures, helper functions, and laws.++### Migrating to 0.5.0.0++`0.5.0.0` is a major (breaking) release. Most users need no changes — `Double`+ledgers keep working and render identically. Four things to know:++- **Custom `HatVal` instances**: `HatVal` dropped its `RealFloat` superclass and+ added `showValue :: n -> String`. If you defined your own `HatVal` instance, add+ a `showValue` (how the value prints inside `Alg`'s `Show`). If you relied on+ `HatVal n => RealFloat n` in a signature, add the `RealFloat` constraint+ explicitly. The built-in `Double` / `NN.Double` instances are unchanged.+- **`fromList` accumulation order**: now a strict left fold. The multiset is+ preserved, but if you compared `Show` / `Eq` / serialized output of a+ `fromList`-built journal byte-for-byte, the same-(note,base) sequence order may+ differ. Switch such ledgers to `MoneyDecimal` for order-independent results, or+ compare via `norm` / `bar` / `balanceBy` rather than raw structure.+- **Abstract `Alg` / `Journal`**: pattern-match `Alg` on `Zero`+ and `(:@)` only and build values with `(.@)`, `(.+)`, `fromList`, `mkJournal`,+ and `(.|)`. Code that constructed `Liner` directly must import+ `ExchangeAlgebra.Algebra.Internal` (the exposed `Alg` representation module,+ which carries no stability guarantee). Rebuild journals with `mkJournal`,+ `(.|)`, or `fromList`.+- **Spill files are validated**: `readBinarySpillFile` and+ `restoreJournalFromBinarySpill` now raise on a truncated, stale or gapped+ file instead of merging a partial ledger; use the `...Checked` variants for an+ `Either`. `Simulate.Lite` truncates its spill file when a run opens it.++(`0.5.0.0` also includes the `union` zero-base correctness fix first shipped in+`0.4.1.1`; see the changelog.)+ ## Documentation - Haddock: <https://hackage.haskell.org/package/exchangealgebra>-- A tutorial / guided walkthrough is planned, based on an upcoming paper.+- Manual (English and Japanese): <https://yakagika.github.io/ExchangeAlgebra/>. It records a journal entry in exchange algebra+ step by step and covers the Algebra, Journal, Accounting, and IO layers of the Hackage release named in its title. ## License -Dual licensed under MIT and the Open World License (OWL). See `LICENSE` for details.+Licensed under the MIT license. See [LICENSE.txt](LICENSE.txt) for the full text. ## Publications using this library @@ -597,9 +662,9 @@ DOI: [10.1002/sres.3850030105](https://doi.org/10.1002/sres.3850030105) The axiomatic origin of Exchange Algebra. This paper formalizes double-entry- bookkeeping as an accounting vector space over the extended basis- `Γ = Λ ∪ Λ̂` (account titles and their dual hats), introduces the five- transaction axioms, and derives the debit/credit partition and the balance+ bookkeeping as an accounting vector space over `Γ = Λ ∪ Λ̂` (account titles+ and their dual hats). It introduces the five transaction axioms and derives+ the debit/credit partition and the balance principle (`|y_L| = |y_R|`) purely algebraically. - Hiroshi Deguchi. *Economics as an Agent-Based Complex System:
− docs/admission-api-design-notes.md
@@ -1,163 +0,0 @@-# 受入 API の設計ノート--この文書は `ExchangeAlgebra.IO.Input.Admission` の実装判断を記録する開発者向けの設計ノートである.-受入は, 信頼できない書き手 (言語モデルなど) が書いた仕訳帳について, 会計的な整合性を取引ごとに確かめる.-仕訳の経済的な意味, 勘定の選び方の適否, 演習の正解との一致は確かめない.--## 範囲--受入が持つのは次の 2 つだけである.--| 関数 | 問い | 結果 |-|---|---|---|-| `admit` | 仕訳帳の各取引 (note) が, それ単独で会計的に整合しているか | `Either (AdmissionFailure n b) (Admitted n b)` |-| `checkEvidence` | 受入済みの仕訳帳が, 信頼側の記録 (証憑) と一致するか | `Either (NonEmpty (EvidenceMismatch m b)) ()` |--受入は仕訳を作らない. 決算整理と締めの仕訳は, 書き手が会計の関数-(`ExchangeAlgebra.Accounting.Adjustment`, `closingEntries` など) で計算して仕訳帳に含める.-期首の残高のように信頼側が与える事実も仕訳帳に含めて渡し, 信頼側の記録との一致を `checkEvidence` で確かめる.-試算表と諸表は, 受入の後に `admittedJournal` から既存の関数-(`Presentation.present`, `ExchangeAlgebra.IO.Output.Statements` の CSV 出力) で作る.-会計的な所見 (逆残高, 仮勘定の残りなど) は `trialBalanceFindings` が返し, 帳票の作成は所見で止まらない.--使ってよい勘定の一覧, 特定の勘定への直接の記帳の禁止, 損益と純資産の間の振替の禁止のような規則は,-実験や道具の側の規則であり library には置かない. 例えば売上を利益剰余金へ直接振り替える提出も受け入れられ,-それを見つけるのは正解との照合である.--## 型--`admit` は note `n` と基底 `b` について多相で, 値は `MoneyDecimal` に固定する.--```haskell-admit :: (Note n, ExBaseClass b)- => Journal n MoneyDecimal b- -> Either (AdmissionFailure n b) (Admitted n b)-```--値を固定するのは, 金額の厳密な和と, 証憑との値の等号比較を, 有限の 10 進数で行うためである.-`TxKey = TxKey EntityId PeriodId TxId` は既定の note の型で, 会社・期間・取引を分ける.-他の `Note` の型も使える.--`Admitted` と `AdmissionFailure` の構築子は非公開で, `admit` だけが作る.-`Admitted` は「取引ごとの整合性を確かめた仕訳帳」であることを型で表す印で,-`checkEvidence` と利用者の関数が引数の型で検査済みを要求できるようにする.-中身は `admittedJournal` で取り出し, 既存の関数にそのまま渡せる. 印のほかに機構は持たない.-どちらの型にも, 中身から値を作り直す instance (`Generic`, `Read`, `Binary` など) を実装しない.-保証は `unsafeCoerce` と内部 module を使わないことを前提とする. EA の module は Safe Haskell ではない.--## admit の検査--各 note の各 posting について次を確かめる.--| 検査 | 違反 | 理由 |-|---|---|---|-| 値が正 | `NonPositiveAmount n b v` | posting の値は非負で, 0 の項は台帳に置かない |-| 側が `Hat` か `Not` | `WildcardSide n b` | 台帳の項の Hat / Not は借方か貸方かを決める値である. wildcard の `HatNot` は問い合わせにだけ使う |-| 勘定が記帳できる | `NotPostableAccount n b` | どの処理でも記帳できない勘定 (wildcard の `AccountTitle`) を拒む |--さらに, `WildcardSide` と `NotPostableAccount` の無い note について, 借方の合計と貸方の合計が厳密に等しいことを確かめる-(`Imbalanced n debit credit`). 借方・貸方は `decL` (Debit) と `decR` (Credit) で決め, Hat / Not の符号では決めない.-現金売上 `100 .@ Not :< Cash .+ 100 .@ Not :< Sales` は, 借方が Cash, 貸方が Sales で釣り合う.-和は厳密に累算し, 報告する値だけを 1 回丸める.-`HatNot` の項に `decL` を掛けると例外になり, wildcard の勘定の区分を問うても例外になるので,-これらを含む note では貸借を比べない.--`(.@)` は `HatNot` と負の値と有限でない値を拒むので, 公開 API で作った仕訳帳では値と側の検査は通常は落ちない.-それでも検査を残すのは, 費用が小さく, 内部の構築子で作った値も同じ型で届くからである.--違反は全部集めて返し, 最初の 1 件で止めない. 並びは note の昇順, note の中は posting の基底の昇順で,-`Imbalanced` はその note の最後に置く. 成功したときは仕訳帳を変えずに `Admitted` に入れる.-note を足しも消しもせず, 同じ基底の項をまとめず, `bar` を掛けない.--検査しないもの:--- 取引の key の重複. 同じ note の元を足すと仕訳帳の中で 1 つの元にまとまるので, 仕訳帳には重複を区別する情報が残らない.- 重複は仕訳帳を作る前の変換 (JSON の読み込みなど) で確かめる. 既存の `checkedJournalIn` も仕訳帳を作る前に `DuplicateTxId` を検出する.-- 空の取引. 仕訳帳の正規形は値 0 の note を持たない.-- 処理によって変わる記帳の権限 (締めでだけ記帳できる勘定など). 受入は処理を知らない.-- 取引をまたぐ残高, 締めの有無, 証憑との一致 (`checkEvidence` で確かめる), 正解との一致.--法則:--- `admit j == Right a` ならば `admittedJournal a == j`.-- note が重ならない `j1`, `j2` について, `admit j1` と `admit j2` が成功すれば `admit (j1 .+ j2)` も成功する.-- `admit Zero` は成功する.--## checkEvidence の照合--```haskell-checkEvidence- :: (Note m, HatBaseClass b)- => Admitted n b- -> (Journal n MoneyDecimal b -> Journal m MoneyDecimal b)- -> Journal m MoneyDecimal b- -> Either (NonEmpty (EvidenceMismatch m b)) ()-```--証憑 (銀行の明細, 現金の実査, 信頼側が与える期首の残高など) は, 期待する元の仕訳帳で渡す.-まず受入済みの仕訳帳に選び方 `f` を掛ける. `f` は射影, 振替, `bar`, note の付け替えなど,-利用者が要るだけ選んでまとめる関数である. `checkEvidence` 自身は集約せず, `bar` を呼ばない.--期待する posting 1 つ (note `m`, 基底 `b`, 値 `v`) を, `f` の結果への問い合わせとして片方向に照合する.-期待の元が pattern, `f` の結果の元が台帳の entry である.--- note: `plank` の note は全ての note に当たる. それ以外の note は自分自身にだけ当たる.-- 基底: 問い合わせの向きで照合する. 期待の基底の wildcard の軸 (勘定の `AccountTitle` など) は, その軸のどの値にも当たる.- 対称の `.==` は使わない.-- 側: 期待の基底の側は `Hat` か `Not` で書く (`(.@)` は `HatNot` を拒む).- 1 つの基底の両側を 1 つの正味の値として比べたいときは, `f` で `bar` を掛け, 結果の側を書く.--当たる posting がちょうど 1 つで値が厳密に等しければ一致である. それ以外は次の不一致になる.--| 当たる posting | 結果 |-|---|---|-| 0 個 | `EvidenceMissing m b v` |-| 1 個で値が違う | `EvidenceDiffers m b expected found` |-| 2 個以上 | `EvidenceAmbiguous m b values` (`f` で 1 つにまとめる. 同じ基底の両側なら `bar`, 別の勘定なら振替) |--posting は 1 つずつ数える. 同じ基底の seq の各項は別の posting で, 1 つにしたければ `f` で `bar` を掛ける.-期待側に同じ note と基底の posting が複数あれば, それぞれを独立の期待として照合する.-どの期待にも当たらない `f` の結果の元は無視する. 証憑は「あるべきもの」を述べ, 仕訳帳の全体を述べない.-全ての期待を照合し, 不一致は期待の note と基底の昇順で全部返す.--例: `f` の結果が `"sale"` の現金 100 だけのとき, 期待が `"sale"` の現金 100 なら一致,-`plank` の note の現金 100 でも一致, `"rent"` の現金 100 なら `EvidenceMissing` になる.--法則:--- `checkEvidence a f Zero == Right ()`.-- `e` の各 posting が, 上の片方向の照合で `admittedJournal a` のちょうど 1 つの posting に当たり, 値が等しければ- `checkEvidence a id e == Right ()`. 前提の「ちょうど 1 つ」は外せない. 例えば `plank` の note の現金 100 と- `"sale"` の現金 200 を持つ仕訳帳で, 現金だけを射影した元を期待にすると, `plank` の期待が 2 つに当たり- `EvidenceAmbiguous` になる.-- 期待ごとの検査なので, `checkEvidence a f (e1 .+ e2)` が成功するのは `checkEvidence a f e1` と `checkEvidence a f e2` が- ともに成功するときに限る.--## module の配置--| module | 公開 | 内容 |-|---|---|---|-| `ExchangeAlgebra.IO.Input.Admission` | 公開 | 入口. 取引の key, `admit`, `checkEvidence` と診断の型 |-| `...Admission.Diagnostic` | 非公開 | `AdmissionError`, `AdmissionFailure`, `EvidenceMismatch` |-| `...Admission.Representation` | 非公開 | `Admitted` と `admittedJournal` |-| `...Admission.Engine` | 非公開 | `admit` |-| `...Admission.Evidence` | 非公開 | `checkEvidence` |-| `ExchangeAlgebra.Accounting.Transaction` | 公開 | `TxKey`, `EntityId`, `PeriodId`, `TxId`, `Entry`, `isBlankKey` |-| `ExchangeAlgebra.Accounting.Equivalence` | 公開 | 取引の map の同値判定 (受入とは独立) |--構築子を置く非公開 module は, `package.yaml` と生成される `exchangealgebra.cabal` の両方で library の `other-modules` に登録する.--## 同値判定--`ExchangeAlgebra.Accounting.Equivalence` は受入とは独立した関数で, 受入していない `Entry` の map にも使える.-`isEquivalentUpTo` は全ての方式でキー集合の一致を要求し, 会社・期間・取引の境界を保つ.-posting の比較は `(Hat, AccountTitles, MoneyDecimal)` を sort した多重集合で行い, `Alg` の `Eq` や仕訳帳全体の `bar` で代用しない.--| 方式 | 正規化の範囲 |-|---|---|-| `PostingMultiset` | 行の順序だけを無視する |-| `NetWithinTransaction` | 各取引の `Alg` を個別に `bar` する |-| `NetAccountsInTransactions` | 指定した取引の指定した勘定だけ `bar` し, 他は厳密に比べる |--`closingDifferences` と `isClosingEquivalent` は 2 つの締めを取引の key ごとに比べる.-利益剰余金以外の勘定は借方・貸方の側ごとの厳密な合計で, 利益剰余金は貸方から借方を引いた厳密な正味で比べる.
exchangealgebra.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack name: exchangealgebra-version: 0.6.1.1+version: 0.7.0.0 synopsis: Exchange Algebra for bookkeeping and economic simulation description: Exchange Algebra is an algebraic description of bookkeeping developed by Hiroshi Deguchi. This package represents bookkeeping entries as members of a redundant algebra. The Hat direction of a base expresses a decrease, and the Not direction expresses an increase. Term values are non-negative. The package provides journals with notes, accounting operations such as closing, transfers, trial balances, and financial statements, CSV input and output, and a state-space framework for economic simulation. See the README for a guide and the changelog for migration notes. category: Accounting, Finance, Math@@ -14,8 +14,8 @@ author: Kaya Akagi maintainer: yakagika@icloud.com copyright: 2018-2026 Kaya Akagi-license: OtherLicense-license-file: LICENSE+license: MIT+license-file: LICENSE.txt build-type: Simple extra-source-files: README.md@@ -36,24 +36,12 @@ test/fixtures/example-numbers-p1/README.md test/fixtures/example-numbers-p1/ripple-analysis.tsv test/fixtures/export-surface-p2/counts.tsv- test/fixtures/export-surface-p2/ExchangeAlgebra.Accounting.PostingPolicy.txt+ test/fixtures/export-surface-p2/ExchangeAlgebra.Accounting.Account.Jcci.txt test/fixtures/export-surface-p2/ExchangeAlgebra.Accounting.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Base.Account.JcciAliases.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Base.Account.Registry.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Base.Account.Types.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Base.Element.txt test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Base.txt test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Internal.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Transfer.Rule.txt test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Transfer.txt test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Assist.Descriptions.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Assist.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Bookkeeping.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Consolidation.Worksheet.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Convert.Checked.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Convert.Csv.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Convert.txt test/fixtures/export-surface-p2/ExchangeAlgebra.IO.Input.Admission.txt test/fixtures/export-surface-p2/ExchangeAlgebra.Journal.Transfer.Rule.txt test/fixtures/export-surface-p2/ExchangeAlgebra.Journal.Transfer.txt@@ -61,13 +49,7 @@ test/fixtures/export-surface-p2/ExchangeAlgebra.Optimize.Annealing.txt test/fixtures/export-surface-p2/ExchangeAlgebra.Optimize.GA.txt test/fixtures/export-surface-p2/ExchangeAlgebra.Optimize.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Posting.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Render.Bookkeeping.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Render.Csv.txt test/fixtures/export-surface-p2/ExchangeAlgebra.Render.Simulation.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Reporting.Group.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Reporting.Metric.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Reporting.Presentation.txt test/fixtures/export-surface-p2/ExchangeAlgebra.Simulate.Analysis.txt test/fixtures/export-surface-p2/ExchangeAlgebra.Simulate.Engine.txt test/fixtures/export-surface-p2/ExchangeAlgebra.Simulate.Lite.txt@@ -77,21 +59,16 @@ test/fixtures/export-surface-p2/ExchangeAlgebra.Simulate.Spill.txt test/fixtures/export-surface-p2/ExchangeAlgebra.Simulate.txt test/fixtures/export-surface-p2/ExchangeAlgebra.Simulate.Visualize.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.TrialBalance.Balance.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.TrialBalance.Validation.txt test/fixtures/export-surface-p2/ExchangeAlgebra.txt- test/fixtures/export-surface-p2/ExchangeAlgebra.Value.txt test/fixtures/export-surface-p2/orphans.txt test/fixtures/export-surface-p2/README.md test/fixtures/jcci-2022/queries.tsv test/fixtures/jcci-2022/README.md test/fixtures/jcci-2022/source.tsv test/fixtures/post-vocab/account-info.tsv- test/fixtures/post-vocab/ordinals.tsv test/fixtures/post-vocab/README.md test/fixtures/post-vocab/semantics.tsv test/fixtures/post-vocab/suggest.tsv- test/fixtures/pre-vland2/ordinals.tsv test/fixtures/readout-baseline-p1/alg-decimal-f-dec2.tsv test/fixtures/readout-baseline-p1/alg-decimal-f-int.tsv test/fixtures/readout-baseline-p1/alg-double-f-cancel.tsv@@ -134,8 +111,9 @@ test/compile-fail/AlgRecordUpdate.hs test/compile-fail/Coerce.hs test/compile-fail/Constructor.hs- test/compile-fail/DeprecatedTransfer.hs test/compile-fail/HiddenModule.hs+ test/compile-fail/JcciHiddenConstructor.hs+ test/compile-fail/JcciMacroTitle.hs test/compile-fail/PublicClient.hs test/compile-fail/PublicExplicitImportClient.hs test/compile-fail/RawDerivation.hs@@ -150,7 +128,6 @@ test/compat-clients/README.md tools/check-export-surface.py tools/check-orphans.py- docs/admission-api-design-notes.md source-repository head type: git@@ -166,11 +143,11 @@ ExchangeAlgebra ExchangeAlgebra.Accounting ExchangeAlgebra.Accounting.Account+ ExchangeAlgebra.Accounting.Account.Jcci ExchangeAlgebra.Accounting.Closing ExchangeAlgebra.Accounting.Consolidation ExchangeAlgebra.Accounting.Entries ExchangeAlgebra.Accounting.Exchange- ExchangeAlgebra.Accounting.PostingPolicy ExchangeAlgebra.Accounting.Statements ExchangeAlgebra.Accounting.Statements.Group ExchangeAlgebra.Accounting.Statements.Metric@@ -181,24 +158,12 @@ ExchangeAlgebra.Accounting.Transfer ExchangeAlgebra.Algebra ExchangeAlgebra.Algebra.Base- ExchangeAlgebra.Algebra.Base.Account.JcciAliases- ExchangeAlgebra.Algebra.Base.Account.Registry- ExchangeAlgebra.Algebra.Base.Account.Types- ExchangeAlgebra.Algebra.Base.Element ExchangeAlgebra.Algebra.Core ExchangeAlgebra.Algebra.Element ExchangeAlgebra.Algebra.Internal ExchangeAlgebra.Algebra.Posting ExchangeAlgebra.Algebra.Transfer- ExchangeAlgebra.Algebra.Transfer.Rule ExchangeAlgebra.Algebra.Value- ExchangeAlgebra.Assist- ExchangeAlgebra.Assist.Descriptions- ExchangeAlgebra.Bookkeeping- ExchangeAlgebra.Consolidation.Worksheet- ExchangeAlgebra.Convert- ExchangeAlgebra.Convert.Checked- ExchangeAlgebra.Convert.Csv ExchangeAlgebra.IO.Input ExchangeAlgebra.IO.Input.Csv ExchangeAlgebra.IO.Input.Assist@@ -209,6 +174,7 @@ ExchangeAlgebra.Accounting.Transaction ExchangeAlgebra.Accounting.Adjustment ExchangeAlgebra.Accounting.Equivalence+ ExchangeAlgebra.Accounting.Audit ExchangeAlgebra.Journal ExchangeAlgebra.Journal.Core ExchangeAlgebra.Journal.Transfer@@ -216,13 +182,7 @@ ExchangeAlgebra.Optimize ExchangeAlgebra.Optimize.Annealing ExchangeAlgebra.Optimize.GA- ExchangeAlgebra.Posting- ExchangeAlgebra.Render.Bookkeeping- ExchangeAlgebra.Render.Csv ExchangeAlgebra.Render.Simulation- ExchangeAlgebra.Reporting.Group- ExchangeAlgebra.Reporting.Metric- ExchangeAlgebra.Reporting.Presentation ExchangeAlgebra.Simulate ExchangeAlgebra.Simulate.Analysis ExchangeAlgebra.Simulation.Analysis@@ -240,9 +200,6 @@ ExchangeAlgebra.Simulate.Policy ExchangeAlgebra.Simulate.Random ExchangeAlgebra.Simulate.Spill- ExchangeAlgebra.TrialBalance.Balance- ExchangeAlgebra.TrialBalance.Validation- ExchangeAlgebra.Value other-modules: ExchangeAlgebra.Accounting.TrialBalance.Accum ExchangeAlgebra.Accounting.Catalog@@ -254,8 +211,9 @@ ExchangeAlgebra.Journal.Core.Representation ExchangeAlgebra.Accounting.Account.Title ExchangeAlgebra.Accounting.Account.Classification- ExchangeAlgebra.Accounting.Account.Aliases+ ExchangeAlgebra.Accounting.Account.Spec ExchangeAlgebra.Accounting.Account.Registry+ ExchangeAlgebra.Accounting.Account.Vocabulary ExchangeAlgebra.Accounting.Account.PostingPolicy ExchangeAlgebra.Algebra.Transfer.Representation ExchangeAlgebra.Simulation.Network.Representation@@ -279,7 +237,6 @@ , containers >=0.6 && <0.8 , deepseq >=1.4 && <1.6 , hashable >=1.4 && <1.6- , numeric-prelude >=0.4.4 && <0.5 , parallel ==3.2.* , random ==1.2.* , scientific >=0.3.7 && <0.4@@ -315,7 +272,6 @@ , doctest , exchangealgebra , hashable >=1.4 && <1.6- , numeric-prelude >=0.4.4 && <0.5 , parallel ==3.2.* , random ==1.2.* , scientific >=0.3.7 && <0.4@@ -355,7 +311,6 @@ , deepseq >=1.4 && <1.6 , exchangealgebra , hashable- , numeric-prelude >=0.4.4 && <0.5 , parallel ==3.2.* , process , random ==1.2.*@@ -377,11 +332,20 @@ Algebra.ExactReadoutSpec Algebra.AccumSpec Algebra.CoreSpec+ Algebra.PairSpec Journal.JournalSpec Journal.NormalFormSpec Accounting.AdjustmentSpec+ Accounting.AuditSpec+ Accounting.ConsolidationVocabularySpec+ Accounting.PresentationVocabularySpec+ Accounting.VocabularyLawSpec+ Accounting.ClosingTargetSpec+ Accounting.JcciSpec Accounting.RegistrySpec+ Accounting.ProcedureLawSpec IO.InputOutputSpec+ IO.AccountNamesSpec Simulate.SimulateSpec Simulation.NetworkSpec Simulation.OptimizeSpec@@ -402,6 +366,7 @@ Transfer.RuleSpec Transfer.BalanceSpec Value.MoneyParseSpec+ Value.MoneyDoubleBinarySpec hs-source-dirs: test ghc-options: -threaded -rtsopts -with-rtsopts=-N@@ -419,7 +384,6 @@ , exchangealgebra , hashable >=1.4 && <1.6 , mtl ==2.3.*- , numeric-prelude >=0.4.4 && <0.5 , parallel ==3.2.* , random ==1.2.* , scientific >=0.3.7 && <0.4
src/ExchangeAlgebra.hs view
@@ -5,7 +5,7 @@ Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license Package for Exchange Algebra defined by Hiroshi Deguchi. @@ -39,8 +39,8 @@ * 'Prelude.Double' — fast IEEE-754; fine for simulations and quick work. * t'ExchangeAlgebra.Algebra.Value.MoneyDouble' — same speed, but a dedicated money newtype so a ledger value cannot be confused with a raw coefficient.- * t'ExchangeAlgebra.Algebra.Value.MoneyDecimal' — exact decimal; construction-order- independent totals. Use for audited\/deterministic ledgers.+ * t'ExchangeAlgebra.Algebra.Value.MoneyDecimal' — exact decimal arithmetic, so+ totals match decimal bookkeeping. Use for audited ledgers. For multi-period simulation or metadata-aware journals (notes, components), import "ExchangeAlgebra.Journal" qualified to avoid overlapping names@@ -98,9 +98,9 @@ , BaseForSingleHat(..) , customError , Element(..)- , AxisKey(..)- , axisIsWildcard- , AxisDecompose(..)+ , ElementKey(..)+ , elementKeyIsWildcard+ , HasElementKeys(..) , (.#) , Name , Subject@@ -174,6 +174,7 @@ , pimoFromDivision , pimoFlip , ExBaseClass(..)+ , StandardBase , AccountBase(..) , Exchange(..) , projCredit@@ -184,20 +185,17 @@ , projDeferredAssets , projCurrentLiability , projFixedLiability- , projCapitalStock+ , projNonContraCreditEquity , projContraAssets , projContra -- * Transfers and closing- , TransferScale(MulBy, DivBy)+ , TransferScale , TransferRule(..) , TransferRules , TransferRuleError(..) , TransferApplyError(..) , mkTransferRules , rulesToList- , relabel- , scaleBy- , divideBy , collapseEntries , collapseNetEntries , TransferShare(..)@@ -217,6 +215,9 @@ , transferEntriesByWith , ClosingSide(..) , closingSide+ , ClosingTargetViolation(..)+ , closingTargetViolation+ , ClosingError(..) , closingEntries , SettleRule , retainedEarningsRule@@ -232,17 +233,18 @@ , balanceSide , balanceAmount , TrialBalanceStage(..)- , TrialBalanceInput(..)- , ReclassificationRule(..)- , TBFinding(..)- , trialBalanceFindings- , ReportingContext(..)+ , ReportingContext+ , ReportingContextOf(..) , ReportingScope(..)+ , reportingContext , jcciSecondGradeContext- , FinancialStatements(..)+ , FinancialStatements+ , FinancialStatementsOf(..) , StatementSection(..)- , StatementLine(..)- , PresentationIssue(..)+ , StatementLine+ , StatementLineOf(..)+ , PresentationIssue+ , PresentationIssueOf(..) , present -- * Output , writeCSV@@ -309,6 +311,7 @@ ) import ExchangeAlgebra.Accounting.Exchange ( ExBaseClass(..)+ , StandardBase , AccountBase(..) , Exchange(..) , projCredit@@ -319,23 +322,20 @@ , projDeferredAssets , projCurrentLiability , projFixedLiability- , projCapitalStock+ , projNonContraCreditEquity , projContraAssets , projContra ) -- Generic per-posting rules. The accounting transfer below owns Relabel and -- transferEntries in this module, so they are not imported from here.-import ExchangeAlgebra.Algebra.Transfer.Representation- ( TransferScale(MulBy, DivBy)+import ExchangeAlgebra.Algebra.Transfer+ ( TransferScale , TransferRule(..) , TransferRules , TransferRuleError(..) , TransferApplyError(..) , mkTransferRules , rulesToList- , relabel- , scaleBy- , divideBy , collapseEntries , collapseNetEntries )@@ -343,6 +343,9 @@ import ExchangeAlgebra.Accounting.Closing ( ClosingSide(..) , closingSide+ , ClosingTargetViolation(..)+ , closingTargetViolation+ , ClosingError(..) , closingEntries , SettleRule , retainedEarningsRule@@ -359,21 +362,20 @@ , balanceSide , balanceAmount )-import ExchangeAlgebra.Accounting.TrialBalance.Validation- ( TrialBalanceStage(..)- , TrialBalanceInput(..)- , ReclassificationRule(..)- , TBFinding(..)- , trialBalanceFindings- )+import ExchangeAlgebra.Accounting.TrialBalance.Validation (TrialBalanceStage(..)) import ExchangeAlgebra.Accounting.Statements.Presentation- ( ReportingContext(..)+ ( ReportingContext+ , ReportingContextOf(..) , ReportingScope(..)+ , reportingContext , jcciSecondGradeContext- , FinancialStatements(..)+ , FinancialStatements+ , FinancialStatementsOf(..) , StatementSection(..)- , StatementLine(..)- , PresentationIssue(..)+ , StatementLine+ , StatementLineOf(..)+ , PresentationIssue+ , PresentationIssueOf(..) , present ) import ExchangeAlgebra.IO.Output.Csv (writeCSV, csvTranspose)
src/ExchangeAlgebra/Accounting.hs view
@@ -3,7 +3,7 @@ Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license The accounting layer on top of "ExchangeAlgebra.Algebra": the names that realize Definitions 7-9 of Akagi (2026), Appendix A.@@ -43,6 +43,7 @@ , FixedCurrent(..) , PIMO(..) , ExBaseClass(..)+ , StandardBase , AccountBase(..) , switchSide , defaultSide@@ -59,11 +60,12 @@ , projDeferredAssets , projCurrentLiability , projFixedLiability- , projCapitalStock+ , projNonContraCreditEquity , projContraAssets , projContra -- * Definition 9: base rules and closing- , module ExchangeAlgebra.Algebra.Transfer.Rule+ , module ExchangeAlgebra.Algebra.Transfer+ , module ExchangeAlgebra.Accounting.Closing -- * Definition 9: accounting transfer , module ExchangeAlgebra.Accounting.Transfer ) where@@ -84,6 +86,7 @@ ) import ExchangeAlgebra.Accounting.Exchange ( ExBaseClass(..)+ , StandardBase , AccountBase(..) , Exchange(..) , projCredit@@ -94,30 +97,30 @@ , projDeferredAssets , projCurrentLiability , projFixedLiability- , projCapitalStock+ , projNonContraCreditEquity , projContraAssets , projContra ) import ExchangeAlgebra.Accounting.Transfer -import ExchangeAlgebra.Algebra.Transfer.Representation as ExchangeAlgebra.Algebra.Transfer.Rule- ( TransferScale(MulBy, DivBy)+import ExchangeAlgebra.Algebra.Transfer+ ( TransferScale , TransferRule(..) , TransferRules , TransferRuleError(..) , TransferApplyError(..) , mkTransferRules , rulesToList- , relabel- , scaleBy- , divideBy , collapseEntries , collapseNetEntries ) -import ExchangeAlgebra.Accounting.Closing as ExchangeAlgebra.Algebra.Transfer.Rule+import ExchangeAlgebra.Accounting.Closing ( ClosingSide(..) , closingSide+ , ClosingTargetViolation(..)+ , closingTargetViolation+ , ClosingError(..) , closingEntries , SettleRule , retainedEarningsRule
src/ExchangeAlgebra/Accounting/Account.hs view
@@ -3,7 +3,8 @@ -- | Account title metadata and direction helpers for exchange bases (Definition 7). module ExchangeAlgebra.Accounting.Account- ( AccountTitles(..)+ ( AccountVocabulary(..)+ , AccountTitles(..) , AccountDivision(..), Side(..), ClosingRule(..), FixedCurrent(..) , AccountRole(..), PostingCapability(..), DivisionSemantics(..) , HomeSideSemantics(..), ReportingEligibility(..)@@ -15,13 +16,11 @@ , pimoFromDivision, pimoFlip ) where -import ExchangeAlgebra.Algebra.Base.Representation (customError)+import ExchangeAlgebra.Accounting.Account.Vocabulary (AccountVocabulary(..), classifyAccountDivision) import ExchangeAlgebra.Accounting.Account.Title (AccountTitles(..)) import ExchangeAlgebra.Accounting.Account.Classification import ExchangeAlgebra.Accounting.Account.Registry-import ExchangeAlgebra.Accounting.Account.Aliases (jcciAliases) import ExchangeAlgebra.Accounting.Account.PostingPolicy-import GHC.Stack (HasCallStack) import Control.DeepSeq (NFData(..)) -- | Reverse the credit/debit side. Swaps Credit and Debit.@@ -48,17 +47,6 @@ defaultSide Liability = Credit defaultSide Equity = Credit defaultSide Revenue = Credit---- | Classify an account title into an account division (Assets/Equity/Liability/Cost/Revenue).------ Complexity: O(1)-{-# INLINE classifyAccountDivision #-}-classifyAccountDivision :: HasCallStack => AccountTitles -> AccountDivision-classifyAccountDivision AccountTitle = customError "this is wildcard AccountTitle"-classifyAccountDivision title =- case accountSpec title of- Just spec -> asDivision spec- Nothing -> customError "this is wildcard AccountTitle" -- | PIMO direction. In Proposition 5.3.8 (Deguchi 2004, pp.89-91) PS, IN, -- MS and OUT mean __plus stock, input, minus stock and output__ —
− src/ExchangeAlgebra/Accounting/Account/Aliases.hs
@@ -1,217 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}-{-# OPTIONS_GHC -Wno-deprecations #-}---- Generated by tools/gen-jcci-aliases.py. Do not edit by hand.-module ExchangeAlgebra.Accounting.Account.Aliases- ( jcciAliases ) where--import Data.Text (Text)-import ExchangeAlgebra.Accounting.Account.Title (AccountTitles(..))---- | Return the JCCI account-name aliases for a title.-jcciAliases :: AccountTitles -> [Text]-jcciAliases AccountsPayable = ["〇〇商店", "買掛金"]-jcciAliases AccountsReceivable = ["売掛金", "〇〇商店"]-jcciAliases AccruedConsumptionTax = ["未払金", "未払消費税"]-jcciAliases AccruedCorporateIncomeTaxes = ["未払法人税等"]-jcciAliases AccruedExpenses = ["未払費用", "未払利息"]-jcciAliases AccruedRevenue = ["未収収益", "未収家賃"]-jcciAliases AccumulatedDepreciation = ["建物減価償却累計額", "減価償却累計額", "備品減価償却累計額", "車両運搬具減価償却累計額", "車両減価償却累計額"]-jcciAliases AdditionalIncomeTaxesForPriorPeriods = ["追徴法人税等"]-jcciAliases AdvancesPaid = ["前払金", "前渡金"]-jcciAliases AdvancesReceived = ["前受金", "契約負債"]-jcciAliases AdvertisingExpense = ["広告宣伝費", "広告費", "広告料", "宣伝費"]-jcciAliases AffiliateStocks = ["関係会社株式", "関連会社株式"]-jcciAliases AllowanceForBonuses = ["賞与引当金", "役員賞与引当金"]-jcciAliases AllowanceForDoubtfulAccounts = ["貸倒引当金"]-jcciAliases AllowanceForProductWarranties = ["商品保証引当金", "製品保証引当金"]-jcciAliases AllowanceForRepairs = ["修繕引当金", "特別修繕引当金"]-jcciAliases AllowanceForRetirementBenefits = ["退職給付引当金"]-jcciAliases AmortizationOfGoodwill = ["のれん償却"]-jcciAliases AmortizationOfPatents = ["特許権償却"]-jcciAliases AmortizationOfSoftware = ["ソフトウェア償却"]-jcciAliases AvailableForSaleSecurities = ["投資有価証券", "その他有価証券"]-jcciAliases BadDebtLoss = ["貸倒損失"]-jcciAliases BankOverdraft = ["借入金", "当座借越"]-jcciAliases Bonuses = ["賞与", "役員賞与"]-jcciAliases BonusesPayable = ["未払賞与", "未払役員賞与", "未払賞与金"]-jcciAliases BranchCurrentAccount = ["支店"]-jcciAliases Building = ["建物"]-jcciAliases BusinessCommencementExpenses = ["開業費"]-jcciAliases BusinessTrip = ["旅費交通費", "旅費", "交通費"]-jcciAliases CapitalStock = ["資本金"]-jcciAliases CapitalSurplus = ["資本剰余金"]-jcciAliases Cash = ["現金"]-jcciAliases CashOverShort = ["現金過不足"]-jcciAliases CommunicationExpenses = ["通信費"]-jcciAliases Commutation = ["通信費"]-jcciAliases ConstructionFundReserve = ["新築積立金"]-jcciAliases ConstructionInProgress = ["建設仮勘定", "建設仮", "建設前渡金", "建設仮払金"]-jcciAliases ConsumptionTaxPaid = ["仮払金", "仮払消費税"]-jcciAliases ConsumptionTaxReceived = ["仮受金", "仮受消費税"]-jcciAliases ConsumptionTaxRefundReceivable = ["未収還付消費税", "未収消費税"]-jcciAliases ContraAccountForGuaranteeObligations = ["保証債務見返"]-jcciAliases ContractAssets = ["契約資産"]-jcciAliases CorporateIncomeTaxes = ["法人税、住民税及び事業税", "法人税等"]-jcciAliases CostOfServices = ["役務原価", "営業費用"]-jcciAliases CreditCardReceivable = ["クレジット売掛金"]-jcciAliases CurrentDeposits = ["当座預金", "当座預金○○銀行"]-jcciAliases DeferredTaxAssets = ["繰延税金資産"]-jcciAliases DeferredTaxLiabilities = ["繰延税金負債"]-jcciAliases DeliveryExpenses = ["発送費", "支払運賃", "発送運賃"]-jcciAliases Deposits = ["普通預金", "銀行預金", "普通預金○○銀行"]-jcciAliases DepositsInSpecialAccounts = ["銀行預金", "別段預金"]-jcciAliases DepositsReceived = ["預り金", "従業員預り金", "所得税預り金", "住民税預り金", "社会保険料預り金"]-jcciAliases DepositsReceivedFromOfficers = ["役員預り金"]-jcciAliases Depreciation = ["減価償却費", "建物減価償却費", "備品減価償却費"]-jcciAliases DevelopmentExpenses = ["開発費"]-jcciAliases DishonoredNotesReceivable = ["不渡手形"]-jcciAliases DividendEqualizationReserve = ["配当平均積立金"]-jcciAliases DividendsReceived = ["受取配当金"]-jcciAliases EarnedSurplus = ["利益剰余金"]-jcciAliases ElectronicallyRecordedObligations = ["電子記録債務"]-jcciAliases ElectronicallyRecordedReceivable = ["電子記録債権"]-jcciAliases Fixtures = ["備品"]-jcciAliases ForeignExchangeGains = ["為替差損益", "為替差益"]-jcciAliases ForeignExchangeLosses = ["為替差損益", "為替差損"]-jcciAliases GainOnBargainPurchase = ["負ののれん発生益"]-jcciAliases GainOnConstructionGrants = ["工事負担金受贈益"]-jcciAliases GainOnDonationOfFixedAssets = ["固定資産受贈益"]-jcciAliases GainOnNationalSubsidies = ["国庫補助金受贈益"]-jcciAliases GainOnSalesOfFixedAssets = ["固定資産売却益", "備品売却益", "土地売却益", "建物売却益"]-jcciAliases GainOnSalesOfInvestmentSecurities = ["投資有価証券売却益", "その他有価証券売却益"]-jcciAliases GainOnSalesOfSecurities = ["有価証券売却益", "有価証券売買益", "有価証券運用益"]-jcciAliases GainOnValuationOfSecurities = ["有価証券運用益", "有価証券評価益", "有価証券評価損益", "有価証券運用損益"]-jcciAliases GeneralReserve = ["別途積立金"]-jcciAliases GiftCertificatesReceived = ["受取商品券"]-jcciAliases Goodwill = ["のれん"]-jcciAliases GuaranteeDepositsReceived = ["預り保証金", "受入保証金"]-jcciAliases GuaranteeObligations = ["保証債務"]-jcciAliases HeadOfficeCurrentAccount = ["本店"]-jcciAliases HeldToMaturityBonds = ["満期保有目的債券", "投資有価証券"]-jcciAliases IncomeSummary = ["損益"]-jcciAliases IncomeTaxesAdjustment = ["法人税等調整額"]-jcciAliases IncomeTaxesRefundReceivable = ["未収還付法人税等"]-jcciAliases IncorporationExpenses = ["創立費"]-jcciAliases InsuranceExpense = ["保険料", "支払保険料", "火災保険料"]-jcciAliases InsuranceGain = ["保険差益"]-jcciAliases InterestEarned = ["受取利息"]-jcciAliases InterestExpense = ["支払利息"]-jcciAliases InterestOnSecurities = ["有価証券利息", "受取社債利息"]-jcciAliases InventoryShrinkageLoss = ["棚卸減耗損", "棚卸減耗費"]-jcciAliases InvestmentSecurities = ["投資有価証券"]-jcciAliases Land = ["土地"]-jcciAliases LandRentPaid = ["地代家賃", "支払賃借料", "支払不動産賃借料", "支払地代"]-jcciAliases LandRentReceived = ["受取地代"]-jcciAliases LeaseExpenses = ["支払リース料"]-jcciAliases LeaseObligations = ["リース債務"]-jcciAliases LeasedAssets = ["リース資産"]-jcciAliases LeaseholdRights = ["借地権"]-jcciAliases LegalCapitalSurplus = ["資本準備金", "株式払込剰余金"]-jcciAliases LegalRetainedEarnings = ["利益準備金"]-jcciAliases LoansPayable = ["借入金", "銀行借入金", "役員借入金"]-jcciAliases LoansReceivable = ["貸付金", "従業員貸付金", "役員貸付金"]-jcciAliases LongTermLoansPayable = ["長期借入金"]-jcciAliases LongTermLoansReceivable = ["長期貸付金"]-jcciAliases LongTermOtherPayables = ["長期未払金"]-jcciAliases LongTermPrepaidExpenses = ["長期前払費用"]-jcciAliases LossOnFire = ["火災損失", "災害損失"]-jcciAliases LossOnReductionOfFixedAssets = ["固定資産圧縮損", "備品圧縮損", "建物圧縮損", "機械装置圧縮損"]-jcciAliases LossOnRetirementOfFixedAssets = ["固定資産除却損", "固定資産廃棄損", "備品除却損", "建物除却損", "除却損"]-jcciAliases LossOnSalesOfElectronicallyRecordedReceivables = ["電子記録債権売却損"]-jcciAliases LossOnSalesOfFixedAssets = ["固定資産売却損", "備品売却損", "建物売却損", "土地売却損"]-jcciAliases LossOnSalesOfInvestmentSecurities = ["投資有価証券売却損", "その他有価証券売却損"]-jcciAliases LossOnSalesOfNotesReceivable = ["手形売却損"]-jcciAliases LossOnSalesOfReceivables = ["債権売却損"]-jcciAliases LossOnSalesOfSecurities = ["有価証券売却損", "有価証券売買損", "有価証券運用損"]-jcciAliases LossOnValuationOfMerchandise = ["商品評価損", "棚卸評価損"]-jcciAliases LossOnValuationOfSecurities = ["有価証券運用損", "有価証券評価損", "有価証券評価損益", "有価証券運用損益"]-jcciAliases Machinery = ["機械装置", "機械"]-jcciAliases MaintenanceExpenses = ["保守費", "維持費", "支払メンテナンス料"]-jcciAliases MembershipFees = ["諸会費"]-jcciAliases MerchandiseInventory = ["繰越商品"]-jcciAliases MiscellaneousExpenses = ["雑費"]-jcciAliases MiscellaneousIncome = ["雑益", "雑収入", "雑収益"]-jcciAliases MiscellaneousLoss = ["雑損", "雑損失"]-jcciAliases NetDefinedBenefitAsset = ["退職給付に係る資産"]-jcciAliases NetDefinedBenefitLiability = ["退職給付に係る負債"]-jcciAliases NetIncomeAttributableToNCI = ["非支配株主に帰属する当期純利益"]-jcciAliases NetLossAttributableToNCI = ["非支配株主に帰属する当期純損失"]-jcciAliases NonControllingInterests = ["非支配株主持分"]-jcciAliases NonOperatingElectronicallyRecordedObligations = ["営業外電子記録債務"]-jcciAliases NonOperatingElectronicallyRecordedReceivable = ["営業外電子記録債権"]-jcciAliases NonOperatingNotesPayable = ["営業外支払手形"]-jcciAliases NonOperatingNotesReceivable = ["営業外受取手形"]-jcciAliases NotesLoansPayable = ["借入金", "手形借入金"]-jcciAliases NotesLoansReceivable = ["貸付金", "手形貸付金"]-jcciAliases NotesPayable = ["支払手形"]-jcciAliases NotesReceivable = ["受取手形"]-jcciAliases OperatingExpenses = ["営業費用"]-jcciAliases OperatingRevenue = ["営業収益"]-jcciAliases OtherCapitalSurplus = ["その他資本剰余金"]-jcciAliases OtherPayables = ["未払金"]-jcciAliases OtherReceivables = ["未収入金", "未収金"]-jcciAliases Patent = ["特許権"]-jcciAliases PaymentFees = ["支払手数料", "販売手数料"]-jcciAliases PaymentsOnBehalf = ["立替金", "従業員立替金"]-jcciAliases PettyCash = ["小口現金"]-jcciAliases PrepaidCorporateIncomeTaxes = ["仮払金", "仮払法人税等"]-jcciAliases PrepaidExpenses = ["前払費用", "前払保険料"]-jcciAliases PrepaidPensionCost = ["前払年金費用"]-jcciAliases Products = ["商品"]-jcciAliases PropertyTaxPayable = ["未払固定資産税"]-jcciAliases ProvisionForBonuses = ["賞与引当金繰入", "役員賞与引当金繰入"]-jcciAliases ProvisionForDoubtfulAccounts = ["貸倒引当金繰入", "貸倒引当金繰入額"]-jcciAliases ProvisionForProductWarranties = ["商品保証引当金繰入", "製品保証引当金繰入"]-jcciAliases ProvisionForRepairs = ["修繕引当金繰入", "特別修繕引当金繰入"]-jcciAliases PurchaseRebates = ["仕入割戻"]-jcciAliases Purchases = ["仕入"]-jcciAliases ReceiptFee = ["受取手数料"]-jcciAliases RecoveryOfBadDebts = ["償却債権取立益"]-jcciAliases RefundLiabilities = ["返金負債"]-jcciAliases RefundOfIncomeTaxes = ["還付法人税等"]-jcciAliases RentExpense = ["支払家賃", "地代家賃", "支払賃借料", "支払不動産賃借料"]-jcciAliases RentalIncome = ["受取家賃"]-jcciAliases RepairFundReserve = ["修繕積立金"]-jcciAliases RepairsExpense = ["修繕費", "支払修繕料", "修理費"]-jcciAliases ResearchAndDevelopmentExpenses = ["研究開発費"]-jcciAliases RetainedEarnings = ["繰越利益剰余金"]-jcciAliases RetirementBenefitExpenses = ["退職給付費用", "退職給付引当金繰入", "退職給付引当損"]-jcciAliases ReversalOfAllowanceForDoubtfulAccounts = ["貸倒引当金戻入", "貸倒引当金戻入益"]-jcciAliases ReversalOfAllowanceForProductWarranties = ["商品保証引当金戻入", "製品保証引当金戻入"]-jcciAliases ReversalOfAllowanceForRepairs = ["修繕引当金戻入"]-jcciAliases Sales = ["売上"]-jcciAliases SalesCost = ["売上原価"]-jcciAliases SalesRebates = ["売上割戻"]-jcciAliases Securities = ["有価証券"]-jcciAliases SecurityDepositsPaid = ["差入保証金"]-jcciAliases ServiceRevenue = ["役務収益", "営業収益"]-jcciAliases ShortTermLoansPayable = ["短期借入金"]-jcciAliases ShortTermLoansReceivable = ["短期貸付金"]-jcciAliases Software = ["ソフトウェア"]-jcciAliases SoftwareInProgress = ["ソフトウェア仮勘定"]-jcciAliases StatutoryWelfareExpenses = ["法定福利費", "社会保険料"]-jcciAliases StockIssuanceCosts = ["株式交付費"]-jcciAliases StockSubscriptionDeposits = ["株式申込証拠金", "申込証拠金", "新株式申込証拠金"]-jcciAliases StorageExpenses = ["保管費", "保管料", "倉庫料"]-jcciAliases Structures = ["構築物"]-jcciAliases SubsidiaryStocks = ["子会社株式", "関係会社株式"]-jcciAliases SuppliesExpenses = ["消耗品費", "事務用消耗品費"]-jcciAliases SuppliesOnHand = ["貯蔵品"]-jcciAliases SuspenseAccount = ["未決算", "火災未決算", "保険未決算"]-jcciAliases SuspensePayments = ["仮払金"]-jcciAliases SuspenseReceipts = ["仮受金"]-jcciAliases TaxesExpense = ["租税公課", "公租公課", "固定資産税", "印紙税"]-jcciAliases TimeDeposits = ["銀行預金", "定期預金", "定期預金○○銀行"]-jcciAliases ToolsAndInstruments = ["工具器具"]-jcciAliases Trademark = ["商標権"]-jcciAliases TradingSecurities = ["売買目的有価証券", "有価証券"]-jcciAliases UnearnedRevenue = ["前受収益", "前受地代"]-jcciAliases UnpaidDividends = ["未払配当金", "未払株主配当金"]-jcciAliases UtilitiesExpense = ["水道光熱費", "光熱水費"]-jcciAliases ValuationDifferenceOnOtherSecurities = ["その他有価証券評価差額金"]-jcciAliases Vehicle = ["車両運搬具", "車両", "運搬具"]-jcciAliases WageExpenditure = ["給料", "給料手当", "賃金給料"]-jcciAliases WelfareExpenses = ["福利厚生費"]-jcciAliases WorkInProcess = ["仕掛品"]-jcciAliases _ = []
+ src/ExchangeAlgebra/Accounting/Account/Jcci.hs view
@@ -0,0 +1,1037 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE TypeFamilies #-}++-- | Account titles for ledgers limited to the library's JCCI vocabulary.+--+-- Import this module for t'JcciTitles'. Import @ExchangeAlgebra.Accounting.Account@+-- for the chart that also includes macroeconomic accounts. Use qualified imports+-- when working with both charts in one module.+--+-- When adding a JCCI title, add its constructor and row to the account title+-- table. Add the matching pattern to this module's export list, type signature,+-- definitions, and @COMPLETE@ pragma in constructor order.+module ExchangeAlgebra.Accounting.Account.Jcci+ ( JcciTitles+ , widen+ , narrow+ , narrowAlg+ , pattern Cash+ , pattern Deposits+ , pattern CurrentDeposits+ , pattern Securities+ , pattern InvestmentSecurities+ , pattern InvestmentInAssociate+ , pattern LongTermNationalBonds+ , pattern ShortTermNationalBonds+ , pattern Products+ , pattern Machinery+ , pattern Building+ , pattern Vehicle+ , pattern StockInvestment+ , pattern EquipmentInvestment+ , pattern LongTermLoansReceivable+ , pattern AccountsReceivable+ , pattern ShortTermLoansReceivable+ , pattern Gold+ , pattern CapitalStock+ , pattern RetainedEarnings+ , pattern LongTermLoansPayable+ , pattern ShortTermLoansPayable+ , pattern LoansPayable+ , pattern LongTermNationalBondsPayable+ , pattern ShortTermNationalBondsPayable+ , pattern Depreciation+ , pattern AmortizationExpense+ , pattern SalesCost+ , pattern BusinessTrip+ , pattern UtilitiesExpense+ , pattern RentExpense+ , pattern AdvertisingExpense+ , pattern DeliveryExpenses+ , pattern SuppliesExpenses+ , pattern MiscellaneousExpenses+ , pattern WageExpenditure+ , pattern InterestExpense+ , pattern TaxesExpense+ , pattern Purchases+ , pattern NetIncome+ , pattern NationalBondInterestEarned+ , pattern DepositInterestEarned+ , pattern GrossProfit+ , pattern OrdinaryProfit+ , pattern InterestEarned+ , pattern ReceiptFee+ , pattern RentalIncome+ , pattern Sales+ , pattern EquityInEarningsOfInvestee+ , pattern NetLoss+ , pattern PettyCash+ , pattern NotesReceivable+ , pattern ElectronicallyRecordedReceivable+ , pattern CreditCardReceivable+ , pattern NotesLoansReceivable+ , pattern MerchandiseInventory+ , pattern AdvancesPaid+ , pattern PrepaidExpenses+ , pattern AccruedRevenue+ , pattern OtherReceivables+ , pattern PaymentsOnBehalf+ , pattern SuspensePayments+ , pattern ConsumptionTaxPaid+ , pattern PrepaidCorporateIncomeTaxes+ , pattern Land+ , pattern Fixtures+ , pattern Patent+ , pattern Trademark+ , pattern Software+ , pattern CashOverShort+ , pattern AccountsPayable+ , pattern NotesPayable+ , pattern ElectronicallyRecordedObligations+ , pattern NotesLoansPayable+ , pattern BankOverdraft+ , pattern AdvancesReceived+ , pattern UnearnedRevenue+ , pattern AccruedExpenses+ , pattern OtherPayables+ , pattern DepositsReceived+ , pattern SuspenseReceipts+ , pattern ConsumptionTaxReceived+ , pattern AccruedConsumptionTax+ , pattern AccruedCorporateIncomeTaxes+ , pattern UnpaidDividends+ , pattern AllowanceForDoubtfulAccounts+ , pattern AccumulatedDepreciation+ , pattern LegalRetainedEarnings+ , pattern CumulativeTranslationAdjustment+ , pattern ProvisionForDoubtfulAccounts+ , pattern BadDebtLoss+ , pattern LossOnSalesOfFixedAssets+ , pattern LossOnSalesOfNotesReceivable+ , pattern PaymentFees+ , pattern MiscellaneousLoss+ , pattern CorporateIncomeTaxes+ , pattern CommunicationExpenses+ , pattern GainOnSalesOfFixedAssets+ , pattern RecoveryOfBadDebts+ , pattern MiscellaneousIncome+ , pattern ReversalOfAllowanceForDoubtfulAccounts+ , pattern TimeDeposits+ , pattern LoansReceivable+ , pattern GiftCertificatesReceived+ , pattern SecurityDepositsPaid+ , pattern SuppliesOnHand+ , pattern ContractAssets+ , pattern IncomeTaxesRefundReceivable+ , pattern WorkInProcess+ , pattern DeferredTaxAssets+ , pattern LeasedAssets+ , pattern ToolsAndInstruments+ , pattern ConstructionInProgress+ , pattern Goodwill+ , pattern SoftwareInProgress+ , pattern LongTermPrepaidExpenses+ , pattern DishonoredNotesReceivable+ , pattern PrepaidPensionCost+ , pattern NetDefinedBenefitAsset+ , pattern DepositsInSpecialAccounts+ , pattern Structures+ , pattern LeaseholdRights+ , pattern NonOperatingNotesReceivable+ , pattern NonOperatingElectronicallyRecordedReceivable+ , pattern RefundLiabilities+ , pattern NonOperatingNotesPayable+ , pattern NonOperatingElectronicallyRecordedObligations+ , pattern BonusesPayable+ , pattern AllowanceForRepairs+ , pattern AllowanceForProductWarranties+ , pattern AllowanceForBonuses+ , pattern DeferredTaxLiabilities+ , pattern LeaseObligations+ , pattern GuaranteeDepositsReceived+ , pattern AllowanceForRetirementBenefits+ , pattern LongTermOtherPayables+ , pattern NetDefinedBenefitLiability+ , pattern StockSubscriptionDeposits+ , pattern LegalCapitalSurplus+ , pattern OtherCapitalSurplus+ , pattern DividendEqualizationReserve+ , pattern RepairFundReserve+ , pattern ConstructionFundReserve+ , pattern GeneralReserve+ , pattern ValuationDifferenceOnOtherSecurities+ , pattern NonControllingInterests+ , pattern CapitalSurplus+ , pattern EarnedSurplus+ , pattern ServiceRevenue+ , pattern OperatingRevenue+ , pattern GainOnSalesOfSecurities+ , pattern GainOnValuationOfSecurities+ , pattern DividendsReceived+ , pattern InterestOnSecurities+ , pattern GainOnSalesOfInvestmentSecurities+ , pattern InsuranceGain+ , pattern GainOnBargainPurchase+ , pattern ReversalOfAllowanceForRepairs+ , pattern ReversalOfAllowanceForProductWarranties+ , pattern GainOnDonationOfFixedAssets+ , pattern GainOnNationalSubsidies+ , pattern GainOnConstructionGrants+ , pattern LandRentReceived+ , pattern SalesRebates+ , pattern CostOfServices+ , pattern OperatingExpenses+ , pattern InventoryShrinkageLoss+ , pattern LossOnValuationOfMerchandise+ , pattern Bonuses+ , pattern RetirementBenefitExpenses+ , pattern ProvisionForRepairs+ , pattern ProvisionForBonuses+ , pattern ProvisionForProductWarranties+ , pattern ResearchAndDevelopmentExpenses+ , pattern AmortizationOfGoodwill+ , pattern AmortizationOfSoftware+ , pattern AmortizationOfPatents+ , pattern LeaseExpenses+ , pattern IncorporationExpenses+ , pattern StockIssuanceCosts+ , pattern BusinessCommencementExpenses+ , pattern DevelopmentExpenses+ , pattern LossOnSalesOfElectronicallyRecordedReceivables+ , pattern LossOnSalesOfReceivables+ , pattern LossOnSalesOfSecurities+ , pattern LossOnValuationOfSecurities+ , pattern LossOnSalesOfInvestmentSecurities+ , pattern LossOnFire+ , pattern LossOnRetirementOfFixedAssets+ , pattern LossOnReductionOfFixedAssets+ , pattern AdditionalIncomeTaxesForPriorPeriods+ , pattern RefundOfIncomeTaxes+ , pattern PurchaseRebates+ , pattern WelfareExpenses+ , pattern MaintenanceExpenses+ , pattern StatutoryWelfareExpenses+ , pattern LandRentPaid+ , pattern InsuranceExpense+ , pattern RepairsExpense+ , pattern StorageExpenses+ , pattern MembershipFees+ , pattern IncomeSummary+ , pattern SuspenseAccount+ , pattern ForeignExchangeGains+ , pattern ForeignExchangeLosses+ , pattern ContraAccountForGuaranteeObligations+ , pattern GuaranteeObligations+ , pattern IncomeTaxesAdjustment+ , pattern BranchCurrentAccount+ , pattern HeadOfficeCurrentAccount+ , pattern NetIncomeAttributableToNCI+ , pattern NetLossAttributableToNCI+ , pattern TradingSecurities+ , pattern HeldToMaturityBonds+ , pattern SubsidiaryStocks+ , pattern AffiliateStocks+ , pattern AvailableForSaleSecurities+ , pattern ConsumptionTaxRefundReceivable+ , pattern PropertyTaxPayable+ , pattern DepositsReceivedFromOfficers+ , pattern EntertainmentExpenses+ , pattern MeetingExpenses+ , pattern NewspaperBooksExpenses+ , pattern RawMaterials+ , pattern GoodsInTransit+ , pattern SalesAllowances+ , pattern PurchaseAllowances+ , pattern ReversalOfAllowanceForBonuses+ , pattern DirectorsCompensations+ , pattern AnyJcci+ ) where++import Control.DeepSeq (NFData)+import qualified Data.Binary as Binary+import Data.Hashable (Hashable)+import qualified Data.Set as Set+import ExchangeAlgebra.Accounting.Account.Classification (Side(..))+import ExchangeAlgebra.Accounting.Account.Title (AccountTitles)+import qualified ExchangeAlgebra.Accounting.Account.Title as T+import ExchangeAlgebra.Accounting.Account.Vocabulary (AccountVocabulary(..))+import ExchangeAlgebra.Accounting.Exchange (ExBaseClass(..))+import ExchangeAlgebra.Algebra.Base (BaseClass, Element(..), HatBase(..))+import ExchangeAlgebra.Algebra.Core (Alg, (.@), foldEntries, unionsMerge)+import ExchangeAlgebra.Algebra.Value (HatVal)++-- | A JCCI account title or the wildcard 'AnyJcci'.+newtype JcciTitles = JcciTitles AccountTitles+ deriving newtype (Eq, Ord, Show, NFData, Hashable)++instance Binary.Binary JcciTitles where+ put = Binary.put . widen+ get = do+ title <- Binary.get+ case narrow title of+ Just jcci -> pure jcci+ Nothing -> fail ("JcciTitles: macroeconomic account " ++ show title)++instance Element JcciTitles where+ wildcard = AnyJcci++instance BaseClass JcciTitles++instance AccountVocabulary JcciTitles where+ vocabSpec = vocabSpec . widen+ vocabSemantics = vocabSemantics . widen+ vocabImpossibleBalanceSides =+ [ (Cash, Credit)+ , (PettyCash, Credit)+ , (CapitalStock, Debit)+ , (AccumulatedDepreciation, Debit)+ ]+ vocabSuspenseTitles = [SuspensePayments, SuspenseReceipts, SuspenseAccount]+ vocabAdditionalClosingResidualTitles = [CashOverShort]+ vocabReciprocalPairs = [(BranchCurrentAccount, HeadOfficeCurrentAccount)]+ closingTarget = RetainedEarnings+ vocabDivision = vocabDivision . widen+ vocabContra = vocabContra . widen++instance ExBaseClass (HatBase JcciTitles) where+ type TitleOf (HatBase JcciTitles) = JcciTitles+ getAccountTitle (_ :< title) = title+ setAccountTitle (side :< _) title = side :< title++-- | Embed a JCCI title in the full chart, mapping 'AnyJcci' to the full chart's wildcard.+--+-- Use @mapBasePart widen ledger@ to embed a ledger. The relabeling preserves+-- term values, Hat and Not directions, and the order of terms with the same base.+widen :: JcciTitles -> AccountTitles+widen (JcciTitles title) = title++-- | Restrict a full-chart title to the JCCI vocabulary.+-- The full chart's wildcard maps to 'AnyJcci'. Macroeconomic titles return 'Nothing'.+narrow :: AccountTitles -> Maybe JcciTitles+narrow title+ | T.isJcciTitle title = Just (JcciTitles title)+ | otherwise = Nothing++-- | Restrict a ledger with account-only bases to the JCCI vocabulary.+-- On success, preserve term values, Hat and Not directions, and each base's term order.+-- If any term uses a macroeconomic title, return all such titles once in ascending order.+narrowAlg+ :: HatVal v+ => Alg v (HatBase AccountTitles)+ -> Either [AccountTitles] (Alg v (HatBase JcciTitles))+narrowAlg ledger = case Set.toAscList rejected of+ [] -> Right (unionsMerge (reverse terms))+ titles -> Left titles+ where+ -- Collect with cons, then pass the terms to unionsMerge in traversal order.+ (rejected, terms) = foldEntries collect (Set.empty, []) ledger++ collect (!missing, accepted) value (side :< title) =+ case narrow title of+ Nothing -> (Set.insert title missing, accepted)+ Just jcci -> (missing, (value .@ side :< jcci) : accepted)++-- | Account title patterns in the full chart's declaration order.+pattern Cash+ , Deposits+ , CurrentDeposits+ , Securities+ , InvestmentSecurities+ , InvestmentInAssociate+ , LongTermNationalBonds+ , ShortTermNationalBonds+ , Products+ , Machinery+ , Building+ , Vehicle+ , StockInvestment+ , EquipmentInvestment+ , LongTermLoansReceivable+ , AccountsReceivable+ , ShortTermLoansReceivable+ , Gold+ , CapitalStock+ , RetainedEarnings+ , LongTermLoansPayable+ , ShortTermLoansPayable+ , LoansPayable+ , LongTermNationalBondsPayable+ , ShortTermNationalBondsPayable+ , Depreciation+ , AmortizationExpense+ , SalesCost+ , BusinessTrip+ , UtilitiesExpense+ , RentExpense+ , AdvertisingExpense+ , DeliveryExpenses+ , SuppliesExpenses+ , MiscellaneousExpenses+ , WageExpenditure+ , InterestExpense+ , TaxesExpense+ , Purchases+ , NetIncome+ , NationalBondInterestEarned+ , DepositInterestEarned+ , GrossProfit+ , OrdinaryProfit+ , InterestEarned+ , ReceiptFee+ , RentalIncome+ , Sales+ , EquityInEarningsOfInvestee+ , NetLoss+ , PettyCash+ , NotesReceivable+ , ElectronicallyRecordedReceivable+ , CreditCardReceivable+ , NotesLoansReceivable+ , MerchandiseInventory+ , AdvancesPaid+ , PrepaidExpenses+ , AccruedRevenue+ , OtherReceivables+ , PaymentsOnBehalf+ , SuspensePayments+ , ConsumptionTaxPaid+ , PrepaidCorporateIncomeTaxes+ , Land+ , Fixtures+ , Patent+ , Trademark+ , Software+ , CashOverShort+ , AccountsPayable+ , NotesPayable+ , ElectronicallyRecordedObligations+ , NotesLoansPayable+ , BankOverdraft+ , AdvancesReceived+ , UnearnedRevenue+ , AccruedExpenses+ , OtherPayables+ , DepositsReceived+ , SuspenseReceipts+ , ConsumptionTaxReceived+ , AccruedConsumptionTax+ , AccruedCorporateIncomeTaxes+ , UnpaidDividends+ , AllowanceForDoubtfulAccounts+ , AccumulatedDepreciation+ , LegalRetainedEarnings+ , CumulativeTranslationAdjustment+ , ProvisionForDoubtfulAccounts+ , BadDebtLoss+ , LossOnSalesOfFixedAssets+ , LossOnSalesOfNotesReceivable+ , PaymentFees+ , MiscellaneousLoss+ , CorporateIncomeTaxes+ , CommunicationExpenses+ , GainOnSalesOfFixedAssets+ , RecoveryOfBadDebts+ , MiscellaneousIncome+ , ReversalOfAllowanceForDoubtfulAccounts+ , TimeDeposits+ , LoansReceivable+ , GiftCertificatesReceived+ , SecurityDepositsPaid+ , SuppliesOnHand+ , ContractAssets+ , IncomeTaxesRefundReceivable+ , WorkInProcess+ , DeferredTaxAssets+ , LeasedAssets+ , ToolsAndInstruments+ , ConstructionInProgress+ , Goodwill+ , SoftwareInProgress+ , LongTermPrepaidExpenses+ , DishonoredNotesReceivable+ , PrepaidPensionCost+ , NetDefinedBenefitAsset+ , DepositsInSpecialAccounts+ , Structures+ , LeaseholdRights+ , NonOperatingNotesReceivable+ , NonOperatingElectronicallyRecordedReceivable+ , RefundLiabilities+ , NonOperatingNotesPayable+ , NonOperatingElectronicallyRecordedObligations+ , BonusesPayable+ , AllowanceForRepairs+ , AllowanceForProductWarranties+ , AllowanceForBonuses+ , DeferredTaxLiabilities+ , LeaseObligations+ , GuaranteeDepositsReceived+ , AllowanceForRetirementBenefits+ , LongTermOtherPayables+ , NetDefinedBenefitLiability+ , StockSubscriptionDeposits+ , LegalCapitalSurplus+ , OtherCapitalSurplus+ , DividendEqualizationReserve+ , RepairFundReserve+ , ConstructionFundReserve+ , GeneralReserve+ , ValuationDifferenceOnOtherSecurities+ , NonControllingInterests+ , CapitalSurplus+ , EarnedSurplus+ , ServiceRevenue+ , OperatingRevenue+ , GainOnSalesOfSecurities+ , GainOnValuationOfSecurities+ , DividendsReceived+ , InterestOnSecurities+ , GainOnSalesOfInvestmentSecurities+ , InsuranceGain+ , GainOnBargainPurchase+ , ReversalOfAllowanceForRepairs+ , ReversalOfAllowanceForProductWarranties+ , GainOnDonationOfFixedAssets+ , GainOnNationalSubsidies+ , GainOnConstructionGrants+ , LandRentReceived+ , SalesRebates+ , CostOfServices+ , OperatingExpenses+ , InventoryShrinkageLoss+ , LossOnValuationOfMerchandise+ , Bonuses+ , RetirementBenefitExpenses+ , ProvisionForRepairs+ , ProvisionForBonuses+ , ProvisionForProductWarranties+ , ResearchAndDevelopmentExpenses+ , AmortizationOfGoodwill+ , AmortizationOfSoftware+ , AmortizationOfPatents+ , LeaseExpenses+ , IncorporationExpenses+ , StockIssuanceCosts+ , BusinessCommencementExpenses+ , DevelopmentExpenses+ , LossOnSalesOfElectronicallyRecordedReceivables+ , LossOnSalesOfReceivables+ , LossOnSalesOfSecurities+ , LossOnValuationOfSecurities+ , LossOnSalesOfInvestmentSecurities+ , LossOnFire+ , LossOnRetirementOfFixedAssets+ , LossOnReductionOfFixedAssets+ , AdditionalIncomeTaxesForPriorPeriods+ , RefundOfIncomeTaxes+ , PurchaseRebates+ , WelfareExpenses+ , MaintenanceExpenses+ , StatutoryWelfareExpenses+ , LandRentPaid+ , InsuranceExpense+ , RepairsExpense+ , StorageExpenses+ , MembershipFees+ , IncomeSummary+ , SuspenseAccount+ , ForeignExchangeGains+ , ForeignExchangeLosses+ , ContraAccountForGuaranteeObligations+ , GuaranteeObligations+ , IncomeTaxesAdjustment+ , BranchCurrentAccount+ , HeadOfficeCurrentAccount+ , NetIncomeAttributableToNCI+ , NetLossAttributableToNCI+ , TradingSecurities+ , HeldToMaturityBonds+ , SubsidiaryStocks+ , AffiliateStocks+ , AvailableForSaleSecurities+ , ConsumptionTaxRefundReceivable+ , PropertyTaxPayable+ , DepositsReceivedFromOfficers+ , EntertainmentExpenses+ , MeetingExpenses+ , NewspaperBooksExpenses+ , RawMaterials+ , GoodsInTransit+ , SalesAllowances+ , PurchaseAllowances+ , ReversalOfAllowanceForBonuses+ , DirectorsCompensations+ :: JcciTitles+pattern Cash = JcciTitles T.Cash+pattern Deposits = JcciTitles T.Deposits+pattern CurrentDeposits = JcciTitles T.CurrentDeposits+pattern Securities = JcciTitles T.Securities+pattern InvestmentSecurities = JcciTitles T.InvestmentSecurities+pattern InvestmentInAssociate = JcciTitles T.InvestmentInAssociate+pattern LongTermNationalBonds = JcciTitles T.LongTermNationalBonds+pattern ShortTermNationalBonds = JcciTitles T.ShortTermNationalBonds+pattern Products = JcciTitles T.Products+pattern Machinery = JcciTitles T.Machinery+pattern Building = JcciTitles T.Building+pattern Vehicle = JcciTitles T.Vehicle+pattern StockInvestment = JcciTitles T.StockInvestment+pattern EquipmentInvestment = JcciTitles T.EquipmentInvestment+pattern LongTermLoansReceivable = JcciTitles T.LongTermLoansReceivable+pattern AccountsReceivable = JcciTitles T.AccountsReceivable+pattern ShortTermLoansReceivable = JcciTitles T.ShortTermLoansReceivable+pattern Gold = JcciTitles T.Gold+pattern CapitalStock = JcciTitles T.CapitalStock+pattern RetainedEarnings = JcciTitles T.RetainedEarnings+pattern LongTermLoansPayable = JcciTitles T.LongTermLoansPayable+pattern ShortTermLoansPayable = JcciTitles T.ShortTermLoansPayable+pattern LoansPayable = JcciTitles T.LoansPayable+pattern LongTermNationalBondsPayable = JcciTitles T.LongTermNationalBondsPayable+pattern ShortTermNationalBondsPayable = JcciTitles T.ShortTermNationalBondsPayable+pattern Depreciation = JcciTitles T.Depreciation+pattern AmortizationExpense = JcciTitles T.AmortizationExpense+pattern SalesCost = JcciTitles T.SalesCost+pattern BusinessTrip = JcciTitles T.BusinessTrip+pattern UtilitiesExpense = JcciTitles T.UtilitiesExpense+pattern RentExpense = JcciTitles T.RentExpense+pattern AdvertisingExpense = JcciTitles T.AdvertisingExpense+pattern DeliveryExpenses = JcciTitles T.DeliveryExpenses+pattern SuppliesExpenses = JcciTitles T.SuppliesExpenses+pattern MiscellaneousExpenses = JcciTitles T.MiscellaneousExpenses+pattern WageExpenditure = JcciTitles T.WageExpenditure+pattern InterestExpense = JcciTitles T.InterestExpense+pattern TaxesExpense = JcciTitles T.TaxesExpense+pattern Purchases = JcciTitles T.Purchases+pattern NetIncome = JcciTitles T.NetIncome+pattern NationalBondInterestEarned = JcciTitles T.NationalBondInterestEarned+pattern DepositInterestEarned = JcciTitles T.DepositInterestEarned+pattern GrossProfit = JcciTitles T.GrossProfit+pattern OrdinaryProfit = JcciTitles T.OrdinaryProfit+pattern InterestEarned = JcciTitles T.InterestEarned+pattern ReceiptFee = JcciTitles T.ReceiptFee+pattern RentalIncome = JcciTitles T.RentalIncome+pattern Sales = JcciTitles T.Sales+pattern EquityInEarningsOfInvestee = JcciTitles T.EquityInEarningsOfInvestee+pattern NetLoss = JcciTitles T.NetLoss+pattern PettyCash = JcciTitles T.PettyCash+pattern NotesReceivable = JcciTitles T.NotesReceivable+pattern ElectronicallyRecordedReceivable = JcciTitles T.ElectronicallyRecordedReceivable+pattern CreditCardReceivable = JcciTitles T.CreditCardReceivable+pattern NotesLoansReceivable = JcciTitles T.NotesLoansReceivable+pattern MerchandiseInventory = JcciTitles T.MerchandiseInventory+pattern AdvancesPaid = JcciTitles T.AdvancesPaid+pattern PrepaidExpenses = JcciTitles T.PrepaidExpenses+pattern AccruedRevenue = JcciTitles T.AccruedRevenue+pattern OtherReceivables = JcciTitles T.OtherReceivables+pattern PaymentsOnBehalf = JcciTitles T.PaymentsOnBehalf+pattern SuspensePayments = JcciTitles T.SuspensePayments+pattern ConsumptionTaxPaid = JcciTitles T.ConsumptionTaxPaid+pattern PrepaidCorporateIncomeTaxes = JcciTitles T.PrepaidCorporateIncomeTaxes+pattern Land = JcciTitles T.Land+pattern Fixtures = JcciTitles T.Fixtures+pattern Patent = JcciTitles T.Patent+pattern Trademark = JcciTitles T.Trademark+pattern Software = JcciTitles T.Software+pattern CashOverShort = JcciTitles T.CashOverShort+pattern AccountsPayable = JcciTitles T.AccountsPayable+pattern NotesPayable = JcciTitles T.NotesPayable+pattern ElectronicallyRecordedObligations = JcciTitles T.ElectronicallyRecordedObligations+pattern NotesLoansPayable = JcciTitles T.NotesLoansPayable+pattern BankOverdraft = JcciTitles T.BankOverdraft+pattern AdvancesReceived = JcciTitles T.AdvancesReceived+pattern UnearnedRevenue = JcciTitles T.UnearnedRevenue+pattern AccruedExpenses = JcciTitles T.AccruedExpenses+pattern OtherPayables = JcciTitles T.OtherPayables+pattern DepositsReceived = JcciTitles T.DepositsReceived+pattern SuspenseReceipts = JcciTitles T.SuspenseReceipts+pattern ConsumptionTaxReceived = JcciTitles T.ConsumptionTaxReceived+pattern AccruedConsumptionTax = JcciTitles T.AccruedConsumptionTax+pattern AccruedCorporateIncomeTaxes = JcciTitles T.AccruedCorporateIncomeTaxes+pattern UnpaidDividends = JcciTitles T.UnpaidDividends+pattern AllowanceForDoubtfulAccounts = JcciTitles T.AllowanceForDoubtfulAccounts+pattern AccumulatedDepreciation = JcciTitles T.AccumulatedDepreciation+pattern LegalRetainedEarnings = JcciTitles T.LegalRetainedEarnings+pattern CumulativeTranslationAdjustment = JcciTitles T.CumulativeTranslationAdjustment+pattern ProvisionForDoubtfulAccounts = JcciTitles T.ProvisionForDoubtfulAccounts+pattern BadDebtLoss = JcciTitles T.BadDebtLoss+pattern LossOnSalesOfFixedAssets = JcciTitles T.LossOnSalesOfFixedAssets+pattern LossOnSalesOfNotesReceivable = JcciTitles T.LossOnSalesOfNotesReceivable+pattern PaymentFees = JcciTitles T.PaymentFees+pattern MiscellaneousLoss = JcciTitles T.MiscellaneousLoss+pattern CorporateIncomeTaxes = JcciTitles T.CorporateIncomeTaxes+pattern CommunicationExpenses = JcciTitles T.CommunicationExpenses+pattern GainOnSalesOfFixedAssets = JcciTitles T.GainOnSalesOfFixedAssets+pattern RecoveryOfBadDebts = JcciTitles T.RecoveryOfBadDebts+pattern MiscellaneousIncome = JcciTitles T.MiscellaneousIncome+pattern ReversalOfAllowanceForDoubtfulAccounts = JcciTitles T.ReversalOfAllowanceForDoubtfulAccounts+pattern TimeDeposits = JcciTitles T.TimeDeposits+pattern LoansReceivable = JcciTitles T.LoansReceivable+pattern GiftCertificatesReceived = JcciTitles T.GiftCertificatesReceived+pattern SecurityDepositsPaid = JcciTitles T.SecurityDepositsPaid+pattern SuppliesOnHand = JcciTitles T.SuppliesOnHand+pattern ContractAssets = JcciTitles T.ContractAssets+pattern IncomeTaxesRefundReceivable = JcciTitles T.IncomeTaxesRefundReceivable+pattern WorkInProcess = JcciTitles T.WorkInProcess+pattern DeferredTaxAssets = JcciTitles T.DeferredTaxAssets+pattern LeasedAssets = JcciTitles T.LeasedAssets+pattern ToolsAndInstruments = JcciTitles T.ToolsAndInstruments+pattern ConstructionInProgress = JcciTitles T.ConstructionInProgress+pattern Goodwill = JcciTitles T.Goodwill+pattern SoftwareInProgress = JcciTitles T.SoftwareInProgress+pattern LongTermPrepaidExpenses = JcciTitles T.LongTermPrepaidExpenses+pattern DishonoredNotesReceivable = JcciTitles T.DishonoredNotesReceivable+pattern PrepaidPensionCost = JcciTitles T.PrepaidPensionCost+pattern NetDefinedBenefitAsset = JcciTitles T.NetDefinedBenefitAsset+pattern DepositsInSpecialAccounts = JcciTitles T.DepositsInSpecialAccounts+pattern Structures = JcciTitles T.Structures+pattern LeaseholdRights = JcciTitles T.LeaseholdRights+pattern NonOperatingNotesReceivable = JcciTitles T.NonOperatingNotesReceivable+pattern NonOperatingElectronicallyRecordedReceivable =+ JcciTitles T.NonOperatingElectronicallyRecordedReceivable+pattern RefundLiabilities = JcciTitles T.RefundLiabilities+pattern NonOperatingNotesPayable = JcciTitles T.NonOperatingNotesPayable+pattern NonOperatingElectronicallyRecordedObligations =+ JcciTitles T.NonOperatingElectronicallyRecordedObligations+pattern BonusesPayable = JcciTitles T.BonusesPayable+pattern AllowanceForRepairs = JcciTitles T.AllowanceForRepairs+pattern AllowanceForProductWarranties = JcciTitles T.AllowanceForProductWarranties+pattern AllowanceForBonuses = JcciTitles T.AllowanceForBonuses+pattern DeferredTaxLiabilities = JcciTitles T.DeferredTaxLiabilities+pattern LeaseObligations = JcciTitles T.LeaseObligations+pattern GuaranteeDepositsReceived = JcciTitles T.GuaranteeDepositsReceived+pattern AllowanceForRetirementBenefits = JcciTitles T.AllowanceForRetirementBenefits+pattern LongTermOtherPayables = JcciTitles T.LongTermOtherPayables+pattern NetDefinedBenefitLiability = JcciTitles T.NetDefinedBenefitLiability+pattern StockSubscriptionDeposits = JcciTitles T.StockSubscriptionDeposits+pattern LegalCapitalSurplus = JcciTitles T.LegalCapitalSurplus+pattern OtherCapitalSurplus = JcciTitles T.OtherCapitalSurplus+pattern DividendEqualizationReserve = JcciTitles T.DividendEqualizationReserve+pattern RepairFundReserve = JcciTitles T.RepairFundReserve+pattern ConstructionFundReserve = JcciTitles T.ConstructionFundReserve+pattern GeneralReserve = JcciTitles T.GeneralReserve+pattern ValuationDifferenceOnOtherSecurities = JcciTitles T.ValuationDifferenceOnOtherSecurities+pattern NonControllingInterests = JcciTitles T.NonControllingInterests+pattern CapitalSurplus = JcciTitles T.CapitalSurplus+pattern EarnedSurplus = JcciTitles T.EarnedSurplus+pattern ServiceRevenue = JcciTitles T.ServiceRevenue+pattern OperatingRevenue = JcciTitles T.OperatingRevenue+pattern GainOnSalesOfSecurities = JcciTitles T.GainOnSalesOfSecurities+pattern GainOnValuationOfSecurities = JcciTitles T.GainOnValuationOfSecurities+pattern DividendsReceived = JcciTitles T.DividendsReceived+pattern InterestOnSecurities = JcciTitles T.InterestOnSecurities+pattern GainOnSalesOfInvestmentSecurities = JcciTitles T.GainOnSalesOfInvestmentSecurities+pattern InsuranceGain = JcciTitles T.InsuranceGain+pattern GainOnBargainPurchase = JcciTitles T.GainOnBargainPurchase+pattern ReversalOfAllowanceForRepairs = JcciTitles T.ReversalOfAllowanceForRepairs+pattern ReversalOfAllowanceForProductWarranties =+ JcciTitles T.ReversalOfAllowanceForProductWarranties+pattern GainOnDonationOfFixedAssets = JcciTitles T.GainOnDonationOfFixedAssets+pattern GainOnNationalSubsidies = JcciTitles T.GainOnNationalSubsidies+pattern GainOnConstructionGrants = JcciTitles T.GainOnConstructionGrants+pattern LandRentReceived = JcciTitles T.LandRentReceived+pattern SalesRebates = JcciTitles T.SalesRebates+pattern CostOfServices = JcciTitles T.CostOfServices+pattern OperatingExpenses = JcciTitles T.OperatingExpenses+pattern InventoryShrinkageLoss = JcciTitles T.InventoryShrinkageLoss+pattern LossOnValuationOfMerchandise = JcciTitles T.LossOnValuationOfMerchandise+pattern Bonuses = JcciTitles T.Bonuses+pattern RetirementBenefitExpenses = JcciTitles T.RetirementBenefitExpenses+pattern ProvisionForRepairs = JcciTitles T.ProvisionForRepairs+pattern ProvisionForBonuses = JcciTitles T.ProvisionForBonuses+pattern ProvisionForProductWarranties = JcciTitles T.ProvisionForProductWarranties+pattern ResearchAndDevelopmentExpenses = JcciTitles T.ResearchAndDevelopmentExpenses+pattern AmortizationOfGoodwill = JcciTitles T.AmortizationOfGoodwill+pattern AmortizationOfSoftware = JcciTitles T.AmortizationOfSoftware+pattern AmortizationOfPatents = JcciTitles T.AmortizationOfPatents+pattern LeaseExpenses = JcciTitles T.LeaseExpenses+pattern IncorporationExpenses = JcciTitles T.IncorporationExpenses+pattern StockIssuanceCosts = JcciTitles T.StockIssuanceCosts+pattern BusinessCommencementExpenses = JcciTitles T.BusinessCommencementExpenses+pattern DevelopmentExpenses = JcciTitles T.DevelopmentExpenses+pattern LossOnSalesOfElectronicallyRecordedReceivables =+ JcciTitles T.LossOnSalesOfElectronicallyRecordedReceivables+pattern LossOnSalesOfReceivables = JcciTitles T.LossOnSalesOfReceivables+pattern LossOnSalesOfSecurities = JcciTitles T.LossOnSalesOfSecurities+pattern LossOnValuationOfSecurities = JcciTitles T.LossOnValuationOfSecurities+pattern LossOnSalesOfInvestmentSecurities = JcciTitles T.LossOnSalesOfInvestmentSecurities+pattern LossOnFire = JcciTitles T.LossOnFire+pattern LossOnRetirementOfFixedAssets = JcciTitles T.LossOnRetirementOfFixedAssets+pattern LossOnReductionOfFixedAssets = JcciTitles T.LossOnReductionOfFixedAssets+pattern AdditionalIncomeTaxesForPriorPeriods = JcciTitles T.AdditionalIncomeTaxesForPriorPeriods+pattern RefundOfIncomeTaxes = JcciTitles T.RefundOfIncomeTaxes+pattern PurchaseRebates = JcciTitles T.PurchaseRebates+pattern WelfareExpenses = JcciTitles T.WelfareExpenses+pattern MaintenanceExpenses = JcciTitles T.MaintenanceExpenses+pattern StatutoryWelfareExpenses = JcciTitles T.StatutoryWelfareExpenses+pattern LandRentPaid = JcciTitles T.LandRentPaid+pattern InsuranceExpense = JcciTitles T.InsuranceExpense+pattern RepairsExpense = JcciTitles T.RepairsExpense+pattern StorageExpenses = JcciTitles T.StorageExpenses+pattern MembershipFees = JcciTitles T.MembershipFees+pattern IncomeSummary = JcciTitles T.IncomeSummary+pattern SuspenseAccount = JcciTitles T.SuspenseAccount+pattern ForeignExchangeGains = JcciTitles T.ForeignExchangeGains+pattern ForeignExchangeLosses = JcciTitles T.ForeignExchangeLosses+pattern ContraAccountForGuaranteeObligations = JcciTitles T.ContraAccountForGuaranteeObligations+pattern GuaranteeObligations = JcciTitles T.GuaranteeObligations+pattern IncomeTaxesAdjustment = JcciTitles T.IncomeTaxesAdjustment+pattern BranchCurrentAccount = JcciTitles T.BranchCurrentAccount+pattern HeadOfficeCurrentAccount = JcciTitles T.HeadOfficeCurrentAccount+pattern NetIncomeAttributableToNCI = JcciTitles T.NetIncomeAttributableToNCI+pattern NetLossAttributableToNCI = JcciTitles T.NetLossAttributableToNCI+pattern TradingSecurities = JcciTitles T.TradingSecurities+pattern HeldToMaturityBonds = JcciTitles T.HeldToMaturityBonds+pattern SubsidiaryStocks = JcciTitles T.SubsidiaryStocks+pattern AffiliateStocks = JcciTitles T.AffiliateStocks+pattern AvailableForSaleSecurities = JcciTitles T.AvailableForSaleSecurities+pattern ConsumptionTaxRefundReceivable = JcciTitles T.ConsumptionTaxRefundReceivable+pattern PropertyTaxPayable = JcciTitles T.PropertyTaxPayable+pattern DepositsReceivedFromOfficers = JcciTitles T.DepositsReceivedFromOfficers+pattern EntertainmentExpenses = JcciTitles T.EntertainmentExpenses+pattern MeetingExpenses = JcciTitles T.MeetingExpenses+pattern NewspaperBooksExpenses = JcciTitles T.NewspaperBooksExpenses+pattern RawMaterials = JcciTitles T.RawMaterials+pattern GoodsInTransit = JcciTitles T.GoodsInTransit+pattern SalesAllowances = JcciTitles T.SalesAllowances+pattern PurchaseAllowances = JcciTitles T.PurchaseAllowances+pattern ReversalOfAllowanceForBonuses = JcciTitles T.ReversalOfAllowanceForBonuses+pattern DirectorsCompensations = JcciTitles T.DirectorsCompensations++-- | Wildcard for a JCCI account title.+pattern AnyJcci :: JcciTitles+pattern AnyJcci = JcciTitles T.AccountTitle++{-# COMPLETE Cash+ , Deposits+ , CurrentDeposits+ , Securities+ , InvestmentSecurities+ , InvestmentInAssociate+ , LongTermNationalBonds+ , ShortTermNationalBonds+ , Products+ , Machinery+ , Building+ , Vehicle+ , StockInvestment+ , EquipmentInvestment+ , LongTermLoansReceivable+ , AccountsReceivable+ , ShortTermLoansReceivable+ , Gold+ , CapitalStock+ , RetainedEarnings+ , LongTermLoansPayable+ , ShortTermLoansPayable+ , LoansPayable+ , LongTermNationalBondsPayable+ , ShortTermNationalBondsPayable+ , Depreciation+ , AmortizationExpense+ , SalesCost+ , BusinessTrip+ , UtilitiesExpense+ , RentExpense+ , AdvertisingExpense+ , DeliveryExpenses+ , SuppliesExpenses+ , MiscellaneousExpenses+ , WageExpenditure+ , InterestExpense+ , TaxesExpense+ , Purchases+ , NetIncome+ , NationalBondInterestEarned+ , DepositInterestEarned+ , GrossProfit+ , OrdinaryProfit+ , InterestEarned+ , ReceiptFee+ , RentalIncome+ , Sales+ , EquityInEarningsOfInvestee+ , NetLoss+ , PettyCash+ , NotesReceivable+ , ElectronicallyRecordedReceivable+ , CreditCardReceivable+ , NotesLoansReceivable+ , MerchandiseInventory+ , AdvancesPaid+ , PrepaidExpenses+ , AccruedRevenue+ , OtherReceivables+ , PaymentsOnBehalf+ , SuspensePayments+ , ConsumptionTaxPaid+ , PrepaidCorporateIncomeTaxes+ , Land+ , Fixtures+ , Patent+ , Trademark+ , Software+ , CashOverShort+ , AccountsPayable+ , NotesPayable+ , ElectronicallyRecordedObligations+ , NotesLoansPayable+ , BankOverdraft+ , AdvancesReceived+ , UnearnedRevenue+ , AccruedExpenses+ , OtherPayables+ , DepositsReceived+ , SuspenseReceipts+ , ConsumptionTaxReceived+ , AccruedConsumptionTax+ , AccruedCorporateIncomeTaxes+ , UnpaidDividends+ , AllowanceForDoubtfulAccounts+ , AccumulatedDepreciation+ , LegalRetainedEarnings+ , CumulativeTranslationAdjustment+ , ProvisionForDoubtfulAccounts+ , BadDebtLoss+ , LossOnSalesOfFixedAssets+ , LossOnSalesOfNotesReceivable+ , PaymentFees+ , MiscellaneousLoss+ , CorporateIncomeTaxes+ , CommunicationExpenses+ , GainOnSalesOfFixedAssets+ , RecoveryOfBadDebts+ , MiscellaneousIncome+ , ReversalOfAllowanceForDoubtfulAccounts+ , TimeDeposits+ , LoansReceivable+ , GiftCertificatesReceived+ , SecurityDepositsPaid+ , SuppliesOnHand+ , ContractAssets+ , IncomeTaxesRefundReceivable+ , WorkInProcess+ , DeferredTaxAssets+ , LeasedAssets+ , ToolsAndInstruments+ , ConstructionInProgress+ , Goodwill+ , SoftwareInProgress+ , LongTermPrepaidExpenses+ , DishonoredNotesReceivable+ , PrepaidPensionCost+ , NetDefinedBenefitAsset+ , DepositsInSpecialAccounts+ , Structures+ , LeaseholdRights+ , NonOperatingNotesReceivable+ , NonOperatingElectronicallyRecordedReceivable+ , RefundLiabilities+ , NonOperatingNotesPayable+ , NonOperatingElectronicallyRecordedObligations+ , BonusesPayable+ , AllowanceForRepairs+ , AllowanceForProductWarranties+ , AllowanceForBonuses+ , DeferredTaxLiabilities+ , LeaseObligations+ , GuaranteeDepositsReceived+ , AllowanceForRetirementBenefits+ , LongTermOtherPayables+ , NetDefinedBenefitLiability+ , StockSubscriptionDeposits+ , LegalCapitalSurplus+ , OtherCapitalSurplus+ , DividendEqualizationReserve+ , RepairFundReserve+ , ConstructionFundReserve+ , GeneralReserve+ , ValuationDifferenceOnOtherSecurities+ , NonControllingInterests+ , CapitalSurplus+ , EarnedSurplus+ , ServiceRevenue+ , OperatingRevenue+ , GainOnSalesOfSecurities+ , GainOnValuationOfSecurities+ , DividendsReceived+ , InterestOnSecurities+ , GainOnSalesOfInvestmentSecurities+ , InsuranceGain+ , GainOnBargainPurchase+ , ReversalOfAllowanceForRepairs+ , ReversalOfAllowanceForProductWarranties+ , GainOnDonationOfFixedAssets+ , GainOnNationalSubsidies+ , GainOnConstructionGrants+ , LandRentReceived+ , SalesRebates+ , CostOfServices+ , OperatingExpenses+ , InventoryShrinkageLoss+ , LossOnValuationOfMerchandise+ , Bonuses+ , RetirementBenefitExpenses+ , ProvisionForRepairs+ , ProvisionForBonuses+ , ProvisionForProductWarranties+ , ResearchAndDevelopmentExpenses+ , AmortizationOfGoodwill+ , AmortizationOfSoftware+ , AmortizationOfPatents+ , LeaseExpenses+ , IncorporationExpenses+ , StockIssuanceCosts+ , BusinessCommencementExpenses+ , DevelopmentExpenses+ , LossOnSalesOfElectronicallyRecordedReceivables+ , LossOnSalesOfReceivables+ , LossOnSalesOfSecurities+ , LossOnValuationOfSecurities+ , LossOnSalesOfInvestmentSecurities+ , LossOnFire+ , LossOnRetirementOfFixedAssets+ , LossOnReductionOfFixedAssets+ , AdditionalIncomeTaxesForPriorPeriods+ , RefundOfIncomeTaxes+ , PurchaseRebates+ , WelfareExpenses+ , MaintenanceExpenses+ , StatutoryWelfareExpenses+ , LandRentPaid+ , InsuranceExpense+ , RepairsExpense+ , StorageExpenses+ , MembershipFees+ , IncomeSummary+ , SuspenseAccount+ , ForeignExchangeGains+ , ForeignExchangeLosses+ , ContraAccountForGuaranteeObligations+ , GuaranteeObligations+ , IncomeTaxesAdjustment+ , BranchCurrentAccount+ , HeadOfficeCurrentAccount+ , NetIncomeAttributableToNCI+ , NetLossAttributableToNCI+ , TradingSecurities+ , HeldToMaturityBonds+ , SubsidiaryStocks+ , AffiliateStocks+ , AvailableForSaleSecurities+ , ConsumptionTaxRefundReceivable+ , PropertyTaxPayable+ , DepositsReceivedFromOfficers+ , EntertainmentExpenses+ , MeetingExpenses+ , NewspaperBooksExpenses+ , RawMaterials+ , GoodsInTransit+ , SalesAllowances+ , PurchaseAllowances+ , ReversalOfAllowanceForBonuses+ , DirectorsCompensations+ , AnyJcci :: JcciTitles+ #-}
src/ExchangeAlgebra/Accounting/Account/PostingPolicy.hs view
@@ -5,7 +5,7 @@ Description : Accounting-domain posting authority for processing contexts. Accounting-domain posting authority: which account titles may be used in which-processing context. Input adapters ("ExchangeAlgebra.Convert.Checked") and the+processing context. Input adapters ("ExchangeAlgebra.IO.Input.Checked") and the consolidation worksheet ("ExchangeAlgebra.Accounting.Consolidation") consume this; it does not depend on either.
src/ExchangeAlgebra/Accounting/Account/Registry.hs view
@@ -1,4044 +1,61 @@-{-# LANGUAGE OverloadedStrings #-}-{-# OPTIONS_GHC -Wincomplete-patterns -Werror=incomplete-patterns #-}--- The exhaustive registry intentionally retains the deprecated Commutation--- constructor so that legacy behavior remains byte-for-byte stable.-{-# OPTIONS_GHC -Wno-deprecations #-}--{- |-Module : ExchangeAlgebra.Accounting.Account.Registry-Description : Canonical metadata registry for concrete account titles.--The exhaustive 'accountSpec' case is the single source of truth for account-classification, fixed/current status, and bilingual descriptions. 'accountAliases'-combines its base aliases with the frozen JCCI 2022 standard/permitted-name overlay.--}-module ExchangeAlgebra.Accounting.Account.Registry- ( AccountSpec(..)- , AccountSemantics(..)- , accountAliases- , accountSpec- , accountSemantics- , accountSpecMap- , concreteAccountTitles- , classifyAccountContra- , accountDescriptions- ) where--import qualified Data.List as L-import qualified Data.Map.Strict as M-import Data.Map.Strict (Map)-import Data.Maybe (mapMaybe)-import Data.Text (Text)--import ExchangeAlgebra.Accounting.Account.Classification- ( AccountDivision(..), AccountRole(..), ClosingRule(..)- , DivisionSemantics(..), FixedCurrent(..), HomeSideSemantics(..)- , PostingCapability(..), ReportingEligibility(..), Side(..) )-import ExchangeAlgebra.Accounting.Account.Aliases (jcciAliases)-import ExchangeAlgebra.Accounting.Account.Title (AccountTitles(..))---- | All metadata attached to one concrete account title.-data AccountSpec = AccountSpec- { asDivision :: AccountDivision- , asClosing :: ClosingRule- -- ^ Automatic closing policy. 'NetIncome' and 'NetLoss' are explicit- -- 'NoClose' overrides: their division describes the P\/L presentation- -- side, so division-derived closing would reverse their intended side.- -- GrossProfit and OrdinaryProfit retain CloseByDivision for staged- -- closing. Statement metrics live in- -- "ExchangeAlgebra.Accounting.Statements.Metric".- , asIsContra :: Bool- , asFixedCurrent :: FixedCurrent- , asNameEn :: Text- , asNameJa :: Text- -- | Annotation-free Japanese display label (清書和文表示名) used for- -- financial-statement lines- -- ('ExchangeAlgebra.Accounting.Statements.Presentation.presentationLabel') and LLM-facing- -- names ('ExchangeAlgebra.Assist.safeNameJa'). Unlike 'asNameJa' it never- -- carries notes, legacy-name- -- remarks, or constructor identifiers; the JCCI level-2 A-column sweep in- -- the test suite pins it against the official standard names.- , asLabelJa :: Text- , asDescription :: Text- -- | Registry-local aliases only. Use 'accountAliases' when constructing a- -- parser or UI: that function also includes the frozen JCCI overlay.- , asAliases :: [Text]- } deriving (Show, Eq)---- | Processing and reporting semantics attached to a concrete account title.------ This record deliberately does not replace 'AccountSpec.asDivision'. The--- legacy division remains the exchange-algebra direction input, while this--- layer states whether that value is a financial-statement classification,--- a bookkeeping control class, or only an internal direction encoding.-data AccountSemantics = AccountSemantics- { asemRoles :: [AccountRole]- , asemPostingCapability :: PostingCapability- , asemDivisionSemantics :: DivisionSemantics- , asemHomeSideSemantics :: HomeSideSemantics- , asemReportingEligibility :: ReportingEligibility- } deriving (Show, Eq)---- | All concrete account titles in their stable Enum order.-concreteAccountTitles :: [AccountTitles]-concreteAccountTitles = filter (/= AccountTitle) [minBound .. maxBound]---- | Look up processing and reporting semantics for a concrete account title.--- The wildcard 'AccountTitle' is outside the metadata domain and returns--- 'Nothing' explicitly.-accountSemantics :: AccountTitles -> Maybe AccountSemantics-accountSemantics title = do- spec <- accountSpec title- pure AccountSemantics- { asemRoles = rolesFor title spec- , asemPostingCapability = postingFor title- , asemDivisionSemantics = divisionFor title spec- , asemHomeSideSemantics = homeSideFor title spec- , asemReportingEligibility = reportingFor title- }--rolesFor :: AccountTitles -> AccountSpec -> [AccountRole]-rolesFor title _ = case title of- Cash -> [OrdinaryAccount]- Deposits -> [OrdinaryAccount]- CurrentDeposits -> [OrdinaryAccount]- Securities -> [OrdinaryAccount]- InvestmentSecurities -> [OrdinaryAccount]- InvestmentInAssociate -> [OrdinaryAccount]- LongTermNationalBonds -> [OrdinaryAccount]- ShortTermNationalBonds -> [OrdinaryAccount]- Products -> [OrdinaryAccount]- Machinery -> [OrdinaryAccount]- Building -> [OrdinaryAccount]- Vehicle -> [OrdinaryAccount]- StockInvestment -> [OrdinaryAccount]- EquipmentInvestment -> [OrdinaryAccount]- LongTermLoansReceivable -> [OrdinaryAccount]- AccountsReceivable -> [OrdinaryAccount]- ShortTermLoansReceivable -> [OrdinaryAccount]- ReserveDepositReceivable -> [OrdinaryAccount]- Gold -> [OrdinaryAccount]- GovernmentService -> [OrdinaryAccount]- CapitalStock -> [OrdinaryAccount]- RetainedEarnings -> [OrdinaryAccount]- LongTermLoansPayable -> [OrdinaryAccount]- ShortTermLoansPayable -> [OrdinaryAccount]- LoansPayable -> [OrdinaryAccount]- ReserveForDepreciation -> [OrdinaryAccount]- DepositPayable -> [OrdinaryAccount]- LongTermNationalBondsPayable -> [OrdinaryAccount]- ShortTermNationalBondsPayable -> [OrdinaryAccount]- ReserveDepositPayable -> [OrdinaryAccount]- CentralBankNotePayable -> [OrdinaryAccount]- Depreciation -> [OrdinaryAccount]- AmortizationExpense -> [OrdinaryAccount]- SalesCost -> [OrdinaryAccount]- BusinessTrip -> [OrdinaryAccount]- Commutation -> [OrdinaryAccount]- UtilitiesExpense -> [OrdinaryAccount]- RentExpense -> [OrdinaryAccount]- AdvertisingExpense -> [OrdinaryAccount]- DeliveryExpenses -> [OrdinaryAccount]- SuppliesExpenses -> [OrdinaryAccount]- MiscellaneousExpenses -> [OrdinaryAccount]- EntertainmentExpenses -> [OrdinaryAccount]- MeetingExpenses -> [OrdinaryAccount]- NewspaperBooksExpenses -> [OrdinaryAccount]- WageExpenditure -> [OrdinaryAccount]- InterestExpense -> [OrdinaryAccount]- TaxesExpense -> [OrdinaryAccount]- ConsumptionExpenditure -> [OrdinaryAccount]- SubsidyExpense -> [OrdinaryAccount]- CentralBankPaymentExpense -> [OrdinaryAccount]- Purchases -> [OrdinaryAccount]- NetIncome -> [PeriodResult]- ValueAdded -> [OrdinaryAccount]- SubsidyIncome -> [OrdinaryAccount]- NationalBondInterestEarned -> [OrdinaryAccount]- DepositInterestEarned -> [OrdinaryAccount]- GrossProfit -> [ReportingSubtotal]- OrdinaryProfit -> [ReportingSubtotal]- InterestEarned -> [OrdinaryAccount]- ReceiptFee -> [OrdinaryAccount]- RentalIncome -> [OrdinaryAccount]- WageEarned -> [OrdinaryAccount]- TaxesRevenue -> [OrdinaryAccount]- CentralBankPaymentIncome -> [OrdinaryAccount]- Sales -> [OrdinaryAccount]- EquityInEarningsOfInvestee -> [OrdinaryAccount]- NetLoss -> [PeriodResult]- PettyCash -> [OrdinaryAccount]- NotesReceivable -> [OrdinaryAccount]- ElectronicallyRecordedReceivable -> [OrdinaryAccount]- CreditCardReceivable -> [OrdinaryAccount]- NotesLoansReceivable -> [OrdinaryAccount]- MerchandiseInventory -> [OrdinaryAccount]- GoodsInTransit -> [OrdinaryAccount]- AdvancesPaid -> [OrdinaryAccount]- PrepaidExpenses -> [OrdinaryAccount]- AccruedRevenue -> [OrdinaryAccount]- OtherReceivables -> [OrdinaryAccount]- PaymentsOnBehalf -> [OrdinaryAccount]- SuspensePayments -> [SuspenseOrClearingAccount]- ConsumptionTaxPaid -> [OrdinaryAccount]- PrepaidCorporateIncomeTaxes -> [OrdinaryAccount]- Land -> [OrdinaryAccount]- Fixtures -> [OrdinaryAccount]- Patent -> [OrdinaryAccount]- Trademark -> [OrdinaryAccount]- Software -> [OrdinaryAccount]- CashOverShort -> [SuspenseOrClearingAccount]- AccountsPayable -> [OrdinaryAccount]- NotesPayable -> [OrdinaryAccount]- ElectronicallyRecordedObligations -> [OrdinaryAccount]- NotesLoansPayable -> [OrdinaryAccount]- BankOverdraft -> [OrdinaryAccount]- AdvancesReceived -> [OrdinaryAccount]- UnearnedRevenue -> [OrdinaryAccount]- AccruedExpenses -> [OrdinaryAccount]- OtherPayables -> [OrdinaryAccount]- DepositsReceived -> [OrdinaryAccount]- SuspenseReceipts -> [SuspenseOrClearingAccount]- ConsumptionTaxReceived -> [OrdinaryAccount]- AccruedConsumptionTax -> [OrdinaryAccount]- AccruedCorporateIncomeTaxes -> [OrdinaryAccount]- UnpaidDividends -> [OrdinaryAccount]- AllowanceForDoubtfulAccounts -> [OrdinaryAccount, ContraAccount]- AccumulatedDepreciation -> [OrdinaryAccount, ContraAccount]- LegalRetainedEarnings -> [OrdinaryAccount]- CumulativeTranslationAdjustment -> [OrdinaryAccount]- ProvisionForDoubtfulAccounts -> [OrdinaryAccount]- BadDebtLoss -> [OrdinaryAccount]- LossOnSalesOfFixedAssets -> [OrdinaryAccount]- LossOnSalesOfNotesReceivable -> [OrdinaryAccount]- PaymentFees -> [OrdinaryAccount]- MiscellaneousLoss -> [OrdinaryAccount]- CorporateIncomeTaxes -> [OrdinaryAccount]- CommunicationExpenses -> [OrdinaryAccount]- GainOnSalesOfFixedAssets -> [OrdinaryAccount]- RecoveryOfBadDebts -> [OrdinaryAccount]- MiscellaneousIncome -> [OrdinaryAccount]- ReversalOfAllowanceForDoubtfulAccounts -> [OrdinaryAccount]- TimeDeposits -> [OrdinaryAccount]- LoansReceivable -> [OrdinaryAccount]- GiftCertificatesReceived -> [OrdinaryAccount]- SecurityDepositsPaid -> [OrdinaryAccount]- SuppliesOnHand -> [OrdinaryAccount]- RawMaterials -> [OrdinaryAccount]- ContractAssets -> [OrdinaryAccount]- IncomeTaxesRefundReceivable -> [OrdinaryAccount]- WorkInProcess -> [OrdinaryAccount]- DeferredTaxAssets -> [OrdinaryAccount]- LeasedAssets -> [OrdinaryAccount]- ToolsAndInstruments -> [OrdinaryAccount]- ConstructionInProgress -> [OrdinaryAccount]- Goodwill -> [OrdinaryAccount]- SoftwareInProgress -> [OrdinaryAccount]- LongTermPrepaidExpenses -> [OrdinaryAccount]- DishonoredNotesReceivable -> [OrdinaryAccount]- PrepaidPensionCost -> [OrdinaryAccount]- NetDefinedBenefitAsset -> [OrdinaryAccount]- DepositsInSpecialAccounts -> [OrdinaryAccount]- Structures -> [OrdinaryAccount]- LeaseholdRights -> [OrdinaryAccount]- NonOperatingNotesReceivable -> [OrdinaryAccount]- NonOperatingElectronicallyRecordedReceivable -> [OrdinaryAccount]- RefundLiabilities -> [OrdinaryAccount]- NonOperatingNotesPayable -> [OrdinaryAccount]- NonOperatingElectronicallyRecordedObligations -> [OrdinaryAccount]- BonusesPayable -> [OrdinaryAccount]- AllowanceForRepairs -> [OrdinaryAccount]- AllowanceForProductWarranties -> [OrdinaryAccount]- AllowanceForBonuses -> [OrdinaryAccount]- DeferredTaxLiabilities -> [OrdinaryAccount]- LeaseObligations -> [OrdinaryAccount]- GuaranteeDepositsReceived -> [OrdinaryAccount]- AllowanceForRetirementBenefits -> [OrdinaryAccount]- LongTermOtherPayables -> [OrdinaryAccount]- NetDefinedBenefitLiability -> [OrdinaryAccount]- StockSubscriptionDeposits -> [OrdinaryAccount]- LegalCapitalSurplus -> [OrdinaryAccount]- OtherCapitalSurplus -> [OrdinaryAccount]- DividendEqualizationReserve -> [OrdinaryAccount]- RepairFundReserve -> [OrdinaryAccount]- ConstructionFundReserve -> [OrdinaryAccount]- GeneralReserve -> [OrdinaryAccount]- ValuationDifferenceOnOtherSecurities -> [OrdinaryAccount]- NonControllingInterests -> [AttributionAccount]- CapitalSurplus -> [OrdinaryAccount]- EarnedSurplus -> [OrdinaryAccount]- ServiceRevenue -> [OrdinaryAccount]- OperatingRevenue -> [OrdinaryAccount]- GainOnSalesOfSecurities -> [OrdinaryAccount]- GainOnValuationOfSecurities -> [OrdinaryAccount]- DividendsReceived -> [OrdinaryAccount]- InterestOnSecurities -> [OrdinaryAccount]- GainOnSalesOfInvestmentSecurities -> [OrdinaryAccount]- InsuranceGain -> [OrdinaryAccount]- GainOnBargainPurchase -> [OrdinaryAccount]- ReversalOfAllowanceForRepairs -> [OrdinaryAccount]- ReversalOfAllowanceForBonuses -> [OrdinaryAccount]- ReversalOfAllowanceForProductWarranties -> [OrdinaryAccount]- GainOnDonationOfFixedAssets -> [OrdinaryAccount]- GainOnNationalSubsidies -> [OrdinaryAccount]- GainOnConstructionGrants -> [OrdinaryAccount]- LandRentReceived -> [OrdinaryAccount]- SalesRebates -> [OrdinaryAccount, ContraAccount]- SalesAllowances -> [OrdinaryAccount, ContraAccount]- CostOfServices -> [OrdinaryAccount]- OperatingExpenses -> [OrdinaryAccount]- InventoryShrinkageLoss -> [OrdinaryAccount]- LossOnValuationOfMerchandise -> [OrdinaryAccount]- Bonuses -> [OrdinaryAccount]- RetirementBenefitExpenses -> [OrdinaryAccount]- ProvisionForRepairs -> [OrdinaryAccount]- ProvisionForBonuses -> [OrdinaryAccount]- ProvisionForProductWarranties -> [OrdinaryAccount]- ResearchAndDevelopmentExpenses -> [OrdinaryAccount]- AmortizationOfGoodwill -> [OrdinaryAccount]- AmortizationOfSoftware -> [OrdinaryAccount]- AmortizationOfPatents -> [OrdinaryAccount]- LeaseExpenses -> [OrdinaryAccount]- IncorporationExpenses -> [OrdinaryAccount]- StockIssuanceCosts -> [OrdinaryAccount]- BusinessCommencementExpenses -> [OrdinaryAccount]- DevelopmentExpenses -> [OrdinaryAccount]- LossOnSalesOfElectronicallyRecordedReceivables -> [OrdinaryAccount]- LossOnSalesOfReceivables -> [OrdinaryAccount]- LossOnSalesOfSecurities -> [OrdinaryAccount]- LossOnValuationOfSecurities -> [OrdinaryAccount]- LossOnSalesOfInvestmentSecurities -> [OrdinaryAccount]- LossOnFire -> [OrdinaryAccount]- LossOnRetirementOfFixedAssets -> [OrdinaryAccount]- LossOnReductionOfFixedAssets -> [OrdinaryAccount]- AdditionalIncomeTaxesForPriorPeriods -> [OrdinaryAccount]- RefundOfIncomeTaxes -> [OrdinaryAccount, ContraAccount]- PurchaseRebates -> [OrdinaryAccount, ContraAccount]- PurchaseAllowances -> [OrdinaryAccount, ContraAccount]- WelfareExpenses -> [OrdinaryAccount]- MaintenanceExpenses -> [OrdinaryAccount]- StatutoryWelfareExpenses -> [OrdinaryAccount]- LandRentPaid -> [OrdinaryAccount]- InsuranceExpense -> [OrdinaryAccount]- RepairsExpense -> [OrdinaryAccount]- StorageExpenses -> [OrdinaryAccount]- MembershipFees -> [OrdinaryAccount]- IncomeSummary -> [ClosingDevice]- SuspenseAccount -> [SuspenseOrClearingAccount]- ForeignExchangeGains -> [OrdinaryAccount]- ForeignExchangeLosses -> [OrdinaryAccount]- ContraAccountForGuaranteeObligations -> [OrdinaryAccount]- GuaranteeObligations -> [OrdinaryAccount]- IncomeTaxesAdjustment -> [OrdinaryAccount]- BranchCurrentAccount -> [ReciprocalAccount]- HeadOfficeCurrentAccount -> [ReciprocalAccount]- NetIncomeAttributableToNCI -> [AttributionAccount, PeriodResult]- NetLossAttributableToNCI -> [AttributionAccount, PeriodResult]- TradingSecurities -> [OrdinaryAccount]- HeldToMaturityBonds -> [OrdinaryAccount]- SubsidiaryStocks -> [OrdinaryAccount]- AffiliateStocks -> [OrdinaryAccount]- AvailableForSaleSecurities -> [OrdinaryAccount]- ConsumptionTaxRefundReceivable -> [OrdinaryAccount]- PropertyTaxPayable -> [OrdinaryAccount]- DepositsReceivedFromOfficers -> [OrdinaryAccount]- AccountTitle -> [OrdinaryAccount]--postingFor :: AccountTitles -> PostingCapability-postingFor title = case title of- Cash -> OrdinaryPosting- Deposits -> OrdinaryPosting- CurrentDeposits -> OrdinaryPosting- Securities -> OrdinaryPosting- InvestmentSecurities -> OrdinaryPosting- InvestmentInAssociate -> OrdinaryPosting- LongTermNationalBonds -> OrdinaryPosting- ShortTermNationalBonds -> OrdinaryPosting- Products -> OrdinaryPosting- Machinery -> OrdinaryPosting- Building -> OrdinaryPosting- Vehicle -> OrdinaryPosting- StockInvestment -> OrdinaryPosting- EquipmentInvestment -> OrdinaryPosting- LongTermLoansReceivable -> OrdinaryPosting- AccountsReceivable -> OrdinaryPosting- ShortTermLoansReceivable -> OrdinaryPosting- ReserveDepositReceivable -> OrdinaryPosting- Gold -> OrdinaryPosting- GovernmentService -> OrdinaryPosting- CapitalStock -> OrdinaryPosting- RetainedEarnings -> OrdinaryPosting- LongTermLoansPayable -> OrdinaryPosting- ShortTermLoansPayable -> OrdinaryPosting- LoansPayable -> OrdinaryPosting- ReserveForDepreciation -> OrdinaryPosting- DepositPayable -> OrdinaryPosting- LongTermNationalBondsPayable -> OrdinaryPosting- ShortTermNationalBondsPayable -> OrdinaryPosting- ReserveDepositPayable -> OrdinaryPosting- CentralBankNotePayable -> OrdinaryPosting- Depreciation -> OrdinaryPosting- AmortizationExpense -> OrdinaryPosting- SalesCost -> OrdinaryPosting- BusinessTrip -> OrdinaryPosting- Commutation -> OrdinaryPosting- UtilitiesExpense -> OrdinaryPosting- RentExpense -> OrdinaryPosting- AdvertisingExpense -> OrdinaryPosting- DeliveryExpenses -> OrdinaryPosting- SuppliesExpenses -> OrdinaryPosting- MiscellaneousExpenses -> OrdinaryPosting- EntertainmentExpenses -> OrdinaryPosting- MeetingExpenses -> OrdinaryPosting- NewspaperBooksExpenses -> OrdinaryPosting- WageExpenditure -> OrdinaryPosting- InterestExpense -> OrdinaryPosting- TaxesExpense -> OrdinaryPosting- ConsumptionExpenditure -> OrdinaryPosting- SubsidyExpense -> OrdinaryPosting- CentralBankPaymentExpense -> OrdinaryPosting- Purchases -> OrdinaryPosting- NetIncome -> EngineGeneratedOnly- ValueAdded -> OrdinaryPosting- SubsidyIncome -> OrdinaryPosting- NationalBondInterestEarned -> OrdinaryPosting- DepositInterestEarned -> OrdinaryPosting- GrossProfit -> EngineGeneratedOnly- OrdinaryProfit -> EngineGeneratedOnly- InterestEarned -> OrdinaryPosting- ReceiptFee -> OrdinaryPosting- RentalIncome -> OrdinaryPosting- WageEarned -> OrdinaryPosting- TaxesRevenue -> OrdinaryPosting- CentralBankPaymentIncome -> OrdinaryPosting- Sales -> OrdinaryPosting- EquityInEarningsOfInvestee -> ConsolidationOnly- NetLoss -> EngineGeneratedOnly- PettyCash -> OrdinaryPosting- NotesReceivable -> OrdinaryPosting- ElectronicallyRecordedReceivable -> OrdinaryPosting- CreditCardReceivable -> OrdinaryPosting- NotesLoansReceivable -> OrdinaryPosting- MerchandiseInventory -> OrdinaryPosting- GoodsInTransit -> OrdinaryPosting- AdvancesPaid -> OrdinaryPosting- PrepaidExpenses -> OrdinaryPosting- AccruedRevenue -> OrdinaryPosting- OtherReceivables -> OrdinaryPosting- PaymentsOnBehalf -> OrdinaryPosting- SuspensePayments -> OrdinaryPosting- ConsumptionTaxPaid -> OrdinaryPosting- PrepaidCorporateIncomeTaxes -> OrdinaryPosting- Land -> OrdinaryPosting- Fixtures -> OrdinaryPosting- Patent -> OrdinaryPosting- Trademark -> OrdinaryPosting- Software -> OrdinaryPosting- CashOverShort -> OrdinaryPosting- AccountsPayable -> OrdinaryPosting- NotesPayable -> OrdinaryPosting- ElectronicallyRecordedObligations -> OrdinaryPosting- NotesLoansPayable -> OrdinaryPosting- BankOverdraft -> OrdinaryPosting- AdvancesReceived -> OrdinaryPosting- UnearnedRevenue -> OrdinaryPosting- AccruedExpenses -> OrdinaryPosting- OtherPayables -> OrdinaryPosting- DepositsReceived -> OrdinaryPosting- SuspenseReceipts -> OrdinaryPosting- ConsumptionTaxReceived -> OrdinaryPosting- AccruedConsumptionTax -> OrdinaryPosting- AccruedCorporateIncomeTaxes -> OrdinaryPosting- UnpaidDividends -> OrdinaryPosting- AllowanceForDoubtfulAccounts -> OrdinaryPosting- AccumulatedDepreciation -> OrdinaryPosting- LegalRetainedEarnings -> OrdinaryPosting- CumulativeTranslationAdjustment -> ConsolidationOnly- ProvisionForDoubtfulAccounts -> OrdinaryPosting- BadDebtLoss -> OrdinaryPosting- LossOnSalesOfFixedAssets -> OrdinaryPosting- LossOnSalesOfNotesReceivable -> OrdinaryPosting- PaymentFees -> OrdinaryPosting- MiscellaneousLoss -> OrdinaryPosting- CorporateIncomeTaxes -> OrdinaryPosting- CommunicationExpenses -> OrdinaryPosting- GainOnSalesOfFixedAssets -> OrdinaryPosting- RecoveryOfBadDebts -> OrdinaryPosting- MiscellaneousIncome -> OrdinaryPosting- ReversalOfAllowanceForDoubtfulAccounts -> OrdinaryPosting- TimeDeposits -> OrdinaryPosting- LoansReceivable -> OrdinaryPosting- GiftCertificatesReceived -> OrdinaryPosting- SecurityDepositsPaid -> OrdinaryPosting- SuppliesOnHand -> OrdinaryPosting- RawMaterials -> OrdinaryPosting- ContractAssets -> OrdinaryPosting- IncomeTaxesRefundReceivable -> OrdinaryPosting- WorkInProcess -> OrdinaryPosting- DeferredTaxAssets -> OrdinaryPosting- LeasedAssets -> OrdinaryPosting- ToolsAndInstruments -> OrdinaryPosting- ConstructionInProgress -> OrdinaryPosting- Goodwill -> OrdinaryPosting- SoftwareInProgress -> OrdinaryPosting- LongTermPrepaidExpenses -> OrdinaryPosting- DishonoredNotesReceivable -> OrdinaryPosting- PrepaidPensionCost -> OrdinaryPosting- NetDefinedBenefitAsset -> OrdinaryPosting- DepositsInSpecialAccounts -> OrdinaryPosting- Structures -> OrdinaryPosting- LeaseholdRights -> OrdinaryPosting- NonOperatingNotesReceivable -> OrdinaryPosting- NonOperatingElectronicallyRecordedReceivable -> OrdinaryPosting- RefundLiabilities -> OrdinaryPosting- NonOperatingNotesPayable -> OrdinaryPosting- NonOperatingElectronicallyRecordedObligations -> OrdinaryPosting- BonusesPayable -> OrdinaryPosting- AllowanceForRepairs -> OrdinaryPosting- AllowanceForProductWarranties -> OrdinaryPosting- AllowanceForBonuses -> OrdinaryPosting- DeferredTaxLiabilities -> OrdinaryPosting- LeaseObligations -> OrdinaryPosting- GuaranteeDepositsReceived -> OrdinaryPosting- AllowanceForRetirementBenefits -> OrdinaryPosting- LongTermOtherPayables -> OrdinaryPosting- NetDefinedBenefitLiability -> OrdinaryPosting- StockSubscriptionDeposits -> OrdinaryPosting- LegalCapitalSurplus -> OrdinaryPosting- OtherCapitalSurplus -> OrdinaryPosting- DividendEqualizationReserve -> OrdinaryPosting- RepairFundReserve -> OrdinaryPosting- ConstructionFundReserve -> OrdinaryPosting- GeneralReserve -> OrdinaryPosting- ValuationDifferenceOnOtherSecurities -> OrdinaryPosting- NonControllingInterests -> ConsolidationOnly- CapitalSurplus -> OrdinaryPosting- EarnedSurplus -> OrdinaryPosting- ServiceRevenue -> OrdinaryPosting- OperatingRevenue -> OrdinaryPosting- GainOnSalesOfSecurities -> OrdinaryPosting- GainOnValuationOfSecurities -> OrdinaryPosting- DividendsReceived -> OrdinaryPosting- InterestOnSecurities -> OrdinaryPosting- GainOnSalesOfInvestmentSecurities -> OrdinaryPosting- InsuranceGain -> OrdinaryPosting- GainOnBargainPurchase -> OrdinaryPosting- ReversalOfAllowanceForRepairs -> OrdinaryPosting- ReversalOfAllowanceForBonuses -> OrdinaryPosting- ReversalOfAllowanceForProductWarranties -> OrdinaryPosting- GainOnDonationOfFixedAssets -> OrdinaryPosting- GainOnNationalSubsidies -> OrdinaryPosting- GainOnConstructionGrants -> OrdinaryPosting- LandRentReceived -> OrdinaryPosting- SalesRebates -> OrdinaryPosting- SalesAllowances -> OrdinaryPosting- CostOfServices -> OrdinaryPosting- OperatingExpenses -> OrdinaryPosting- InventoryShrinkageLoss -> OrdinaryPosting- LossOnValuationOfMerchandise -> OrdinaryPosting- Bonuses -> OrdinaryPosting- RetirementBenefitExpenses -> OrdinaryPosting- ProvisionForRepairs -> OrdinaryPosting- ProvisionForBonuses -> OrdinaryPosting- ProvisionForProductWarranties -> OrdinaryPosting- ResearchAndDevelopmentExpenses -> OrdinaryPosting- AmortizationOfGoodwill -> OrdinaryPosting- AmortizationOfSoftware -> OrdinaryPosting- AmortizationOfPatents -> OrdinaryPosting- LeaseExpenses -> OrdinaryPosting- IncorporationExpenses -> OrdinaryPosting- StockIssuanceCosts -> OrdinaryPosting- BusinessCommencementExpenses -> OrdinaryPosting- DevelopmentExpenses -> OrdinaryPosting- LossOnSalesOfElectronicallyRecordedReceivables -> OrdinaryPosting- LossOnSalesOfReceivables -> OrdinaryPosting- LossOnSalesOfSecurities -> OrdinaryPosting- LossOnValuationOfSecurities -> OrdinaryPosting- LossOnSalesOfInvestmentSecurities -> OrdinaryPosting- LossOnFire -> OrdinaryPosting- LossOnRetirementOfFixedAssets -> OrdinaryPosting- LossOnReductionOfFixedAssets -> OrdinaryPosting- AdditionalIncomeTaxesForPriorPeriods -> OrdinaryPosting- RefundOfIncomeTaxes -> OrdinaryPosting- PurchaseRebates -> OrdinaryPosting- PurchaseAllowances -> OrdinaryPosting- WelfareExpenses -> OrdinaryPosting- MaintenanceExpenses -> OrdinaryPosting- StatutoryWelfareExpenses -> OrdinaryPosting- LandRentPaid -> OrdinaryPosting- InsuranceExpense -> OrdinaryPosting- RepairsExpense -> OrdinaryPosting- StorageExpenses -> OrdinaryPosting- MembershipFees -> OrdinaryPosting- IncomeSummary -> ClosingOnly- SuspenseAccount -> OrdinaryPosting- ForeignExchangeGains -> OrdinaryPosting- ForeignExchangeLosses -> OrdinaryPosting- ContraAccountForGuaranteeObligations -> OrdinaryPosting- GuaranteeObligations -> OrdinaryPosting- IncomeTaxesAdjustment -> OrdinaryPosting- BranchCurrentAccount -> OrdinaryPosting- HeadOfficeCurrentAccount -> OrdinaryPosting- NetIncomeAttributableToNCI -> ConsolidationOnly- NetLossAttributableToNCI -> ConsolidationOnly- TradingSecurities -> OrdinaryPosting- HeldToMaturityBonds -> OrdinaryPosting- SubsidiaryStocks -> OrdinaryPosting- AffiliateStocks -> OrdinaryPosting- AvailableForSaleSecurities -> OrdinaryPosting- ConsumptionTaxRefundReceivable -> OrdinaryPosting- PropertyTaxPayable -> OrdinaryPosting- DepositsReceivedFromOfficers -> OrdinaryPosting- AccountTitle -> NotPostable--divisionFor :: AccountTitles -> AccountSpec -> DivisionSemantics-divisionFor title spec = case title of- Cash -> StatementDivision (asDivision spec)- Deposits -> StatementDivision (asDivision spec)- CurrentDeposits -> StatementDivision (asDivision spec)- Securities -> StatementDivision (asDivision spec)- InvestmentSecurities -> StatementDivision (asDivision spec)- InvestmentInAssociate -> StatementDivision (asDivision spec)- LongTermNationalBonds -> StatementDivision (asDivision spec)- ShortTermNationalBonds -> StatementDivision (asDivision spec)- Products -> StatementDivision (asDivision spec)- Machinery -> StatementDivision (asDivision spec)- Building -> StatementDivision (asDivision spec)- Vehicle -> StatementDivision (asDivision spec)- StockInvestment -> StatementDivision (asDivision spec)- EquipmentInvestment -> StatementDivision (asDivision spec)- LongTermLoansReceivable -> StatementDivision (asDivision spec)- AccountsReceivable -> StatementDivision (asDivision spec)- ShortTermLoansReceivable -> StatementDivision (asDivision spec)- ReserveDepositReceivable -> StatementDivision (asDivision spec)- Gold -> StatementDivision (asDivision spec)- GovernmentService -> StatementDivision (asDivision spec)- CapitalStock -> StatementDivision (asDivision spec)- RetainedEarnings -> StatementDivision (asDivision spec)- LongTermLoansPayable -> StatementDivision (asDivision spec)- ShortTermLoansPayable -> StatementDivision (asDivision spec)- LoansPayable -> StatementDivision (asDivision spec)- ReserveForDepreciation -> StatementDivision (asDivision spec)- DepositPayable -> StatementDivision (asDivision spec)- LongTermNationalBondsPayable -> StatementDivision (asDivision spec)- ShortTermNationalBondsPayable -> StatementDivision (asDivision spec)- ReserveDepositPayable -> StatementDivision (asDivision spec)- CentralBankNotePayable -> StatementDivision (asDivision spec)- Depreciation -> StatementDivision (asDivision spec)- AmortizationExpense -> StatementDivision (asDivision spec)- SalesCost -> StatementDivision (asDivision spec)- BusinessTrip -> StatementDivision (asDivision spec)- Commutation -> StatementDivision (asDivision spec)- UtilitiesExpense -> StatementDivision (asDivision spec)- RentExpense -> StatementDivision (asDivision spec)- AdvertisingExpense -> StatementDivision (asDivision spec)- DeliveryExpenses -> StatementDivision (asDivision spec)- SuppliesExpenses -> StatementDivision (asDivision spec)- MiscellaneousExpenses -> StatementDivision (asDivision spec)- EntertainmentExpenses -> StatementDivision (asDivision spec)- MeetingExpenses -> StatementDivision (asDivision spec)- NewspaperBooksExpenses -> StatementDivision (asDivision spec)- WageExpenditure -> StatementDivision (asDivision spec)- InterestExpense -> StatementDivision (asDivision spec)- TaxesExpense -> StatementDivision (asDivision spec)- ConsumptionExpenditure -> StatementDivision (asDivision spec)- SubsidyExpense -> StatementDivision (asDivision spec)- CentralBankPaymentExpense -> StatementDivision (asDivision spec)- Purchases -> StatementDivision (asDivision spec)- NetIncome -> DirectionEncoding (asDivision spec)- ValueAdded -> StatementDivision (asDivision spec)- SubsidyIncome -> StatementDivision (asDivision spec)- NationalBondInterestEarned -> StatementDivision (asDivision spec)- DepositInterestEarned -> StatementDivision (asDivision spec)- GrossProfit -> DirectionEncoding (asDivision spec)- OrdinaryProfit -> DirectionEncoding (asDivision spec)- InterestEarned -> StatementDivision (asDivision spec)- ReceiptFee -> StatementDivision (asDivision spec)- RentalIncome -> StatementDivision (asDivision spec)- WageEarned -> StatementDivision (asDivision spec)- TaxesRevenue -> StatementDivision (asDivision spec)- CentralBankPaymentIncome -> StatementDivision (asDivision spec)- Sales -> StatementDivision (asDivision spec)- EquityInEarningsOfInvestee -> StatementDivision (asDivision spec)- NetLoss -> DirectionEncoding (asDivision spec)- PettyCash -> StatementDivision (asDivision spec)- NotesReceivable -> StatementDivision (asDivision spec)- ElectronicallyRecordedReceivable -> StatementDivision (asDivision spec)- CreditCardReceivable -> StatementDivision (asDivision spec)- NotesLoansReceivable -> StatementDivision (asDivision spec)- MerchandiseInventory -> StatementDivision (asDivision spec)- GoodsInTransit -> StatementDivision (asDivision spec)- AdvancesPaid -> StatementDivision (asDivision spec)- PrepaidExpenses -> StatementDivision (asDivision spec)- AccruedRevenue -> StatementDivision (asDivision spec)- OtherReceivables -> StatementDivision (asDivision spec)- PaymentsOnBehalf -> StatementDivision (asDivision spec)- SuspensePayments -> BookkeepingControlClass (asDivision spec)- ConsumptionTaxPaid -> StatementDivision (asDivision spec)- PrepaidCorporateIncomeTaxes -> StatementDivision (asDivision spec)- Land -> StatementDivision (asDivision spec)- Fixtures -> StatementDivision (asDivision spec)- Patent -> StatementDivision (asDivision spec)- Trademark -> StatementDivision (asDivision spec)- Software -> StatementDivision (asDivision spec)- CashOverShort -> BookkeepingControlClass (asDivision spec)- AccountsPayable -> StatementDivision (asDivision spec)- NotesPayable -> StatementDivision (asDivision spec)- ElectronicallyRecordedObligations -> StatementDivision (asDivision spec)- NotesLoansPayable -> StatementDivision (asDivision spec)- BankOverdraft -> StatementDivision (asDivision spec)- AdvancesReceived -> StatementDivision (asDivision spec)- UnearnedRevenue -> StatementDivision (asDivision spec)- AccruedExpenses -> StatementDivision (asDivision spec)- OtherPayables -> StatementDivision (asDivision spec)- DepositsReceived -> StatementDivision (asDivision spec)- SuspenseReceipts -> BookkeepingControlClass (asDivision spec)- ConsumptionTaxReceived -> StatementDivision (asDivision spec)- AccruedConsumptionTax -> StatementDivision (asDivision spec)- AccruedCorporateIncomeTaxes -> StatementDivision (asDivision spec)- UnpaidDividends -> StatementDivision (asDivision spec)- AllowanceForDoubtfulAccounts -> StatementDivision (asDivision spec)- AccumulatedDepreciation -> StatementDivision (asDivision spec)- LegalRetainedEarnings -> StatementDivision (asDivision spec)- CumulativeTranslationAdjustment -> StatementDivision (asDivision spec)- ProvisionForDoubtfulAccounts -> StatementDivision (asDivision spec)- BadDebtLoss -> StatementDivision (asDivision spec)- LossOnSalesOfFixedAssets -> StatementDivision (asDivision spec)- LossOnSalesOfNotesReceivable -> StatementDivision (asDivision spec)- PaymentFees -> StatementDivision (asDivision spec)- MiscellaneousLoss -> StatementDivision (asDivision spec)- CorporateIncomeTaxes -> StatementDivision (asDivision spec)- CommunicationExpenses -> StatementDivision (asDivision spec)- GainOnSalesOfFixedAssets -> StatementDivision (asDivision spec)- RecoveryOfBadDebts -> StatementDivision (asDivision spec)- MiscellaneousIncome -> StatementDivision (asDivision spec)- ReversalOfAllowanceForDoubtfulAccounts -> StatementDivision (asDivision spec)- TimeDeposits -> StatementDivision (asDivision spec)- LoansReceivable -> StatementDivision (asDivision spec)- GiftCertificatesReceived -> StatementDivision (asDivision spec)- SecurityDepositsPaid -> StatementDivision (asDivision spec)- SuppliesOnHand -> StatementDivision (asDivision spec)- RawMaterials -> StatementDivision (asDivision spec)- ContractAssets -> StatementDivision (asDivision spec)- IncomeTaxesRefundReceivable -> StatementDivision (asDivision spec)- WorkInProcess -> StatementDivision (asDivision spec)- DeferredTaxAssets -> StatementDivision (asDivision spec)- LeasedAssets -> StatementDivision (asDivision spec)- ToolsAndInstruments -> StatementDivision (asDivision spec)- ConstructionInProgress -> StatementDivision (asDivision spec)- Goodwill -> StatementDivision (asDivision spec)- SoftwareInProgress -> StatementDivision (asDivision spec)- LongTermPrepaidExpenses -> StatementDivision (asDivision spec)- DishonoredNotesReceivable -> StatementDivision (asDivision spec)- PrepaidPensionCost -> StatementDivision (asDivision spec)- NetDefinedBenefitAsset -> StatementDivision (asDivision spec)- DepositsInSpecialAccounts -> StatementDivision (asDivision spec)- Structures -> StatementDivision (asDivision spec)- LeaseholdRights -> StatementDivision (asDivision spec)- NonOperatingNotesReceivable -> StatementDivision (asDivision spec)- NonOperatingElectronicallyRecordedReceivable -> StatementDivision (asDivision spec)- RefundLiabilities -> StatementDivision (asDivision spec)- NonOperatingNotesPayable -> StatementDivision (asDivision spec)- NonOperatingElectronicallyRecordedObligations -> StatementDivision (asDivision spec)- BonusesPayable -> StatementDivision (asDivision spec)- AllowanceForRepairs -> StatementDivision (asDivision spec)- AllowanceForProductWarranties -> StatementDivision (asDivision spec)- AllowanceForBonuses -> StatementDivision (asDivision spec)- DeferredTaxLiabilities -> StatementDivision (asDivision spec)- LeaseObligations -> StatementDivision (asDivision spec)- GuaranteeDepositsReceived -> StatementDivision (asDivision spec)- AllowanceForRetirementBenefits -> StatementDivision (asDivision spec)- LongTermOtherPayables -> StatementDivision (asDivision spec)- NetDefinedBenefitLiability -> StatementDivision (asDivision spec)- StockSubscriptionDeposits -> StatementDivision (asDivision spec)- LegalCapitalSurplus -> StatementDivision (asDivision spec)- OtherCapitalSurplus -> StatementDivision (asDivision spec)- DividendEqualizationReserve -> StatementDivision (asDivision spec)- RepairFundReserve -> StatementDivision (asDivision spec)- ConstructionFundReserve -> StatementDivision (asDivision spec)- GeneralReserve -> StatementDivision (asDivision spec)- ValuationDifferenceOnOtherSecurities -> StatementDivision (asDivision spec)- NonControllingInterests -> StatementDivision (asDivision spec)- CapitalSurplus -> StatementDivision (asDivision spec)- EarnedSurplus -> StatementDivision (asDivision spec)- ServiceRevenue -> StatementDivision (asDivision spec)- OperatingRevenue -> StatementDivision (asDivision spec)- GainOnSalesOfSecurities -> StatementDivision (asDivision spec)- GainOnValuationOfSecurities -> StatementDivision (asDivision spec)- DividendsReceived -> StatementDivision (asDivision spec)- InterestOnSecurities -> StatementDivision (asDivision spec)- GainOnSalesOfInvestmentSecurities -> StatementDivision (asDivision spec)- InsuranceGain -> StatementDivision (asDivision spec)- GainOnBargainPurchase -> StatementDivision (asDivision spec)- ReversalOfAllowanceForRepairs -> StatementDivision (asDivision spec)- ReversalOfAllowanceForBonuses -> StatementDivision (asDivision spec)- ReversalOfAllowanceForProductWarranties -> StatementDivision (asDivision spec)- GainOnDonationOfFixedAssets -> StatementDivision (asDivision spec)- GainOnNationalSubsidies -> StatementDivision (asDivision spec)- GainOnConstructionGrants -> StatementDivision (asDivision spec)- LandRentReceived -> StatementDivision (asDivision spec)- SalesRebates -> StatementDivision (asDivision spec)- SalesAllowances -> StatementDivision (asDivision spec)- CostOfServices -> StatementDivision (asDivision spec)- OperatingExpenses -> StatementDivision (asDivision spec)- InventoryShrinkageLoss -> StatementDivision (asDivision spec)- LossOnValuationOfMerchandise -> StatementDivision (asDivision spec)- Bonuses -> StatementDivision (asDivision spec)- RetirementBenefitExpenses -> StatementDivision (asDivision spec)- ProvisionForRepairs -> StatementDivision (asDivision spec)- ProvisionForBonuses -> StatementDivision (asDivision spec)- ProvisionForProductWarranties -> StatementDivision (asDivision spec)- ResearchAndDevelopmentExpenses -> StatementDivision (asDivision spec)- AmortizationOfGoodwill -> StatementDivision (asDivision spec)- AmortizationOfSoftware -> StatementDivision (asDivision spec)- AmortizationOfPatents -> StatementDivision (asDivision spec)- LeaseExpenses -> StatementDivision (asDivision spec)- IncorporationExpenses -> StatementDivision (asDivision spec)- StockIssuanceCosts -> StatementDivision (asDivision spec)- BusinessCommencementExpenses -> StatementDivision (asDivision spec)- DevelopmentExpenses -> StatementDivision (asDivision spec)- LossOnSalesOfElectronicallyRecordedReceivables -> StatementDivision (asDivision spec)- LossOnSalesOfReceivables -> StatementDivision (asDivision spec)- LossOnSalesOfSecurities -> StatementDivision (asDivision spec)- LossOnValuationOfSecurities -> StatementDivision (asDivision spec)- LossOnSalesOfInvestmentSecurities -> StatementDivision (asDivision spec)- LossOnFire -> StatementDivision (asDivision spec)- LossOnRetirementOfFixedAssets -> StatementDivision (asDivision spec)- LossOnReductionOfFixedAssets -> StatementDivision (asDivision spec)- AdditionalIncomeTaxesForPriorPeriods -> StatementDivision (asDivision spec)- RefundOfIncomeTaxes -> StatementDivision (asDivision spec)- PurchaseRebates -> StatementDivision (asDivision spec)- PurchaseAllowances -> StatementDivision (asDivision spec)- WelfareExpenses -> StatementDivision (asDivision spec)- MaintenanceExpenses -> StatementDivision (asDivision spec)- StatutoryWelfareExpenses -> StatementDivision (asDivision spec)- LandRentPaid -> StatementDivision (asDivision spec)- InsuranceExpense -> StatementDivision (asDivision spec)- RepairsExpense -> StatementDivision (asDivision spec)- StorageExpenses -> StatementDivision (asDivision spec)- MembershipFees -> StatementDivision (asDivision spec)- IncomeSummary -> DirectionEncoding (asDivision spec)- SuspenseAccount -> BookkeepingControlClass (asDivision spec)- ForeignExchangeGains -> StatementDivision (asDivision spec)- ForeignExchangeLosses -> StatementDivision (asDivision spec)- ContraAccountForGuaranteeObligations -> StatementDivision (asDivision spec)- GuaranteeObligations -> StatementDivision (asDivision spec)- IncomeTaxesAdjustment -> StatementDivision (asDivision spec)- BranchCurrentAccount -> BookkeepingControlClass (asDivision spec)- HeadOfficeCurrentAccount -> BookkeepingControlClass (asDivision spec)- NetIncomeAttributableToNCI -> DirectionEncoding (asDivision spec)- NetLossAttributableToNCI -> DirectionEncoding (asDivision spec)- TradingSecurities -> StatementDivision (asDivision spec)- HeldToMaturityBonds -> StatementDivision (asDivision spec)- SubsidiaryStocks -> StatementDivision (asDivision spec)- AffiliateStocks -> StatementDivision (asDivision spec)- AvailableForSaleSecurities -> StatementDivision (asDivision spec)- ConsumptionTaxRefundReceivable -> StatementDivision (asDivision spec)- PropertyTaxPayable -> StatementDivision (asDivision spec)- DepositsReceivedFromOfficers -> StatementDivision (asDivision spec)- AccountTitle -> NoStatementDivision--homeSideFor :: AccountTitles -> AccountSpec -> HomeSideSemantics-homeSideFor title spec = case title of- Cash -> FixedHomeSide (legacyHomeSide spec)- Deposits -> FixedHomeSide (legacyHomeSide spec)- CurrentDeposits -> FixedHomeSide (legacyHomeSide spec)- Securities -> FixedHomeSide (legacyHomeSide spec)- InvestmentSecurities -> FixedHomeSide (legacyHomeSide spec)- InvestmentInAssociate -> FixedHomeSide (legacyHomeSide spec)- LongTermNationalBonds -> FixedHomeSide (legacyHomeSide spec)- ShortTermNationalBonds -> FixedHomeSide (legacyHomeSide spec)- Products -> FixedHomeSide (legacyHomeSide spec)- Machinery -> FixedHomeSide (legacyHomeSide spec)- Building -> FixedHomeSide (legacyHomeSide spec)- Vehicle -> FixedHomeSide (legacyHomeSide spec)- StockInvestment -> FixedHomeSide (legacyHomeSide spec)- EquipmentInvestment -> FixedHomeSide (legacyHomeSide spec)- LongTermLoansReceivable -> FixedHomeSide (legacyHomeSide spec)- AccountsReceivable -> FixedHomeSide (legacyHomeSide spec)- ShortTermLoansReceivable -> FixedHomeSide (legacyHomeSide spec)- ReserveDepositReceivable -> FixedHomeSide (legacyHomeSide spec)- Gold -> FixedHomeSide (legacyHomeSide spec)- GovernmentService -> FixedHomeSide (legacyHomeSide spec)- CapitalStock -> FixedHomeSide (legacyHomeSide spec)- RetainedEarnings -> FixedHomeSide (legacyHomeSide spec)- LongTermLoansPayable -> FixedHomeSide (legacyHomeSide spec)- ShortTermLoansPayable -> FixedHomeSide (legacyHomeSide spec)- LoansPayable -> FixedHomeSide (legacyHomeSide spec)- ReserveForDepreciation -> FixedHomeSide (legacyHomeSide spec)- DepositPayable -> FixedHomeSide (legacyHomeSide spec)- LongTermNationalBondsPayable -> FixedHomeSide (legacyHomeSide spec)- ShortTermNationalBondsPayable -> FixedHomeSide (legacyHomeSide spec)- ReserveDepositPayable -> FixedHomeSide (legacyHomeSide spec)- CentralBankNotePayable -> FixedHomeSide (legacyHomeSide spec)- Depreciation -> FixedHomeSide (legacyHomeSide spec)- AmortizationExpense -> FixedHomeSide (legacyHomeSide spec)- SalesCost -> FixedHomeSide (legacyHomeSide spec)- BusinessTrip -> FixedHomeSide (legacyHomeSide spec)- Commutation -> FixedHomeSide (legacyHomeSide spec)- UtilitiesExpense -> FixedHomeSide (legacyHomeSide spec)- RentExpense -> FixedHomeSide (legacyHomeSide spec)- AdvertisingExpense -> FixedHomeSide (legacyHomeSide spec)- DeliveryExpenses -> FixedHomeSide (legacyHomeSide spec)- SuppliesExpenses -> FixedHomeSide (legacyHomeSide spec)- MiscellaneousExpenses -> FixedHomeSide (legacyHomeSide spec)- EntertainmentExpenses -> FixedHomeSide (legacyHomeSide spec)- MeetingExpenses -> FixedHomeSide (legacyHomeSide spec)- NewspaperBooksExpenses -> FixedHomeSide (legacyHomeSide spec)- WageExpenditure -> FixedHomeSide (legacyHomeSide spec)- InterestExpense -> FixedHomeSide (legacyHomeSide spec)- TaxesExpense -> FixedHomeSide (legacyHomeSide spec)- ConsumptionExpenditure -> FixedHomeSide (legacyHomeSide spec)- SubsidyExpense -> FixedHomeSide (legacyHomeSide spec)- CentralBankPaymentExpense -> FixedHomeSide (legacyHomeSide spec)- Purchases -> FixedHomeSide (legacyHomeSide spec)- NetIncome -> FixedHomeSide (legacyHomeSide spec)- ValueAdded -> FixedHomeSide (legacyHomeSide spec)- SubsidyIncome -> FixedHomeSide (legacyHomeSide spec)- NationalBondInterestEarned -> FixedHomeSide (legacyHomeSide spec)- DepositInterestEarned -> FixedHomeSide (legacyHomeSide spec)- GrossProfit -> FixedHomeSide (legacyHomeSide spec)- OrdinaryProfit -> FixedHomeSide (legacyHomeSide spec)- InterestEarned -> FixedHomeSide (legacyHomeSide spec)- ReceiptFee -> FixedHomeSide (legacyHomeSide spec)- RentalIncome -> FixedHomeSide (legacyHomeSide spec)- WageEarned -> FixedHomeSide (legacyHomeSide spec)- TaxesRevenue -> FixedHomeSide (legacyHomeSide spec)- CentralBankPaymentIncome -> FixedHomeSide (legacyHomeSide spec)- Sales -> FixedHomeSide (legacyHomeSide spec)- EquityInEarningsOfInvestee -> FixedHomeSide (legacyHomeSide spec)- NetLoss -> FixedHomeSide (legacyHomeSide spec)- PettyCash -> FixedHomeSide (legacyHomeSide spec)- NotesReceivable -> FixedHomeSide (legacyHomeSide spec)- ElectronicallyRecordedReceivable -> FixedHomeSide (legacyHomeSide spec)- CreditCardReceivable -> FixedHomeSide (legacyHomeSide spec)- NotesLoansReceivable -> FixedHomeSide (legacyHomeSide spec)- MerchandiseInventory -> FixedHomeSide (legacyHomeSide spec)- GoodsInTransit -> FixedHomeSide (legacyHomeSide spec)- AdvancesPaid -> FixedHomeSide (legacyHomeSide spec)- PrepaidExpenses -> FixedHomeSide (legacyHomeSide spec)- AccruedRevenue -> FixedHomeSide (legacyHomeSide spec)- OtherReceivables -> FixedHomeSide (legacyHomeSide spec)- PaymentsOnBehalf -> FixedHomeSide (legacyHomeSide spec)- SuspensePayments -> FixedHomeSide (legacyHomeSide spec)- ConsumptionTaxPaid -> FixedHomeSide (legacyHomeSide spec)- PrepaidCorporateIncomeTaxes -> FixedHomeSide (legacyHomeSide spec)- Land -> FixedHomeSide (legacyHomeSide spec)- Fixtures -> FixedHomeSide (legacyHomeSide spec)- Patent -> FixedHomeSide (legacyHomeSide spec)- Trademark -> FixedHomeSide (legacyHomeSide spec)- Software -> FixedHomeSide (legacyHomeSide spec)- CashOverShort -> ContextDependentHomeSide- AccountsPayable -> FixedHomeSide (legacyHomeSide spec)- NotesPayable -> FixedHomeSide (legacyHomeSide spec)- ElectronicallyRecordedObligations -> FixedHomeSide (legacyHomeSide spec)- NotesLoansPayable -> FixedHomeSide (legacyHomeSide spec)- BankOverdraft -> FixedHomeSide (legacyHomeSide spec)- AdvancesReceived -> FixedHomeSide (legacyHomeSide spec)- UnearnedRevenue -> FixedHomeSide (legacyHomeSide spec)- AccruedExpenses -> FixedHomeSide (legacyHomeSide spec)- OtherPayables -> FixedHomeSide (legacyHomeSide spec)- DepositsReceived -> FixedHomeSide (legacyHomeSide spec)- SuspenseReceipts -> FixedHomeSide (legacyHomeSide spec)- ConsumptionTaxReceived -> FixedHomeSide (legacyHomeSide spec)- AccruedConsumptionTax -> FixedHomeSide (legacyHomeSide spec)- AccruedCorporateIncomeTaxes -> FixedHomeSide (legacyHomeSide spec)- UnpaidDividends -> FixedHomeSide (legacyHomeSide spec)- AllowanceForDoubtfulAccounts -> FixedHomeSide (legacyHomeSide spec)- AccumulatedDepreciation -> FixedHomeSide (legacyHomeSide spec)- LegalRetainedEarnings -> FixedHomeSide (legacyHomeSide spec)- CumulativeTranslationAdjustment -> FixedHomeSide (legacyHomeSide spec)- ProvisionForDoubtfulAccounts -> FixedHomeSide (legacyHomeSide spec)- BadDebtLoss -> FixedHomeSide (legacyHomeSide spec)- LossOnSalesOfFixedAssets -> FixedHomeSide (legacyHomeSide spec)- LossOnSalesOfNotesReceivable -> FixedHomeSide (legacyHomeSide spec)- PaymentFees -> FixedHomeSide (legacyHomeSide spec)- MiscellaneousLoss -> FixedHomeSide (legacyHomeSide spec)- CorporateIncomeTaxes -> FixedHomeSide (legacyHomeSide spec)- CommunicationExpenses -> FixedHomeSide (legacyHomeSide spec)- GainOnSalesOfFixedAssets -> FixedHomeSide (legacyHomeSide spec)- RecoveryOfBadDebts -> FixedHomeSide (legacyHomeSide spec)- MiscellaneousIncome -> FixedHomeSide (legacyHomeSide spec)- ReversalOfAllowanceForDoubtfulAccounts -> FixedHomeSide (legacyHomeSide spec)- TimeDeposits -> FixedHomeSide (legacyHomeSide spec)- LoansReceivable -> FixedHomeSide (legacyHomeSide spec)- GiftCertificatesReceived -> FixedHomeSide (legacyHomeSide spec)- SecurityDepositsPaid -> FixedHomeSide (legacyHomeSide spec)- SuppliesOnHand -> FixedHomeSide (legacyHomeSide spec)- RawMaterials -> FixedHomeSide (legacyHomeSide spec)- ContractAssets -> FixedHomeSide (legacyHomeSide spec)- IncomeTaxesRefundReceivable -> FixedHomeSide (legacyHomeSide spec)- WorkInProcess -> FixedHomeSide (legacyHomeSide spec)- DeferredTaxAssets -> FixedHomeSide (legacyHomeSide spec)- LeasedAssets -> FixedHomeSide (legacyHomeSide spec)- ToolsAndInstruments -> FixedHomeSide (legacyHomeSide spec)- ConstructionInProgress -> FixedHomeSide (legacyHomeSide spec)- Goodwill -> FixedHomeSide (legacyHomeSide spec)- SoftwareInProgress -> FixedHomeSide (legacyHomeSide spec)- LongTermPrepaidExpenses -> FixedHomeSide (legacyHomeSide spec)- DishonoredNotesReceivable -> FixedHomeSide (legacyHomeSide spec)- PrepaidPensionCost -> FixedHomeSide (legacyHomeSide spec)- NetDefinedBenefitAsset -> FixedHomeSide (legacyHomeSide spec)- DepositsInSpecialAccounts -> FixedHomeSide (legacyHomeSide spec)- Structures -> FixedHomeSide (legacyHomeSide spec)- LeaseholdRights -> FixedHomeSide (legacyHomeSide spec)- NonOperatingNotesReceivable -> FixedHomeSide (legacyHomeSide spec)- NonOperatingElectronicallyRecordedReceivable -> FixedHomeSide (legacyHomeSide spec)- RefundLiabilities -> FixedHomeSide (legacyHomeSide spec)- NonOperatingNotesPayable -> FixedHomeSide (legacyHomeSide spec)- NonOperatingElectronicallyRecordedObligations -> FixedHomeSide (legacyHomeSide spec)- BonusesPayable -> FixedHomeSide (legacyHomeSide spec)- AllowanceForRepairs -> FixedHomeSide (legacyHomeSide spec)- AllowanceForProductWarranties -> FixedHomeSide (legacyHomeSide spec)- AllowanceForBonuses -> FixedHomeSide (legacyHomeSide spec)- DeferredTaxLiabilities -> FixedHomeSide (legacyHomeSide spec)- LeaseObligations -> FixedHomeSide (legacyHomeSide spec)- GuaranteeDepositsReceived -> FixedHomeSide (legacyHomeSide spec)- AllowanceForRetirementBenefits -> FixedHomeSide (legacyHomeSide spec)- LongTermOtherPayables -> FixedHomeSide (legacyHomeSide spec)- NetDefinedBenefitLiability -> FixedHomeSide (legacyHomeSide spec)- StockSubscriptionDeposits -> FixedHomeSide (legacyHomeSide spec)- LegalCapitalSurplus -> FixedHomeSide (legacyHomeSide spec)- OtherCapitalSurplus -> FixedHomeSide (legacyHomeSide spec)- DividendEqualizationReserve -> FixedHomeSide (legacyHomeSide spec)- RepairFundReserve -> FixedHomeSide (legacyHomeSide spec)- ConstructionFundReserve -> FixedHomeSide (legacyHomeSide spec)- GeneralReserve -> FixedHomeSide (legacyHomeSide spec)- ValuationDifferenceOnOtherSecurities -> FixedHomeSide (legacyHomeSide spec)- NonControllingInterests -> FixedHomeSide (legacyHomeSide spec)- CapitalSurplus -> FixedHomeSide (legacyHomeSide spec)- EarnedSurplus -> FixedHomeSide (legacyHomeSide spec)- ServiceRevenue -> FixedHomeSide (legacyHomeSide spec)- OperatingRevenue -> FixedHomeSide (legacyHomeSide spec)- GainOnSalesOfSecurities -> FixedHomeSide (legacyHomeSide spec)- GainOnValuationOfSecurities -> FixedHomeSide (legacyHomeSide spec)- DividendsReceived -> FixedHomeSide (legacyHomeSide spec)- InterestOnSecurities -> FixedHomeSide (legacyHomeSide spec)- GainOnSalesOfInvestmentSecurities -> FixedHomeSide (legacyHomeSide spec)- InsuranceGain -> FixedHomeSide (legacyHomeSide spec)- GainOnBargainPurchase -> FixedHomeSide (legacyHomeSide spec)- ReversalOfAllowanceForRepairs -> FixedHomeSide (legacyHomeSide spec)- ReversalOfAllowanceForBonuses -> FixedHomeSide (legacyHomeSide spec)- ReversalOfAllowanceForProductWarranties -> FixedHomeSide (legacyHomeSide spec)- GainOnDonationOfFixedAssets -> FixedHomeSide (legacyHomeSide spec)- GainOnNationalSubsidies -> FixedHomeSide (legacyHomeSide spec)- GainOnConstructionGrants -> FixedHomeSide (legacyHomeSide spec)- LandRentReceived -> FixedHomeSide (legacyHomeSide spec)- SalesRebates -> FixedHomeSide (legacyHomeSide spec)- SalesAllowances -> FixedHomeSide (legacyHomeSide spec)- CostOfServices -> FixedHomeSide (legacyHomeSide spec)- OperatingExpenses -> FixedHomeSide (legacyHomeSide spec)- InventoryShrinkageLoss -> FixedHomeSide (legacyHomeSide spec)- LossOnValuationOfMerchandise -> FixedHomeSide (legacyHomeSide spec)- Bonuses -> FixedHomeSide (legacyHomeSide spec)- RetirementBenefitExpenses -> FixedHomeSide (legacyHomeSide spec)- ProvisionForRepairs -> FixedHomeSide (legacyHomeSide spec)- ProvisionForBonuses -> FixedHomeSide (legacyHomeSide spec)- ProvisionForProductWarranties -> FixedHomeSide (legacyHomeSide spec)- ResearchAndDevelopmentExpenses -> FixedHomeSide (legacyHomeSide spec)- AmortizationOfGoodwill -> FixedHomeSide (legacyHomeSide spec)- AmortizationOfSoftware -> FixedHomeSide (legacyHomeSide spec)- AmortizationOfPatents -> FixedHomeSide (legacyHomeSide spec)- LeaseExpenses -> FixedHomeSide (legacyHomeSide spec)- IncorporationExpenses -> FixedHomeSide (legacyHomeSide spec)- StockIssuanceCosts -> FixedHomeSide (legacyHomeSide spec)- BusinessCommencementExpenses -> FixedHomeSide (legacyHomeSide spec)- DevelopmentExpenses -> FixedHomeSide (legacyHomeSide spec)- LossOnSalesOfElectronicallyRecordedReceivables -> FixedHomeSide (legacyHomeSide spec)- LossOnSalesOfReceivables -> FixedHomeSide (legacyHomeSide spec)- LossOnSalesOfSecurities -> FixedHomeSide (legacyHomeSide spec)- LossOnValuationOfSecurities -> FixedHomeSide (legacyHomeSide spec)- LossOnSalesOfInvestmentSecurities -> FixedHomeSide (legacyHomeSide spec)- LossOnFire -> FixedHomeSide (legacyHomeSide spec)- LossOnRetirementOfFixedAssets -> FixedHomeSide (legacyHomeSide spec)- LossOnReductionOfFixedAssets -> FixedHomeSide (legacyHomeSide spec)- AdditionalIncomeTaxesForPriorPeriods -> FixedHomeSide (legacyHomeSide spec)- RefundOfIncomeTaxes -> FixedHomeSide (legacyHomeSide spec)- PurchaseRebates -> FixedHomeSide (legacyHomeSide spec)- PurchaseAllowances -> FixedHomeSide (legacyHomeSide spec)- WelfareExpenses -> FixedHomeSide (legacyHomeSide spec)- MaintenanceExpenses -> FixedHomeSide (legacyHomeSide spec)- StatutoryWelfareExpenses -> FixedHomeSide (legacyHomeSide spec)- LandRentPaid -> FixedHomeSide (legacyHomeSide spec)- InsuranceExpense -> FixedHomeSide (legacyHomeSide spec)- RepairsExpense -> FixedHomeSide (legacyHomeSide spec)- StorageExpenses -> FixedHomeSide (legacyHomeSide spec)- MembershipFees -> FixedHomeSide (legacyHomeSide spec)- IncomeSummary -> ContextDependentHomeSide- SuspenseAccount -> ContextDependentHomeSide- ForeignExchangeGains -> FixedHomeSide (legacyHomeSide spec)- ForeignExchangeLosses -> FixedHomeSide (legacyHomeSide spec)- ContraAccountForGuaranteeObligations -> FixedHomeSide (legacyHomeSide spec)- GuaranteeObligations -> FixedHomeSide (legacyHomeSide spec)- IncomeTaxesAdjustment -> FixedHomeSide (legacyHomeSide spec)- BranchCurrentAccount -> FixedHomeSide (legacyHomeSide spec)- HeadOfficeCurrentAccount -> FixedHomeSide (legacyHomeSide spec)- NetIncomeAttributableToNCI -> FixedHomeSide (legacyHomeSide spec)- NetLossAttributableToNCI -> FixedHomeSide (legacyHomeSide spec)- TradingSecurities -> FixedHomeSide (legacyHomeSide spec)- HeldToMaturityBonds -> FixedHomeSide (legacyHomeSide spec)- SubsidiaryStocks -> FixedHomeSide (legacyHomeSide spec)- AffiliateStocks -> FixedHomeSide (legacyHomeSide spec)- AvailableForSaleSecurities -> FixedHomeSide (legacyHomeSide spec)- ConsumptionTaxRefundReceivable -> FixedHomeSide (legacyHomeSide spec)- PropertyTaxPayable -> FixedHomeSide (legacyHomeSide spec)- DepositsReceivedFromOfficers -> FixedHomeSide (legacyHomeSide spec)- AccountTitle -> NoPostingSide--legacyHomeSide :: AccountSpec -> Side-legacyHomeSide spec- | asIsContra spec = reverseSide (divisionSide (asDivision spec))- | otherwise = divisionSide (asDivision spec)--divisionSide :: AccountDivision -> Side-divisionSide Assets = Debit-divisionSide Cost = Debit-divisionSide Equity = Credit-divisionSide Liability = Credit-divisionSide Revenue = Credit--reverseSide :: Side -> Side-reverseSide Debit = Credit-reverseSide Credit = Debit-reverseSide Side = Side--reportingFor :: AccountTitles -> ReportingEligibility-reportingFor title = case title of- Cash -> StatementEligible- Deposits -> StatementEligible- CurrentDeposits -> StatementEligible- Securities -> StatementEligible- InvestmentSecurities -> StatementEligible- InvestmentInAssociate -> StatementEligible- LongTermNationalBonds -> StatementEligible- ShortTermNationalBonds -> StatementEligible- Products -> StatementEligible- Machinery -> StatementEligible- Building -> StatementEligible- Vehicle -> StatementEligible- StockInvestment -> StatementEligible- EquipmentInvestment -> StatementEligible- LongTermLoansReceivable -> StatementEligible- AccountsReceivable -> StatementEligible- ShortTermLoansReceivable -> StatementEligible- ReserveDepositReceivable -> StatementEligible- Gold -> StatementEligible- GovernmentService -> StatementEligible- CapitalStock -> StatementEligible- RetainedEarnings -> StatementEligible- LongTermLoansPayable -> StatementEligible- ShortTermLoansPayable -> StatementEligible- LoansPayable -> StatementEligible- ReserveForDepreciation -> StatementEligible- DepositPayable -> StatementEligible- LongTermNationalBondsPayable -> StatementEligible- ShortTermNationalBondsPayable -> StatementEligible- ReserveDepositPayable -> StatementEligible- CentralBankNotePayable -> StatementEligible- Depreciation -> StatementEligible- AmortizationExpense -> StatementEligible- SalesCost -> StatementEligible- BusinessTrip -> StatementEligible- Commutation -> StatementEligible- UtilitiesExpense -> StatementEligible- RentExpense -> StatementEligible- AdvertisingExpense -> StatementEligible- DeliveryExpenses -> StatementEligible- SuppliesExpenses -> StatementEligible- MiscellaneousExpenses -> StatementEligible- EntertainmentExpenses -> StatementEligible- MeetingExpenses -> StatementEligible- NewspaperBooksExpenses -> StatementEligible- WageExpenditure -> StatementEligible- InterestExpense -> StatementEligible- TaxesExpense -> StatementEligible- ConsumptionExpenditure -> StatementEligible- SubsidyExpense -> StatementEligible- CentralBankPaymentExpense -> StatementEligible- Purchases -> StatementEligible- NetIncome -> DerivedPresentation- ValueAdded -> StatementEligible- SubsidyIncome -> StatementEligible- NationalBondInterestEarned -> StatementEligible- DepositInterestEarned -> StatementEligible- GrossProfit -> DerivedPresentation- OrdinaryProfit -> DerivedPresentation- InterestEarned -> StatementEligible- ReceiptFee -> StatementEligible- RentalIncome -> StatementEligible- WageEarned -> StatementEligible- TaxesRevenue -> StatementEligible- CentralBankPaymentIncome -> StatementEligible- Sales -> StatementEligible- EquityInEarningsOfInvestee -> ContextualPresentation- NetLoss -> DerivedPresentation- PettyCash -> StatementEligible- NotesReceivable -> StatementEligible- ElectronicallyRecordedReceivable -> StatementEligible- CreditCardReceivable -> StatementEligible- NotesLoansReceivable -> StatementEligible- MerchandiseInventory -> StatementEligible- GoodsInTransit -> StatementEligible- AdvancesPaid -> StatementEligible- PrepaidExpenses -> StatementEligible- AccruedRevenue -> StatementEligible- OtherReceivables -> StatementEligible- PaymentsOnBehalf -> StatementEligible- SuspensePayments -> ContextualPresentation- ConsumptionTaxPaid -> StatementEligible- PrepaidCorporateIncomeTaxes -> StatementEligible- Land -> StatementEligible- Fixtures -> StatementEligible- Patent -> StatementEligible- Trademark -> StatementEligible- Software -> StatementEligible- CashOverShort -> NotPresented- AccountsPayable -> StatementEligible- NotesPayable -> StatementEligible- ElectronicallyRecordedObligations -> StatementEligible- NotesLoansPayable -> StatementEligible- BankOverdraft -> StatementEligible- AdvancesReceived -> StatementEligible- UnearnedRevenue -> StatementEligible- AccruedExpenses -> StatementEligible- OtherPayables -> StatementEligible- DepositsReceived -> StatementEligible- SuspenseReceipts -> ContextualPresentation- ConsumptionTaxReceived -> StatementEligible- AccruedConsumptionTax -> StatementEligible- AccruedCorporateIncomeTaxes -> StatementEligible- UnpaidDividends -> StatementEligible- AllowanceForDoubtfulAccounts -> StatementEligible- AccumulatedDepreciation -> StatementEligible- LegalRetainedEarnings -> StatementEligible- CumulativeTranslationAdjustment -> ContextualPresentation- ProvisionForDoubtfulAccounts -> StatementEligible- BadDebtLoss -> StatementEligible- LossOnSalesOfFixedAssets -> StatementEligible- LossOnSalesOfNotesReceivable -> StatementEligible- PaymentFees -> StatementEligible- MiscellaneousLoss -> StatementEligible- CorporateIncomeTaxes -> StatementEligible- CommunicationExpenses -> StatementEligible- GainOnSalesOfFixedAssets -> StatementEligible- RecoveryOfBadDebts -> StatementEligible- MiscellaneousIncome -> StatementEligible- ReversalOfAllowanceForDoubtfulAccounts -> StatementEligible- TimeDeposits -> StatementEligible- LoansReceivable -> StatementEligible- GiftCertificatesReceived -> StatementEligible- SecurityDepositsPaid -> StatementEligible- SuppliesOnHand -> StatementEligible- RawMaterials -> StatementEligible- ContractAssets -> StatementEligible- IncomeTaxesRefundReceivable -> StatementEligible- WorkInProcess -> StatementEligible- DeferredTaxAssets -> StatementEligible- LeasedAssets -> StatementEligible- ToolsAndInstruments -> StatementEligible- ConstructionInProgress -> StatementEligible- Goodwill -> StatementEligible- SoftwareInProgress -> StatementEligible- LongTermPrepaidExpenses -> StatementEligible- DishonoredNotesReceivable -> StatementEligible- PrepaidPensionCost -> StatementEligible- NetDefinedBenefitAsset -> StatementEligible- DepositsInSpecialAccounts -> StatementEligible- Structures -> StatementEligible- LeaseholdRights -> StatementEligible- NonOperatingNotesReceivable -> StatementEligible- NonOperatingElectronicallyRecordedReceivable -> StatementEligible- RefundLiabilities -> StatementEligible- NonOperatingNotesPayable -> StatementEligible- NonOperatingElectronicallyRecordedObligations -> StatementEligible- BonusesPayable -> StatementEligible- AllowanceForRepairs -> StatementEligible- AllowanceForProductWarranties -> StatementEligible- AllowanceForBonuses -> StatementEligible- DeferredTaxLiabilities -> StatementEligible- LeaseObligations -> StatementEligible- GuaranteeDepositsReceived -> StatementEligible- AllowanceForRetirementBenefits -> StatementEligible- LongTermOtherPayables -> StatementEligible- NetDefinedBenefitLiability -> StatementEligible- StockSubscriptionDeposits -> StatementEligible- LegalCapitalSurplus -> StatementEligible- OtherCapitalSurplus -> StatementEligible- DividendEqualizationReserve -> StatementEligible- RepairFundReserve -> StatementEligible- ConstructionFundReserve -> StatementEligible- GeneralReserve -> StatementEligible- ValuationDifferenceOnOtherSecurities -> StatementEligible- NonControllingInterests -> ContextualPresentation- CapitalSurplus -> StatementEligible- EarnedSurplus -> StatementEligible- ServiceRevenue -> StatementEligible- OperatingRevenue -> StatementEligible- GainOnSalesOfSecurities -> StatementEligible- GainOnValuationOfSecurities -> StatementEligible- DividendsReceived -> StatementEligible- InterestOnSecurities -> StatementEligible- GainOnSalesOfInvestmentSecurities -> StatementEligible- InsuranceGain -> StatementEligible- GainOnBargainPurchase -> StatementEligible- ReversalOfAllowanceForRepairs -> StatementEligible- ReversalOfAllowanceForBonuses -> StatementEligible- ReversalOfAllowanceForProductWarranties -> StatementEligible- GainOnDonationOfFixedAssets -> StatementEligible- GainOnNationalSubsidies -> StatementEligible- GainOnConstructionGrants -> StatementEligible- LandRentReceived -> StatementEligible- SalesRebates -> StatementEligible- SalesAllowances -> StatementEligible- CostOfServices -> StatementEligible- OperatingExpenses -> StatementEligible- InventoryShrinkageLoss -> StatementEligible- LossOnValuationOfMerchandise -> StatementEligible- Bonuses -> StatementEligible- RetirementBenefitExpenses -> StatementEligible- ProvisionForRepairs -> StatementEligible- ProvisionForBonuses -> StatementEligible- ProvisionForProductWarranties -> StatementEligible- ResearchAndDevelopmentExpenses -> StatementEligible- AmortizationOfGoodwill -> StatementEligible- AmortizationOfSoftware -> StatementEligible- AmortizationOfPatents -> StatementEligible- LeaseExpenses -> StatementEligible- IncorporationExpenses -> StatementEligible- StockIssuanceCosts -> StatementEligible- BusinessCommencementExpenses -> StatementEligible- DevelopmentExpenses -> StatementEligible- LossOnSalesOfElectronicallyRecordedReceivables -> StatementEligible- LossOnSalesOfReceivables -> StatementEligible- LossOnSalesOfSecurities -> StatementEligible- LossOnValuationOfSecurities -> StatementEligible- LossOnSalesOfInvestmentSecurities -> StatementEligible- LossOnFire -> StatementEligible- LossOnRetirementOfFixedAssets -> StatementEligible- LossOnReductionOfFixedAssets -> StatementEligible- AdditionalIncomeTaxesForPriorPeriods -> StatementEligible- RefundOfIncomeTaxes -> StatementEligible- PurchaseRebates -> StatementEligible- PurchaseAllowances -> StatementEligible- WelfareExpenses -> StatementEligible- MaintenanceExpenses -> StatementEligible- StatutoryWelfareExpenses -> StatementEligible- LandRentPaid -> StatementEligible- InsuranceExpense -> StatementEligible- RepairsExpense -> StatementEligible- StorageExpenses -> StatementEligible- MembershipFees -> StatementEligible- IncomeSummary -> NotPresented- SuspenseAccount -> ContextualPresentation- ForeignExchangeGains -> StatementEligible- ForeignExchangeLosses -> StatementEligible- ContraAccountForGuaranteeObligations -> StatementEligible- GuaranteeObligations -> StatementEligible- IncomeTaxesAdjustment -> StatementEligible- BranchCurrentAccount -> ContextualPresentation- HeadOfficeCurrentAccount -> ContextualPresentation- NetIncomeAttributableToNCI -> ContextualPresentation- NetLossAttributableToNCI -> ContextualPresentation- TradingSecurities -> StatementEligible- HeldToMaturityBonds -> StatementEligible- SubsidiaryStocks -> StatementEligible- AffiliateStocks -> StatementEligible- AvailableForSaleSecurities -> StatementEligible- ConsumptionTaxRefundReceivable -> StatementEligible- PropertyTaxPayable -> StatementEligible- DepositsReceivedFromOfficers -> StatementEligible- AccountTitle -> NotPresented---- | Every accepted non-canonical alias for an account. The JCCI overlay is--- generated from the frozen 2022 standard/permitted account-name fixture;--- shared permitted names intentionally remain shared so parsing reports an--- explicit ambiguity instead of silently choosing one account.-accountAliases :: AccountTitles -> [Text]-accountAliases title = L.nub (baseAliases <> jcciAliases title)- where- baseAliases = maybe [] asAliases (accountSpec title)---- | Look up metadata for an account title. The wildcard has no metadata.------ Complexity: O(1)-{-# INLINE accountSpec #-}-accountSpec :: AccountTitles -> Maybe AccountSpec-accountSpec Cash = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Cash"- , asNameJa = "現金"- , asLabelJa = "現金"- , asDescription = "Asset: Cash (現金)"- , asAliases = ["現金"]- }-accountSpec Deposits = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Savings deposits"- , asNameJa = "普通預金"- , asLabelJa = "普通預金"- , asDescription = "Asset: Savings deposits (普通預金)"- , asAliases = ["普通預金"]- }-accountSpec CurrentDeposits = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Current deposits"- , asNameJa = "当座預金"- , asLabelJa = "当座預金"- , asDescription = "Asset: Current deposits (当座預金)"- , asAliases = ["当座預金"]- }-accountSpec Securities = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Securities"- , asNameJa = "有価証券"- , asLabelJa = "有価証券"- , asDescription = "Asset: Securities (有価証券)"- , asAliases = ["有価証券"]- }-accountSpec InvestmentSecurities = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Investment securities"- , asNameJa = "投資有価証券"- , asLabelJa = "投資有価証券"- , asDescription = "Asset: Investment securities (投資有価証券)"- , asAliases = ["投資有価証券"]- }-accountSpec InvestmentInAssociate = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Investment in associate"- , asNameJa = "関係会社株式"- , asLabelJa = "関係会社株式"- , asDescription = "Asset: Investment in associate (関係会社株式). Carrying amount under the equity method (持分法適用投資勘定)."- , asAliases = []- }-accountSpec LongTermNationalBonds = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Long-term national bonds"- , asNameJa = "長期国債"- , asLabelJa = "長期国債"- , asDescription = "Asset: Long-term national bonds (長期国債)"- , asAliases = ["長期国債"]- }-accountSpec ShortTermNationalBonds = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Short-term national bonds"- , asNameJa = "短期国債"- , asLabelJa = "短期国債"- , asDescription = "Asset: Short-term national bonds (短期国債)"- , asAliases = ["短期国債"]- }-accountSpec Products = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Products"- , asNameJa = "商品"- , asLabelJa = "商品"- , asDescription = "Asset: Products (商品)。分記法用。3 分法 (仕入/売上/繰越商品) では 'MerchandiseInventory' を使う"- , asAliases = ["商品"]- }-accountSpec Machinery = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Machinery and equipment"- , asNameJa = "機械装置"- , asLabelJa = "機械装置"- , asDescription = "Asset: Machinery and equipment (機械装置)"- , asAliases = ["機械装置"]- }-accountSpec Building = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Real estate"- , asNameJa = "建物"- , asLabelJa = "建物"- , asDescription = "Asset: Real estate (建物)"- , asAliases = ["建物"]- }-accountSpec Vehicle = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Vehicles"- , asNameJa = "車両運搬具"- , asLabelJa = "車両運搬具"- , asDescription = "Asset: Vehicles (車両運搬具)"- , asAliases = ["車両運搬具"]- }-accountSpec StockInvestment = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Stock investment"- , asNameJa = "株式投資"- , asLabelJa = "株式投資"- , asDescription = "Asset: Stock investment (株式投資)"- , asAliases = ["株式投資"]- }-accountSpec EquipmentInvestment = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Equipment investment"- , asNameJa = "設備投資"- , asLabelJa = "設備投資"- , asDescription = "Asset: Equipment investment (設備投資)"- , asAliases = ["設備投資"]- }-accountSpec LongTermLoansReceivable = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Long-term loans receivable"- , asNameJa = "長期貸付金"- , asLabelJa = "長期貸付金"- , asDescription = "Asset: Long-term loans receivable (長期貸付金)"- , asAliases = ["長期貸付金"]- }-accountSpec AccountsReceivable = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Accounts receivable"- , asNameJa = "売掛金"- , asLabelJa = "売掛金"- , asDescription = "Asset: Accounts receivable (売掛金)"- , asAliases = ["売掛金", "a/r", "accounts receivable"]- }-accountSpec ShortTermLoansReceivable = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Short-term loans receivable"- , asNameJa = "短期貸付金"- , asLabelJa = "短期貸付金"- , asDescription = "Asset: Short-term loans receivable (短期貸付金)"- , asAliases = ["短期貸付金"]- }-accountSpec ReserveDepositReceivable = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Reserve deposits, asset side"- , asNameJa = "準備預金, 資産側 — 市中銀行が中央銀行に置く準備預金。SNA/マクロ系"- , asLabelJa = "準備預金"- , asDescription = "Asset: Reserve deposits, asset side (準備預金, 資産側 — 市中銀行が中央銀行に置く準備預金。SNA/マクロ系)"- , asAliases = ["準備預金"]- }-accountSpec Gold = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Gold"- , asNameJa = "金"- , asLabelJa = "金"- , asDescription = "Asset: Gold (金)"- , asAliases = ["金"]- }-accountSpec GovernmentService = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Government service"- , asNameJa = "政府サービス。SNA/マクロ系"- , asLabelJa = "政府サービス"- , asDescription = "Asset: Government service (政府サービス。SNA/マクロ系)"- , asAliases = ["政府サービス"]- }-accountSpec CapitalStock = Just AccountSpec- { asDivision = Equity- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Capital stock"- , asNameJa = "資本金"- , asLabelJa = "資本金"- , asDescription = "Equity: Capital stock (資本金)"- , asAliases = ["資本金"]- }-accountSpec RetainedEarnings = Just AccountSpec- { asDivision = Equity- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Retained earnings"- , asNameJa = "繰越利益剰余金"- , asLabelJa = "繰越利益剰余金"- , asDescription = "Equity: Retained earnings (繰越利益剰余金)"- , asAliases = ["繰越利益剰余金"]- }-accountSpec LongTermLoansPayable = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Long-term loans payable"- , asNameJa = "長期借入金"- , asLabelJa = "長期借入金"- , asDescription = "Liability: Long-term loans payable (長期借入金)"- , asAliases = ["長期借入金"]- }-accountSpec ShortTermLoansPayable = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Short-term loans payable"- , asNameJa = "短期借入金"- , asLabelJa = "短期借入金"- , asDescription = "Liability: Short-term loans payable (短期借入金)"- , asAliases = ["短期借入金"]- }-accountSpec LoansPayable = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Loans payable"- , asNameJa = "借入金"- , asLabelJa = "借入金"- , asDescription = "Liability: Loans payable (借入金)"- , asAliases = ["借入金"]- }-accountSpec ReserveForDepreciation = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Reserve for depreciation"- , asNameJa = "減価償却引当金 — SNA/マクロ系の旧称。簿記の間接法には 'AccumulatedDepreciation' (減価償却累計額) を使う"- , asLabelJa = "減価償却引当金"- , asDescription = "Liability: Reserve for depreciation (減価償却引当金 — SNA/マクロ系の旧称。簿記の間接法には 'AccumulatedDepreciation' (減価償却累計額) を使う)"- , asAliases = ["減価償却引当金"]- }-accountSpec DepositPayable = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Deposits accepted"- , asNameJa = "受入預金 — 銀行側の負債としての預金。SNA/マクロ系。従業員等からの預り金は 'DepositsReceived'"- , asLabelJa = "受入預金"- , asDescription = "Liability: Deposits accepted (受入預金 — 銀行側の負債としての預金。SNA/マクロ系。従業員等からの預り金は 'DepositsReceived')"- , asAliases = ["受入預金"]- }-accountSpec LongTermNationalBondsPayable = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Long-term national bonds payable"- , asNameJa = "長期国債, 発行側"- , asLabelJa = "長期国債"- , asDescription = "Liability: Long-term national bonds payable (長期国債, 発行側)"- , asAliases = ["長期国債"]- }-accountSpec ShortTermNationalBondsPayable = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Short-term national bonds payable"- , asNameJa = "短期国債, 発行側"- , asLabelJa = "短期国債"- , asDescription = "Liability: Short-term national bonds payable (短期国債, 発行側)"- , asAliases = ["短期国債"]- }-accountSpec ReserveDepositPayable = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Reserve deposits, liability side"- , asNameJa = "準備預金, 負債側 — 中央銀行が受け入れる準備預金。SNA/マクロ系"- , asLabelJa = "準備預金"- , asDescription = "Liability: Reserve deposits, liability side (準備預金, 負債側 — 中央銀行が受け入れる準備預金。SNA/マクロ系)。※簿記の買掛金は 'AccountsPayable' を使うこと (旧 examples が本科目を買掛金の代用にしていた経緯あり)"- , asAliases = ["準備預金"]- }-accountSpec CentralBankNotePayable = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Central bank notes"- , asNameJa = "発行銀行券。SNA/マクロ系"- , asLabelJa = "発行銀行券"- , asDescription = "Liability: Central bank notes (発行銀行券。SNA/マクロ系)"- , asAliases = ["発行銀行券"]- }-accountSpec Depreciation = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Depreciation"- , asNameJa = "減価償却費"- , asLabelJa = "減価償却費"- , asDescription = "Expense: Depreciation (減価償却費)"- , asAliases = ["減価償却費"]- }-accountSpec AmortizationExpense = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Amortization expense for intangibles"- , asNameJa = "無形固定資産償却費 — 特許権・商標権・ソフトウェア等の無形資産の償却費。有形の 'Depreciation' (減価償却費) と区別される"- , asLabelJa = "無形固定資産償却費"- , asDescription = "Expense: Amortization expense for intangibles (無形固定資産償却費 — 特許権・商標権・ソフトウェア等の無形資産の償却費。有形の 'Depreciation' (減価償却費) と区別される)"- , asAliases = []- }-accountSpec SalesCost = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Cost of sales"- , asNameJa = "売上原価"- , asLabelJa = "売上原価"- , asDescription = "Expense: Cost of sales (売上原価)"- , asAliases = ["売上原価", "cogs", "cost of sales"]- }-accountSpec BusinessTrip = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Travel and transportation"- , asNameJa = "旅費交通費"- , asLabelJa = "旅費交通費"- , asDescription = "Expense: Travel and transportation (旅費交通費)"- , asAliases = ["旅費交通費"]- }-accountSpec Commutation = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Communication"- , asNameJa = "通信費 — 旧称。新規コードでは 'CommunicationExpenses' を使う"- , asLabelJa = "通信費"- , asDescription = "Expense: Communication (通信費 — 旧称。新規コードでは 'CommunicationExpenses' を使う)"- , asAliases = ["通信費"]- }-accountSpec UtilitiesExpense = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Utilities"- , asNameJa = "水道光熱費"- , asLabelJa = "水道光熱費"- , asDescription = "Expense: Utilities (水道光熱費)"- , asAliases = ["水道光熱費"]- }-accountSpec RentExpense = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Rent"- , asNameJa = "支払家賃"- , asLabelJa = "支払家賃"- , asDescription = "Expense: Rent (支払家賃)"- , asAliases = ["支払家賃"]- }-accountSpec AdvertisingExpense = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Advertising"- , asNameJa = "広告宣伝費"- , asLabelJa = "広告宣伝費"- , asDescription = "Expense: Advertising (広告宣伝費)"- , asAliases = ["広告宣伝費"]- }-accountSpec DeliveryExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Delivery"- , asNameJa = "発送費"- , asLabelJa = "発送費"- , asDescription = "Expense: Delivery (発送費)"- , asAliases = ["発送費", "荷造運賃"]- }-accountSpec SuppliesExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Supplies"- , asNameJa = "消耗品費"- , asLabelJa = "消耗品費"- , asDescription = "Expense: Supplies (消耗品費)"- , asAliases = ["消耗品費"]- }-accountSpec MiscellaneousExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Miscellaneous"- , asNameJa = "雑費"- , asLabelJa = "雑費"- , asDescription = "Expense: Miscellaneous (雑費)"- , asAliases = ["雑費"]- }-accountSpec EntertainmentExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Entertainment expenses"- , asNameJa = "交際費"- , asLabelJa = "交際費"- , asDescription = "Expense: Entertainment expenses (交際費)"- , asAliases = ["交際費", "接待交際費"]- }-accountSpec MeetingExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Meeting expenses"- , asNameJa = "会議費"- , asLabelJa = "会議費"- , asDescription = "Expense: Meeting expenses (会議費)"- , asAliases = ["会議費"]- }-accountSpec NewspaperBooksExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Newspapers and books"- , asNameJa = "新聞図書費"- , asLabelJa = "新聞図書費"- , asDescription = "Expense: Newspapers and books (新聞図書費)"- , asAliases = ["新聞図書費"]- }-accountSpec WageExpenditure = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Wages"- , asNameJa = "給料"- , asLabelJa = "給料"- , asDescription = "Expense: Wages (給料)"- , asAliases = ["給料"]- }-accountSpec InterestExpense = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Interest expense"- , asNameJa = "支払利息"- , asLabelJa = "支払利息"- , asDescription = "Expense: Interest expense (支払利息)"- , asAliases = ["支払利息"]- }-accountSpec TaxesExpense = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Taxes"- , asNameJa = "租税公課"- , asLabelJa = "租税公課"- , asDescription = "Expense: Taxes (租税公課)"- , asAliases = ["租税公課"]- }-accountSpec ConsumptionExpenditure = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Consumption expenditure"- , asNameJa = "消費支出。SNA/マクロ系"- , asLabelJa = "消費支出"- , asDescription = "Expense: Consumption expenditure (消費支出。SNA/マクロ系)"- , asAliases = ["消費支出"]- }-accountSpec SubsidyExpense = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Subsidy expenditure"- , asNameJa = "補助金支出。SNA/マクロ系"- , asLabelJa = "補助金支出"- , asDescription = "Expense: Subsidy expenditure (補助金支出。SNA/マクロ系)"- , asAliases = ["補助金支出"]- }-accountSpec CentralBankPaymentExpense = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Central bank payment to treasury"- , asNameJa = "国庫納付金支出。SNA/マクロ系"- , asLabelJa = "国庫納付金支出"- , asDescription = "Expense: Central bank payment to treasury (国庫納付金支出。SNA/マクロ系)"- , asAliases = ["国庫納付金支出"]- }-accountSpec Purchases = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Purchases"- , asNameJa = "仕入"- , asLabelJa = "仕入"- , asDescription = "Expense: Purchases (仕入)"- , asAliases = ["仕入"]- }-accountSpec NetIncome = Just AccountSpec- { asDivision = Cost- , asClosing = NoClose- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Net income"- , asNameJa = "当期純利益 — 決算振替用。借方側に立つため Expense 区分"- , asLabelJa = "当期純利益"- , asDescription = "Expense: Net income (当期純利益 — 決算振替用。借方側に立つため Expense 区分)"- , asAliases = ["当期純利益"]- }-accountSpec ValueAdded = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Value added"- , asNameJa = "付加価値。SNA/マクロ系"- , asLabelJa = "付加価値"- , asDescription = "Revenue: Value added (付加価値。SNA/マクロ系)"- , asAliases = ["付加価値"]- }-accountSpec SubsidyIncome = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Subsidy income"- , asNameJa = "補助金収入。SNA/マクロ系"- , asLabelJa = "補助金収入"- , asDescription = "Revenue: Subsidy income (補助金収入。SNA/マクロ系)"- , asAliases = ["補助金収入"]- }-accountSpec NationalBondInterestEarned = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "National bond interest earned"- , asNameJa = "国債利息収入"- , asLabelJa = "国債利息収入"- , asDescription = "Revenue: National bond interest earned (国債利息収入)"- , asAliases = ["国債利息収入"]- }-accountSpec DepositInterestEarned = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Deposit interest earned"- , asNameJa = "預金利息収入"- , asLabelJa = "預金利息収入"- , asDescription = "Revenue: Deposit interest earned (預金利息収入)"- , asAliases = ["預金利息収入"]- }-accountSpec GrossProfit = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Gross profit"- , asNameJa = "売上総利益 — 決算振替用"- , asLabelJa = "売上総利益"- , asDescription = "Revenue: Gross profit (売上総利益 — 決算振替用)"- , asAliases = ["売上総利益"]- }-accountSpec OrdinaryProfit = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Ordinary profit"- , asNameJa = "経常利益 — 決算振替用"- , asLabelJa = "経常利益"- , asDescription = "Revenue: Ordinary profit (経常利益 — 決算振替用)"- , asAliases = ["経常利益"]- }-accountSpec InterestEarned = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Interest earned"- , asNameJa = "受取利息"- , asLabelJa = "受取利息"- , asDescription = "Revenue: Interest earned (受取利息)"- , asAliases = ["受取利息"]- }-accountSpec ReceiptFee = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Receipt fee"- , asNameJa = "受取手数料。支払側は 'PaymentFees'"- , asLabelJa = "受取手数料"- , asDescription = "Revenue: Receipt fee (受取手数料。支払側は 'PaymentFees')"- , asAliases = ["受取手数料"]- }-accountSpec RentalIncome = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Rental income"- , asNameJa = "受取家賃"- , asLabelJa = "受取家賃"- , asDescription = "Revenue: Rental income (受取家賃)"- , asAliases = ["受取家賃"]- }-accountSpec WageEarned = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Wage income"- , asNameJa = "賃金収入。SNA/マクロ系"- , asLabelJa = "賃金収入"- , asDescription = "Revenue: Wage income (賃金収入。SNA/マクロ系)"- , asAliases = ["賃金収入"]- }-accountSpec TaxesRevenue = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Tax revenue"- , asNameJa = "租税収入。SNA/マクロ系"- , asLabelJa = "租税収入"- , asDescription = "Revenue: Tax revenue (租税収入。SNA/マクロ系)"- , asAliases = ["租税収入"]- }-accountSpec CentralBankPaymentIncome = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Central bank payment to treasury"- , asNameJa = "国庫納付金収入。SNA/マクロ系"- , asLabelJa = "国庫納付金収入"- , asDescription = "Revenue: Central bank payment to treasury (国庫納付金収入。SNA/マクロ系)"- , asAliases = ["国庫納付金収入"]- }-accountSpec Sales = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Sales"- , asNameJa = "売上"- , asLabelJa = "売上"- , asDescription = "Revenue: Sales (売上)"- , asAliases = ["売上"]- }-accountSpec EquityInEarningsOfInvestee = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Equity in earnings of investee"- , asNameJa = "持分法による投資利益"- , asLabelJa = "持分法による投資利益"- , asDescription = "Revenue: Equity in earnings of investee (持分法による投資利益). Recognized under the equity method."- , asAliases = []- }-accountSpec NetLoss = Just AccountSpec- { asDivision = Revenue- , asClosing = NoClose- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Net loss"- , asNameJa = "当期純損失 — 決算振替用。貸方側に立つため Revenue 区分"- , asLabelJa = "当期純損失"- , asDescription = "Revenue: Net loss (当期純損失 — 決算振替用。貸方側に立つため Revenue 区分)"- , asAliases = ["当期純損失"]- }-accountSpec PettyCash = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Petty cash"- , asNameJa = "小口現金"- , asLabelJa = "小口現金"- , asDescription = "Asset: Petty cash (小口現金)"- , asAliases = ["小口現金"]- }-accountSpec NotesReceivable = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Notes receivable"- , asNameJa = "受取手形"- , asLabelJa = "受取手形"- , asDescription = "Asset: Notes receivable (受取手形)"- , asAliases = ["受取手形"]- }-accountSpec ElectronicallyRecordedReceivable = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Electronically recorded monetary claims"- , asNameJa = "電子記録債権"- , asLabelJa = "電子記録債権"- , asDescription = "Asset: Electronically recorded monetary claims (電子記録債権)"- , asAliases = ["電子記録債権"]- }-accountSpec CreditCardReceivable = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Credit card receivable"- , asNameJa = "クレジット売掛金"- , asLabelJa = "クレジット売掛金"- , asDescription = "Asset: Credit card receivable (クレジット売掛金)"- , asAliases = ["クレジット売掛金"]- }-accountSpec NotesLoansReceivable = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Loans receivable on notes"- , asNameJa = "手形貸付金"- , asLabelJa = "手形貸付金"- , asDescription = "Asset: Loans receivable on notes (手形貸付金)"- , asAliases = ["手形貸付金"]- }-accountSpec MerchandiseInventory = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Merchandise inventory"- , asNameJa = "繰越商品"- , asLabelJa = "繰越商品"- , asDescription = "Asset: Merchandise inventory (繰越商品). Use under the periodic/3-account method (3 分法: Purchases/Sales/MerchandiseInventory). For 分記法, which records the cost of the goods and the gain on sales at each sale, use 'Products' instead."- , asAliases = ["繰越商品"]- }-accountSpec GoodsInTransit = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Goods in transit"- , asNameJa = "未着品"- , asLabelJa = "未着品"- , asDescription = "Asset: Goods in transit (未着品)"- , asAliases = ["未着品"]- }-accountSpec AdvancesPaid = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Advances paid"- , asNameJa = "前払金"- , asLabelJa = "前払金"- , asDescription = "Asset: Advances paid (前払金)"- , asAliases = ["前払金"]- }-accountSpec PrepaidExpenses = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Prepaid expenses"- , asNameJa = "前払費用"- , asLabelJa = "前払費用"- , asDescription = "Asset: Prepaid expenses (前払費用), deferral account (経過勘定)"- , asAliases = ["前払費用"]- }-accountSpec AccruedRevenue = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Accrued revenue"- , asNameJa = "未収収益"- , asLabelJa = "未収収益"- , asDescription = "Asset: Accrued revenue (未収収益), accrual account (経過勘定)"- , asAliases = ["未収収益"]- }-accountSpec OtherReceivables = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Other receivables"- , asNameJa = "未収入金"- , asLabelJa = "未収入金"- , asDescription = "Asset: Other receivables (未収入金)"- , asAliases = ["未収入金"]- }-accountSpec PaymentsOnBehalf = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Payments made on behalf"- , asNameJa = "立替金"- , asLabelJa = "立替金"- , asDescription = "Asset: Payments made on behalf (立替金)"- , asAliases = ["立替金"]- }-accountSpec SuspensePayments = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Suspense payments"- , asNameJa = "仮払金"- , asLabelJa = "仮払金"- , asDescription = "Asset: Suspense payments (仮払金)"- , asAliases = ["仮払金"]- }-accountSpec ConsumptionTaxPaid = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Consumption tax paid"- , asNameJa = "仮払消費税"- , asLabelJa = "仮払消費税"- , asDescription = "Asset: Consumption tax paid (仮払消費税)"- , asAliases = ["仮払消費税"]- }-accountSpec PrepaidCorporateIncomeTaxes = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Prepaid corporate income taxes"- , asNameJa = "仮払法人税等"- , asLabelJa = "仮払法人税等"- , asDescription = "Asset: Prepaid corporate income taxes (仮払法人税等)"- , asAliases = ["仮払法人税等"]- }-accountSpec Land = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Land"- , asNameJa = "土地"- , asLabelJa = "土地"- , asDescription = "Asset: Land (土地)"- , asAliases = ["土地"]- }-accountSpec Fixtures = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Fixtures and equipment"- , asNameJa = "備品"- , asLabelJa = "備品"- , asDescription = "Asset: Fixtures and equipment (備品)"- , asAliases = ["備品", "器具備品"]- }-accountSpec Patent = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Patent"- , asNameJa = "特許権"- , asLabelJa = "特許権"- , asDescription = "Asset: Patent (特許権)"- , asAliases = ["特許権"]- }-accountSpec Trademark = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Trademark"- , asNameJa = "商標権"- , asLabelJa = "商標権"- , asDescription = "Asset: Trademark (商標権)"- , asAliases = ["商標権"]- }-accountSpec Software = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Software"- , asNameJa = "ソフトウェア"- , asLabelJa = "ソフトウェア"- , asDescription = "Asset: Software (ソフトウェア)"- , asAliases = ["ソフトウェア"]- }-accountSpec CashOverShort = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Cash over and short"- , asNameJa = "現金過不足"- , asLabelJa = "現金過不足"- , asDescription = "Asset: Cash over and short (現金過不足), a temporary/suspense account cleared at closing to MiscellaneousIncome/MiscellaneousLoss"- , asAliases = ["現金過不足"]- }-accountSpec AccountsPayable = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Accounts payable"- , asNameJa = "買掛金"- , asLabelJa = "買掛金"- , asDescription = "Liability: Accounts payable (買掛金)"- , asAliases = ["買掛金", "a/p", "accounts payable"]- }-accountSpec NotesPayable = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Notes payable"- , asNameJa = "支払手形"- , asLabelJa = "支払手形"- , asDescription = "Liability: Notes payable (支払手形)"- , asAliases = ["支払手形"]- }-accountSpec ElectronicallyRecordedObligations = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Electronically recorded monetary obligations"- , asNameJa = "電子記録債務"- , asLabelJa = "電子記録債務"- , asDescription = "Liability: Electronically recorded monetary obligations (電子記録債務)"- , asAliases = ["電子記録債務"]- }-accountSpec NotesLoansPayable = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Loans payable on notes"- , asNameJa = "手形借入金"- , asLabelJa = "手形借入金"- , asDescription = "Liability: Loans payable on notes (手形借入金)"- , asAliases = ["手形借入金"]- }-accountSpec BankOverdraft = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Bank overdraft"- , asNameJa = "当座借越"- , asLabelJa = "当座借越"- , asDescription = "Liability: Bank overdraft (当座借越)"- , asAliases = ["当座借越"]- }-accountSpec AdvancesReceived = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Advances received"- , asNameJa = "前受金"- , asLabelJa = "前受金"- , asDescription = "Liability: Advances received (前受金)"- , asAliases = ["前受金"]- }-accountSpec UnearnedRevenue = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Unearned revenue"- , asNameJa = "前受収益"- , asLabelJa = "前受収益"- , asDescription = "Liability: Unearned revenue (前受収益), deferral account (経過勘定)"- , asAliases = ["前受収益"]- }-accountSpec AccruedExpenses = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Accrued expenses"- , asNameJa = "未払費用"- , asLabelJa = "未払費用"- , asDescription = "Liability: Accrued expenses (未払費用), accrual account (経過勘定)"- , asAliases = ["未払費用"]- }-accountSpec OtherPayables = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Other payables"- , asNameJa = "未払金"- , asLabelJa = "未払金"- , asDescription = "Liability: Other payables (未払金)"- , asAliases = ["未払金"]- }-accountSpec DepositsReceived = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Deposits received"- , asNameJa = "預り金"- , asLabelJa = "預り金"- , asDescription = "Liability: Deposits received (預り金)"- , asAliases = ["預り金"]- }-accountSpec SuspenseReceipts = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Suspense receipts"- , asNameJa = "仮受金"- , asLabelJa = "仮受金"- , asDescription = "Liability: Suspense receipts (仮受金)"- , asAliases = ["仮受金"]- }-accountSpec ConsumptionTaxReceived = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Consumption tax received"- , asNameJa = "仮受消費税"- , asLabelJa = "仮受消費税"- , asDescription = "Liability: Consumption tax received (仮受消費税)"- , asAliases = ["仮受消費税"]- }-accountSpec AccruedConsumptionTax = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Accrued (unpaid) consumption tax"- , asNameJa = "未払消費税"- , asLabelJa = "未払消費税"- , asDescription = "Liability: Accrued (unpaid) consumption tax (未払消費税)"- , asAliases = ["未払消費税"]- }-accountSpec AccruedCorporateIncomeTaxes = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Accrued (unpaid) corporate income taxes"- , asNameJa = "未払法人税等"- , asLabelJa = "未払法人税等"- , asDescription = "Liability: Accrued (unpaid) corporate income taxes (未払法人税等)"- , asAliases = ["未払法人税等"]- }-accountSpec UnpaidDividends = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Unpaid dividends"- , asNameJa = "未払配当金"- , asLabelJa = "未払配当金"- , asDescription = "Liability: Unpaid dividends (未払配当金)"- , asAliases = ["未払配当金"]- }-accountSpec AllowanceForDoubtfulAccounts = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = True- , asFixedCurrent = Current- , asNameEn = "Allowance for doubtful accounts"- , asNameJa = "貸倒引当金"- , asLabelJa = "貸倒引当金"- , asDescription = "Asset (contra): Allowance for doubtful accounts (貸倒引当金), a credit-balance valuation account (評価勘定) deducted from receivables. Home side is Credit because it is a contra asset (isContra); values stay non-negative and the Hat/Not structure is intact. B/S deduction (net) presentation is the ExchangeAlgebra.IO.Output module's job."- , asAliases = ["貸倒引当金"]- }-accountSpec AccumulatedDepreciation = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = True- , asFixedCurrent = Fixed- , asNameEn = "Accumulated depreciation"- , asNameJa = "減価償却累計額"- , asLabelJa = "減価償却累計額"- , asDescription = "Asset (contra): Accumulated depreciation (減価償却累計額), a credit-balance valuation account (評価勘定) under the indirect method (間接法), deducted from the related depreciable assets. Home side is Credit because it is a contra asset (isContra). This is the canonical bookkeeping account for accumulated depreciation; the existing 'ReserveForDepreciation' is retained as the legacy SNA/macro-accounting name."- , asAliases = ["減価償却累計額"]- }-accountSpec LegalRetainedEarnings = Just AccountSpec- { asDivision = Equity- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Legal (appropriated) retained earnings reserve"- , asNameJa = "利益準備金"- , asLabelJa = "利益準備金"- , asDescription = "Equity: Legal (appropriated) retained earnings reserve (利益準備金)"- , asAliases = ["利益準備金"]- }-accountSpec CumulativeTranslationAdjustment = Just AccountSpec- { asDivision = Equity- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Cumulative translation adjustment"- , asNameJa = "為替換算調整勘定; 在外子会社等の外貨建財務諸表の換算差額を計上する OCI/資本の部の項目"- , asLabelJa = "為替換算調整勘定"- , asDescription = "Equity: Cumulative translation adjustment (為替換算調整勘定; 在外子会社等の外貨建財務諸表の換算差額を計上する OCI/資本の部の項目)"- , asAliases = []- }-accountSpec ProvisionForDoubtfulAccounts = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Provision for doubtful accounts"- , asNameJa = "貸倒引当金繰入"- , asLabelJa = "貸倒引当金繰入"- , asDescription = "Expense: Provision for doubtful accounts (貸倒引当金繰入)"- , asAliases = ["貸倒引当金繰入"]- }-accountSpec BadDebtLoss = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Bad debt loss"- , asNameJa = "貸倒損失"- , asLabelJa = "貸倒損失"- , asDescription = "Expense: Bad debt loss (貸倒損失)"- , asAliases = ["貸倒損失"]- }-accountSpec LossOnSalesOfFixedAssets = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Loss on sales of fixed assets"- , asNameJa = "固定資産売却損"- , asLabelJa = "固定資産売却損"- , asDescription = "Expense: Loss on sales of fixed assets (固定資産売却損)"- , asAliases = ["固定資産売却損"]- }-accountSpec LossOnSalesOfNotesReceivable = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Loss on sales of notes receivable"- , asNameJa = "手形売却損"- , asLabelJa = "手形売却損"- , asDescription = "Expense: Loss on sales of notes receivable (手形売却損)"- , asAliases = ["手形売却損"]- }-accountSpec PaymentFees = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Payment fees / fees paid"- , asNameJa = "支払手数料"- , asLabelJa = "支払手数料"- , asDescription = "Expense: Payment fees / fees paid (支払手数料), the debit counterpart of 'ReceiptFee'"- , asAliases = ["支払手数料"]- }-accountSpec MiscellaneousLoss = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Miscellaneous loss"- , asNameJa = "雑損"- , asLabelJa = "雑損"- , asDescription = "Expense: Miscellaneous loss (雑損)"- , asAliases = ["雑損"]- }-accountSpec CorporateIncomeTaxes = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Corporate income taxes"- , asNameJa = "法人税等"- , asLabelJa = "法人税等"- , asDescription = "Expense: Corporate income taxes (法人税等)"- , asAliases = ["法人税等"]- }-accountSpec CommunicationExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Communication expenses"- , asNameJa = "通信費"- , asLabelJa = "通信費"- , asDescription = "Expense: Communication expenses (通信費). Explicitly named counterpart of the legacy 'Commutation' (also \"Communication\"); 'Commutation' is retained for backward compatibility."- , asAliases = ["通信費"]- }-accountSpec GainOnSalesOfFixedAssets = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Gain on sales of fixed assets"- , asNameJa = "固定資産売却益"- , asLabelJa = "固定資産売却益"- , asDescription = "Revenue: Gain on sales of fixed assets (固定資産売却益)"- , asAliases = ["固定資産売却益"]- }-accountSpec RecoveryOfBadDebts = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Recovery of bad debts written off"- , asNameJa = "償却債権取立益"- , asLabelJa = "償却債権取立益"- , asDescription = "Revenue: Recovery of bad debts written off (償却債権取立益)"- , asAliases = ["償却債権取立益"]- }-accountSpec MiscellaneousIncome = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Miscellaneous income"- , asNameJa = "雑益"- , asLabelJa = "雑益"- , asDescription = "Revenue: Miscellaneous income (雑益)"- , asAliases = ["雑益"]- }-accountSpec ReversalOfAllowanceForDoubtfulAccounts = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Reversal of allowance for doubtful accounts"- , asNameJa = "貸倒引当金戻入"- , asLabelJa = "貸倒引当金戻入"- , asDescription = "Revenue: Reversal of allowance for doubtful accounts (貸倒引当金戻入). Credit counterpart used by the 差額補充法/洗替法 when the estimated allowance is smaller than the existing balance (the excess of 'AllowanceForDoubtfulAccounts' is released)."- , asAliases = ["貸倒引当金戻入"]- }-accountSpec TimeDeposits = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Time deposits"- , asNameJa = "定期預金"- , asLabelJa = "定期預金"- , asDescription = "Asset: Time deposits (定期預金)"- , asAliases = ["定期預金"]- }-accountSpec LoansReceivable = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Loans receivable"- , asNameJa = "貸付金"- , asLabelJa = "貸付金"- , asDescription = "Asset: Loans receivable (貸付金)"- , asAliases = ["貸付金"]- }-accountSpec GiftCertificatesReceived = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Gift certificates received"- , asNameJa = "受取商品券"- , asLabelJa = "受取商品券"- , asDescription = "Asset: Gift certificates received (受取商品券)"- , asAliases = ["受取商品券"]- }-accountSpec SecurityDepositsPaid = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Guarantee deposits"- , asNameJa = "差入保証金"- , asLabelJa = "差入保証金"- , asDescription = "Asset: Guarantee deposits (差入保証金)"- , asAliases = ["差入保証金"]- }-accountSpec SuppliesOnHand = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Supplies"- , asNameJa = "貯蔵品"- , asLabelJa = "貯蔵品"- , asDescription = "Asset: Supplies (貯蔵品)"- , asAliases = ["貯蔵品"]- }-accountSpec RawMaterials = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Raw materials"- , asNameJa = "原材料"- , asLabelJa = "原材料"- , asDescription = "Asset: Raw materials (原材料)"- , asAliases = ["原材料", "材料"]- }-accountSpec ContractAssets = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Contract assets"- , asNameJa = "契約資産"- , asLabelJa = "契約資産"- , asDescription = "Asset: Contract assets (契約資産)"- , asAliases = ["契約資産"]- }-accountSpec IncomeTaxesRefundReceivable = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Income taxes refund receivable"- , asNameJa = "未収還付法人税等"- , asLabelJa = "未収還付法人税等"- , asDescription = "Asset: Income taxes refund receivable (未収還付法人税等)"- , asAliases = ["未収還付法人税等"]- }-accountSpec WorkInProcess = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Work in process"- , asNameJa = "仕掛品"- , asLabelJa = "仕掛品"- , asDescription = "Asset: Work in process (仕掛品)"- , asAliases = ["仕掛品"]- }-accountSpec DeferredTaxAssets = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Deferred tax assets"- , asNameJa = "繰延税金資産"- , asLabelJa = "繰延税金資産"- , asDescription = "Asset: Deferred tax assets (繰延税金資産)"- , asAliases = ["繰延税金資産"]- }-accountSpec LeasedAssets = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Leased assets"- , asNameJa = "リース資産"- , asLabelJa = "リース資産"- , asDescription = "Asset: Leased assets (リース資産)"- , asAliases = ["リース資産"]- }-accountSpec ToolsAndInstruments = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Tools and instruments"- , asNameJa = "工具器具"- , asLabelJa = "工具器具"- , asDescription = "Asset: Tools and instruments (工具器具)"- , asAliases = ["工具器具"]- }-accountSpec ConstructionInProgress = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Construction in progress"- , asNameJa = "建設仮勘定"- , asLabelJa = "建設仮勘定"- , asDescription = "Asset: Construction in progress (建設仮勘定)"- , asAliases = ["建設仮勘定"]- }-accountSpec Goodwill = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Goodwill"- , asNameJa = "のれん"- , asLabelJa = "のれん"- , asDescription = "Asset: Goodwill (のれん)"- , asAliases = ["のれん"]- }-accountSpec SoftwareInProgress = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Software in progress"- , asNameJa = "ソフトウェア仮勘定"- , asLabelJa = "ソフトウェア仮勘定"- , asDescription = "Asset: Software in progress (ソフトウェア仮勘定)"- , asAliases = ["ソフトウェア仮勘定"]- }-accountSpec LongTermPrepaidExpenses = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Long-term prepaid expenses"- , asNameJa = "長期前払費用"- , asLabelJa = "長期前払費用"- , asDescription = "Asset: Long-term prepaid expenses (長期前払費用)"- , asAliases = ["長期前払費用"]- }-accountSpec DishonoredNotesReceivable = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Dishonored notes receivable"- , asNameJa = "不渡手形"- , asLabelJa = "不渡手形"- , asDescription = "Asset: Dishonored notes receivable (不渡手形)"- , asAliases = ["不渡手形"]- }-accountSpec PrepaidPensionCost = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Prepaid pension costs"- , asNameJa = "前払年金費用"- , asLabelJa = "前払年金費用"- , asDescription = "Asset: Prepaid pension costs (前払年金費用)"- , asAliases = ["前払年金費用"]- }-accountSpec NetDefinedBenefitAsset = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Retirement benefit asset"- , asNameJa = "退職給付に係る資産"- , asLabelJa = "退職給付に係る資産"- , asDescription = "Asset: Retirement benefit asset (退職給付に係る資産)"- , asAliases = ["退職給付に係る資産"]- }-accountSpec DepositsInSpecialAccounts = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Deposits in special accounts"- , asNameJa = "別段預金"- , asLabelJa = "別段預金"- , asDescription = "Asset: Deposits in special accounts (別段預金)"- , asAliases = ["別段預金"]- }-accountSpec Structures = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Structures"- , asNameJa = "構築物"- , asLabelJa = "構築物"- , asDescription = "Asset: Structures (構築物)"- , asAliases = ["構築物"]- }-accountSpec LeaseholdRights = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Leasehold interests in land"- , asNameJa = "借地権"- , asLabelJa = "借地権"- , asDescription = "Asset: Leasehold interests in land (借地権)"- , asAliases = ["借地権"]- }-accountSpec NonOperatingNotesReceivable = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Non-operating notes receivable"- , asNameJa = "営業外受取手形"- , asLabelJa = "営業外受取手形"- , asDescription = "Asset: Non-operating notes receivable (営業外受取手形)"- , asAliases = ["営業外受取手形"]- }-accountSpec NonOperatingElectronicallyRecordedReceivable = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Electronically recorded monetary claims - non-operating"- , asNameJa = "営業外電子記録債権"- , asLabelJa = "営業外電子記録債権"- , asDescription = "Asset: Electronically recorded monetary claims - non-operating (営業外電子記録債権)"- , asAliases = ["営業外電子記録債権"]- }-accountSpec RefundLiabilities = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Refund liabilities"- , asNameJa = "返金負債"- , asLabelJa = "返金負債"- , asDescription = "Liability: Refund liabilities (返金負債)"- , asAliases = ["返金負債"]- }-accountSpec NonOperatingNotesPayable = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Non-operating notes payable"- , asNameJa = "営業外支払手形"- , asLabelJa = "営業外支払手形"- , asDescription = "Liability: Non-operating notes payable (営業外支払手形)"- , asAliases = ["営業外支払手形"]- }-accountSpec NonOperatingElectronicallyRecordedObligations = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Electronically recorded obligations - non-operating"- , asNameJa = "営業外電子記録債務"- , asLabelJa = "営業外電子記録債務"- , asDescription = "Liability: Electronically recorded obligations - non-operating (営業外電子記録債務)"- , asAliases = ["営業外電子記録債務"]- }-accountSpec BonusesPayable = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Accrued bonuses"- , asNameJa = "未払賞与"- , asLabelJa = "未払賞与"- , asDescription = "Liability: Accrued bonuses (未払賞与)"- , asAliases = ["未払賞与"]- }-accountSpec AllowanceForRepairs = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Provision for repairs"- , asNameJa = "修繕引当金"- , asLabelJa = "修繕引当金"- , asDescription = "Liability: Provision for repairs (修繕引当金)"- , asAliases = ["修繕引当金"]- }-accountSpec AllowanceForProductWarranties = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Provision for warranties"- , asNameJa = "商品保証引当金"- , asLabelJa = "商品保証引当金"- , asDescription = "Liability: Provision for warranties (商品保証引当金)"- , asAliases = ["商品保証引当金"]- }-accountSpec AllowanceForBonuses = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Provision for bonuses"- , asNameJa = "賞与引当金"- , asLabelJa = "賞与引当金"- , asDescription = "Liability: Provision for bonuses (賞与引当金)"- , asAliases = ["賞与引当金"]- }-accountSpec DeferredTaxLiabilities = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Deferred tax liabilities"- , asNameJa = "繰延税金負債"- , asLabelJa = "繰延税金負債"- , asDescription = "Liability: Deferred tax liabilities (繰延税金負債)"- , asAliases = ["繰延税金負債"]- }-accountSpec LeaseObligations = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Lease liabilities"- , asNameJa = "リース債務"- , asLabelJa = "リース債務"- , asDescription = "Liability: Lease liabilities (リース債務)"- , asAliases = ["リース債務"]- }-accountSpec GuaranteeDepositsReceived = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Guarantee deposits received"- , asNameJa = "預り保証金"- , asLabelJa = "預り保証金"- , asDescription = "Liability: Guarantee deposits received (預り保証金)"- , asAliases = ["預り保証金"]- }-accountSpec AllowanceForRetirementBenefits = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Provision for retirement benefits"- , asNameJa = "退職給付引当金"- , asLabelJa = "退職給付引当金"- , asDescription = "Liability: Provision for retirement benefits (退職給付引当金)"- , asAliases = ["退職給付引当金"]- }-accountSpec LongTermOtherPayables = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Long-term accounts payable - other"- , asNameJa = "長期未払金"- , asLabelJa = "長期未払金"- , asDescription = "Liability: Long-term accounts payable - other (長期未払金)"- , asAliases = ["長期未払金"]- }-accountSpec NetDefinedBenefitLiability = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Retirement benefit liability"- , asNameJa = "退職給付に係る負債"- , asLabelJa = "退職給付に係る負債"- , asDescription = "Liability: Retirement benefit liability (退職給付に係る負債)"- , asAliases = ["退職給付に係る負債"]- }-accountSpec StockSubscriptionDeposits = Just AccountSpec- { asDivision = Equity- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Deposits for subscriptions of shares"- , asNameJa = "株式申込証拠金"- , asLabelJa = "株式申込証拠金"- , asDescription = "Equity: Deposits for subscriptions of shares (株式申込証拠金)"- , asAliases = ["株式申込証拠金"]- }-accountSpec LegalCapitalSurplus = Just AccountSpec- { asDivision = Equity- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Legal capital surplus"- , asNameJa = "資本準備金"- , asLabelJa = "資本準備金"- , asDescription = "Equity: Legal capital surplus (資本準備金)"- , asAliases = ["資本準備金"]- }-accountSpec OtherCapitalSurplus = Just AccountSpec- { asDivision = Equity- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Other capital surplus"- , asNameJa = "その他資本剰余金"- , asLabelJa = "その他資本剰余金"- , asDescription = "Equity: Other capital surplus (その他資本剰余金)"- , asAliases = ["その他資本剰余金"]- }-accountSpec DividendEqualizationReserve = Just AccountSpec- { asDivision = Equity- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Reserve for dividend equalization"- , asNameJa = "配当平均積立金"- , asLabelJa = "配当平均積立金"- , asDescription = "Equity: Reserve for dividend equalization (配当平均積立金)"- , asAliases = ["配当平均積立金"]- }-accountSpec RepairFundReserve = Just AccountSpec- { asDivision = Equity- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Reserve for repairs"- , asNameJa = "修繕積立金"- , asLabelJa = "修繕積立金"- , asDescription = "Equity: Reserve for repairs (修繕積立金)"- , asAliases = ["修繕積立金"]- }-accountSpec ConstructionFundReserve = Just AccountSpec- { asDivision = Equity- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Reserve for new construction"- , asNameJa = "新築積立金"- , asLabelJa = "新築積立金"- , asDescription = "Equity: Reserve for new construction (新築積立金)"- , asAliases = ["新築積立金"]- }-accountSpec GeneralReserve = Just AccountSpec- { asDivision = Equity- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "General reserve"- , asNameJa = "別途積立金"- , asLabelJa = "別途積立金"- , asDescription = "Equity: General reserve (別途積立金)"- , asAliases = ["別途積立金"]- }-accountSpec ValuationDifferenceOnOtherSecurities = Just AccountSpec- { asDivision = Equity- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Valuation difference on available-for-sale securities"- , asNameJa = "その他有価証券評価差額金"- , asLabelJa = "その他有価証券評価差額金"- , asDescription = "Equity: Valuation difference on available-for-sale securities (その他有価証券評価差額金)"- , asAliases = ["その他有価証券評価差額金"]- }-accountSpec NonControllingInterests = Just AccountSpec- { asDivision = Equity- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Non-controlling interests"- , asNameJa = "非支配株主持分"- , asLabelJa = "非支配株主持分"- , asDescription = "Equity: Non-controlling interests (非支配株主持分)"- , asAliases = ["非支配株主持分"]- }-accountSpec CapitalSurplus = Just AccountSpec- { asDivision = Equity- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Capital surplus"- , asNameJa = "資本剰余金"- , asLabelJa = "資本剰余金"- , asDescription = "Equity: Capital surplus (資本剰余金)"- , asAliases = ["資本剰余金"]- }-accountSpec EarnedSurplus = Just AccountSpec- { asDivision = Equity- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Retained earnings"- , asNameJa = "利益剰余金"- , asLabelJa = "利益剰余金"- , asDescription = "Equity: Retained earnings (利益剰余金)"- , asAliases = ["利益剰余金"]- }-accountSpec ServiceRevenue = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Service revenue"- , asNameJa = "役務収益"- , asLabelJa = "役務収益"- , asDescription = "Revenue: Service revenue (役務収益)"- , asAliases = ["役務収益"]- }-accountSpec OperatingRevenue = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Operating revenue"- , asNameJa = "営業収益"- , asLabelJa = "営業収益"- , asDescription = "Revenue: Operating revenue (営業収益)"- , asAliases = ["営業収益"]- }-accountSpec GainOnSalesOfSecurities = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Gain on sale of securities"- , asNameJa = "有価証券売却益"- , asLabelJa = "有価証券売却益"- , asDescription = "Revenue: Gain on sale of securities (有価証券売却益)"- , asAliases = ["有価証券売却益"]- }-accountSpec GainOnValuationOfSecurities = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Gain on valuation of securities"- , asNameJa = "有価証券評価益"- , asLabelJa = "有価証券評価益"- , asDescription = "Revenue: Gain on valuation of securities (有価証券評価益)"- , asAliases = ["有価証券評価益"]- }-accountSpec DividendsReceived = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Dividend income"- , asNameJa = "受取配当金"- , asLabelJa = "受取配当金"- , asDescription = "Revenue: Dividend income (受取配当金)"- , asAliases = ["受取配当金"]- }-accountSpec InterestOnSecurities = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Interest on securities"- , asNameJa = "有価証券利息"- , asLabelJa = "有価証券利息"- , asDescription = "Revenue: Interest on securities (有価証券利息)"- , asAliases = ["有価証券利息"]- }-accountSpec GainOnSalesOfInvestmentSecurities = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Gain on sale of investment securities"- , asNameJa = "投資有価証券売却益"- , asLabelJa = "投資有価証券売却益"- , asDescription = "Revenue: Gain on sale of investment securities (投資有価証券売却益)"- , asAliases = ["投資有価証券売却益"]- }-accountSpec InsuranceGain = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Gain on insurance claims"- , asNameJa = "保険差益"- , asLabelJa = "保険差益"- , asDescription = "Revenue: Gain on insurance claims (保険差益)"- , asAliases = ["保険差益"]- }-accountSpec GainOnBargainPurchase = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Gain on bargain purchase"- , asNameJa = "負ののれん発生益"- , asLabelJa = "負ののれん発生益"- , asDescription = "Revenue: Gain on bargain purchase (負ののれん発生益)"- , asAliases = ["負ののれん発生益"]- }-accountSpec ReversalOfAllowanceForRepairs = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Reversal of provision for repairs"- , asNameJa = "修繕引当金戻入"- , asLabelJa = "修繕引当金戻入"- , asDescription = "Revenue: Reversal of provision for repairs (修繕引当金戻入)"- , asAliases = ["修繕引当金戻入"]- }-accountSpec ReversalOfAllowanceForBonuses = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Reversal of provision for bonuses"- , asNameJa = "賞与引当金戻入"- , asLabelJa = "賞与引当金戻入"- , asDescription = "Revenue: Reversal of provision for bonuses (賞与引当金戻入)"- , asAliases = ["賞与引当金戻入"]- }-accountSpec ReversalOfAllowanceForProductWarranties = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Reversal of provision for warranties"- , asNameJa = "商品保証引当金戻入"- , asLabelJa = "商品保証引当金戻入"- , asDescription = "Revenue: Reversal of provision for warranties (商品保証引当金戻入)"- , asAliases = ["商品保証引当金戻入"]- }-accountSpec GainOnDonationOfFixedAssets = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Gain on receipt of donated non-current assets"- , asNameJa = "固定資産受贈益"- , asLabelJa = "固定資産受贈益"- , asDescription = "Revenue: Gain on receipt of donated non-current assets (固定資産受贈益)"- , asAliases = ["固定資産受贈益"]- }-accountSpec GainOnNationalSubsidies = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Gain on receipt of national subsidies"- , asNameJa = "国庫補助金受贈益"- , asLabelJa = "国庫補助金受贈益"- , asDescription = "Revenue: Gain on receipt of national subsidies (国庫補助金受贈益)"- , asAliases = ["国庫補助金受贈益"]- }-accountSpec GainOnConstructionGrants = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Gain on contribution received for construction"- , asNameJa = "工事負担金受贈益"- , asLabelJa = "工事負担金受贈益"- , asDescription = "Revenue: Gain on contribution received for construction (工事負担金受贈益)"- , asAliases = ["工事負担金受贈益"]- }-accountSpec LandRentReceived = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Rental income from land"- , asNameJa = "受取地代"- , asLabelJa = "受取地代"- , asDescription = "Revenue: Rental income from land (受取地代)"- , asAliases = ["受取地代"]- }-accountSpec SalesRebates = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = True- , asFixedCurrent = Other- , asNameEn = "Sales rebates"- , asNameJa = "売上割戻"- , asLabelJa = "売上割戻"- , asDescription = "Revenue: Sales rebates (売上割戻)"- , asAliases = ["売上割戻"]- }-accountSpec SalesAllowances = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = True- , asFixedCurrent = Other- , asNameEn = "Sales allowances"- , asNameJa = "売上値引"- , asLabelJa = "売上値引"- , asDescription = "Revenue: Sales allowances (売上値引)"- , asAliases = ["売上値引"]- }-accountSpec CostOfServices = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Cost of services"- , asNameJa = "役務原価"- , asLabelJa = "役務原価"- , asDescription = "Expense: Cost of services (役務原価)"- , asAliases = ["役務原価"]- }-accountSpec OperatingExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Operating expenses"- , asNameJa = "営業費用"- , asLabelJa = "営業費用"- , asDescription = "Expense: Operating expenses (営業費用)"- , asAliases = ["営業費用"]- }-accountSpec InventoryShrinkageLoss = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Inventory shrinkage loss"- , asNameJa = "棚卸減耗損"- , asLabelJa = "棚卸減耗損"- , asDescription = "Expense: Inventory shrinkage loss (棚卸減耗損)"- , asAliases = ["棚卸減耗損"]- }-accountSpec LossOnValuationOfMerchandise = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Valuation loss on goods"- , asNameJa = "商品評価損"- , asLabelJa = "商品評価損"- , asDescription = "Expense: Valuation loss on goods (商品評価損)"- , asAliases = ["商品評価損"]- }-accountSpec Bonuses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Bonuses"- , asNameJa = "賞与"- , asLabelJa = "賞与"- , asDescription = "Expense: Bonuses (賞与)"- , asAliases = ["賞与"]- }-accountSpec RetirementBenefitExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Retirement benefit expenses"- , asNameJa = "退職給付費用"- , asLabelJa = "退職給付費用"- , asDescription = "Expense: Retirement benefit expenses (退職給付費用)"- , asAliases = ["退職給付費用"]- }-accountSpec ProvisionForRepairs = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Provision for repairs"- , asNameJa = "修繕引当金繰入"- , asLabelJa = "修繕引当金繰入"- , asDescription = "Expense: Provision for repairs (修繕引当金繰入)"- , asAliases = ["修繕引当金繰入"]- }-accountSpec ProvisionForBonuses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Provision for bonuses"- , asNameJa = "賞与引当金繰入"- , asLabelJa = "賞与引当金繰入"- , asDescription = "Expense: Provision for bonuses (賞与引当金繰入)"- , asAliases = ["賞与引当金繰入"]- }-accountSpec ProvisionForProductWarranties = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Provision for warranties"- , asNameJa = "商品保証引当金繰入"- , asLabelJa = "商品保証引当金繰入"- , asDescription = "Expense: Provision for warranties (商品保証引当金繰入)"- , asAliases = ["商品保証引当金繰入"]- }-accountSpec ResearchAndDevelopmentExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Research and development expenses"- , asNameJa = "研究開発費"- , asLabelJa = "研究開発費"- , asDescription = "Expense: Research and development expenses (研究開発費)"- , asAliases = ["研究開発費"]- }-accountSpec AmortizationOfGoodwill = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Amortization of goodwill"- , asNameJa = "のれん償却"- , asLabelJa = "のれん償却"- , asDescription = "Expense: Amortization of goodwill (のれん償却)"- , asAliases = ["のれん償却"]- }-accountSpec AmortizationOfSoftware = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Amortization of software"- , asNameJa = "ソフトウェア償却"- , asLabelJa = "ソフトウェア償却"- , asDescription = "Expense: Amortization of software (ソフトウェア償却)"- , asAliases = ["ソフトウェア償却"]- }-accountSpec AmortizationOfPatents = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Amortization of patent rights"- , asNameJa = "特許権償却"- , asLabelJa = "特許権償却"- , asDescription = "Expense: Amortization of patent rights (特許権償却)"- , asAliases = ["特許権償却"]- }-accountSpec LeaseExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Lease expenses"- , asNameJa = "支払リース料"- , asLabelJa = "支払リース料"- , asDescription = "Expense: Lease expenses (支払リース料)"- , asAliases = ["支払リース料"]- }-accountSpec IncorporationExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Organization expenses"- , asNameJa = "創立費"- , asLabelJa = "創立費"- , asDescription = "Expense: Organization expenses (創立費)"- , asAliases = ["創立費"]- }-accountSpec StockIssuanceCosts = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Share issuance costs"- , asNameJa = "株式交付費"- , asLabelJa = "株式交付費"- , asDescription = "Expense: Share issuance costs (株式交付費)"- , asAliases = ["株式交付費"]- }-accountSpec BusinessCommencementExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Business commencement expenses"- , asNameJa = "開業費"- , asLabelJa = "開業費"- , asDescription = "Expense: Business commencement expenses (開業費)"- , asAliases = ["開業費"]- }-accountSpec DevelopmentExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Development expenses"- , asNameJa = "開発費"- , asLabelJa = "開発費"- , asDescription = "Expense: Development expenses (開発費)"- , asAliases = ["開発費"]- }-accountSpec LossOnSalesOfElectronicallyRecordedReceivables = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Loss on sale of electronically recorded monetary claims"- , asNameJa = "電子記録債権売却損"- , asLabelJa = "電子記録債権売却損"- , asDescription = "Expense: Loss on sale of electronically recorded monetary claims (電子記録債権売却損)"- , asAliases = ["電子記録債権売却損"]- }-accountSpec LossOnSalesOfReceivables = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Loss on sale of receivables"- , asNameJa = "債権売却損"- , asLabelJa = "債権売却損"- , asDescription = "Expense: Loss on sale of receivables (債権売却損)"- , asAliases = ["債権売却損"]- }-accountSpec LossOnSalesOfSecurities = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Loss on sale of securities"- , asNameJa = "有価証券売却損"- , asLabelJa = "有価証券売却損"- , asDescription = "Expense: Loss on sale of securities (有価証券売却損)"- , asAliases = ["有価証券売却損"]- }-accountSpec LossOnValuationOfSecurities = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Loss on valuation of securities"- , asNameJa = "有価証券評価損"- , asLabelJa = "有価証券評価損"- , asDescription = "Expense: Loss on valuation of securities (有価証券評価損)"- , asAliases = ["有価証券評価損"]- }-accountSpec LossOnSalesOfInvestmentSecurities = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Loss on sale of investment securities"- , asNameJa = "投資有価証券売却損"- , asLabelJa = "投資有価証券売却損"- , asDescription = "Expense: Loss on sale of investment securities (投資有価証券売却損)"- , asAliases = ["投資有価証券売却損"]- }-accountSpec LossOnFire = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Loss on fire"- , asNameJa = "火災損失"- , asLabelJa = "火災損失"- , asDescription = "Expense: Loss on fire (火災損失)"- , asAliases = ["火災損失"]- }-accountSpec LossOnRetirementOfFixedAssets = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Loss on retirement of non-current assets"- , asNameJa = "固定資産除却損"- , asLabelJa = "固定資産除却損"- , asDescription = "Expense: Loss on retirement of non-current assets (固定資産除却損)"- , asAliases = ["固定資産除却損"]- }-accountSpec LossOnReductionOfFixedAssets = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Loss on tax purpose reduction entry of non-current assets"- , asNameJa = "固定資産圧縮損"- , asLabelJa = "固定資産圧縮損"- , asDescription = "Expense: Loss on tax purpose reduction entry of non-current assets (固定資産圧縮損)"- , asAliases = ["固定資産圧縮損"]- }-accountSpec AdditionalIncomeTaxesForPriorPeriods = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Additional income taxes for prior periods"- , asNameJa = "追徴法人税等"- , asLabelJa = "追徴法人税等"- , asDescription = "Expense: Additional income taxes for prior periods (追徴法人税等)"- , asAliases = ["追徴法人税等"]- }-accountSpec RefundOfIncomeTaxes = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = True- , asFixedCurrent = Other- , asNameEn = "Refund of income taxes"- , asNameJa = "還付法人税等"- , asLabelJa = "還付法人税等"- , asDescription = "Expense: Refund of income taxes (還付法人税等)"- , asAliases = ["還付法人税等"]- }-accountSpec PurchaseRebates = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = True- , asFixedCurrent = Other- , asNameEn = "Purchase rebates"- , asNameJa = "仕入割戻"- , asLabelJa = "仕入割戻"- , asDescription = "Expense: Purchase rebates (仕入割戻)"- , asAliases = ["仕入割戻"]- }-accountSpec PurchaseAllowances = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = True- , asFixedCurrent = Other- , asNameEn = "Purchase allowances"- , asNameJa = "仕入値引"- , asLabelJa = "仕入値引"- , asDescription = "Expense: Purchase allowances (仕入値引)"- , asAliases = ["仕入値引"]- }-accountSpec WelfareExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Welfare expenses"- , asNameJa = "福利厚生費"- , asLabelJa = "福利厚生費"- , asDescription = "Expense: Welfare expenses (福利厚生費)"- , asAliases = ["福利厚生費"]- }-accountSpec MaintenanceExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Maintenance expenses"- , asNameJa = "保守費"- , asLabelJa = "保守費"- , asDescription = "Expense: Maintenance expenses (保守費)"- , asAliases = ["保守費"]- }-accountSpec StatutoryWelfareExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Legal welfare expenses"- , asNameJa = "法定福利費"- , asLabelJa = "法定福利費"- , asDescription = "Expense: Legal welfare expenses (法定福利費)"- , asAliases = ["法定福利費"]- }-accountSpec LandRentPaid = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Rent expenses on land"- , asNameJa = "支払地代"- , asLabelJa = "支払地代"- , asDescription = "Expense: Rent expenses on land (支払地代)"- , asAliases = ["支払地代"]- }-accountSpec InsuranceExpense = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Insurance expenses"- , asNameJa = "保険料"- , asLabelJa = "保険料"- , asDescription = "Expense: Insurance expenses (保険料)"- , asAliases = ["保険料"]- }-accountSpec RepairsExpense = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Repair expenses"- , asNameJa = "修繕費"- , asLabelJa = "修繕費"- , asDescription = "Expense: Repair expenses (修繕費)"- , asAliases = ["修繕費"]- }-accountSpec StorageExpenses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Storage costs"- , asNameJa = "保管費"- , asLabelJa = "保管費"- , asDescription = "Expense: Storage costs (保管費)"- , asAliases = ["保管費"]- }-accountSpec MembershipFees = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Membership fees"- , asNameJa = "諸会費"- , asLabelJa = "諸会費"- , asDescription = "Expense: Membership fees (諸会費)"- , asAliases = ["諸会費"]- }-accountSpec IncomeSummary = Just AccountSpec- { asDivision = Assets- , asClosing = NoClose- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Income summary"- , asNameJa = "損益"- , asLabelJa = "損益"- , asDescription = "Bookkeeping device: Income summary (損益). Assets/NoClose is a technical debit-side placeholder; it is not a balance-sheet asset and is not automatically closed."- , asAliases = ["損益"]- }-accountSpec SuspenseAccount = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Suspense account"- , asNameJa = "未決算"- , asLabelJa = "未決算"- , asDescription = "Asset: Suspense account (未決算)"- , asAliases = ["未決算"]- }-accountSpec ForeignExchangeGains = Just AccountSpec- { asDivision = Revenue- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Foreign exchange gains"- , asNameJa = "為替差益"- , asLabelJa = "為替差益"- , asDescription = "Revenue: Foreign exchange gains (為替差益)"- , asAliases = ["為替差益"]- }-accountSpec ForeignExchangeLosses = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Foreign exchange losses"- , asNameJa = "為替差損"- , asLabelJa = "為替差損"- , asDescription = "Expense: Foreign exchange losses (為替差損)"- , asAliases = ["為替差損"]- }-accountSpec ContraAccountForGuaranteeObligations = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Contra account for guarantee obligations"- , asNameJa = "保証債務見返"- , asLabelJa = "保証債務見返"- , asDescription = "Asset: Contra account for guarantee obligations (保証債務見返)"- , asAliases = ["保証債務見返"]- }-accountSpec GuaranteeObligations = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Guarantee obligations"- , asNameJa = "保証債務"- , asLabelJa = "保証債務"- , asDescription = "Liability: Guarantee obligations (保証債務)"- , asAliases = ["保証債務"]- }-accountSpec IncomeTaxesAdjustment = Just AccountSpec- { asDivision = Cost- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Income taxes - deferred"- , asNameJa = "法人税等調整額"- , asLabelJa = "法人税等調整額"- , asDescription = "Expense: Income taxes - deferred (法人税等調整額)"- , asAliases = ["法人税等調整額"]- }-accountSpec BranchCurrentAccount = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Branch current account"- , asNameJa = "支店"- , asLabelJa = "支店"- , asDescription = "Asset: Branch current account (支店)"- , asAliases = ["支店"]- }-accountSpec HeadOfficeCurrentAccount = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Head office current account"- , asNameJa = "本店"- , asLabelJa = "本店"- , asDescription = "Liability: Head office current account (本店), the credit-balance reciprocal account in branch books."- , asAliases = ["本店"]- }-accountSpec NetIncomeAttributableToNCI = Just AccountSpec- { asDivision = Cost- , asClosing = NoClose- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Profit attributable to non-controlling interests"- , asNameJa = "非支配株主に帰属する当期純利益"- , asLabelJa = "非支配株主に帰属する当期純利益"- , asDescription = "Expense: Profit attributable to non-controlling interests (非支配株主に帰属する当期純利益). NoClose: consolidation procedures transfer it separately to non-controlling interests."- , asAliases = ["非支配株主に帰属する当期純利益"]- }-accountSpec NetLossAttributableToNCI = Just AccountSpec- { asDivision = Revenue- , asClosing = NoClose- , asIsContra = False- , asFixedCurrent = Other- , asNameEn = "Loss attributable to non-controlling interests"- , asNameJa = "非支配株主に帰属する当期純損失"- , asLabelJa = "非支配株主に帰属する当期純損失"- , asDescription = "Revenue: Loss attributable to non-controlling interests (非支配株主に帰属する当期純損失). NoClose: consolidation procedures transfer it separately to non-controlling interests."- , asAliases = ["非支配株主に帰属する当期純損失"]- }-accountSpec TradingSecurities = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Trading securities"- , asNameJa = "売買目的有価証券"- , asLabelJa = "売買目的有価証券"- , asDescription = "Asset: Trading securities (売買目的有価証券)"- , asAliases = ["売買目的有価証券"]- }-accountSpec HeldToMaturityBonds = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Held-to-maturity bonds"- , asNameJa = "満期保有目的債券"- , asLabelJa = "満期保有目的債券"- , asDescription = "Asset: Held-to-maturity bonds (満期保有目的債券)"- , asAliases = ["満期保有目的債券"]- }-accountSpec SubsidiaryStocks = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Shares of subsidiaries"- , asNameJa = "子会社株式"- , asLabelJa = "子会社株式"- , asDescription = "Asset: Shares of subsidiaries (子会社株式)"- , asAliases = ["子会社株式"]- }-accountSpec AffiliateStocks = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Shares of associates"- , asNameJa = "関連会社株式"- , asLabelJa = "関連会社株式"- , asDescription = "Asset: Shares of associates (関連会社株式)"- , asAliases = ["関連会社株式"]- }-accountSpec AvailableForSaleSecurities = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Fixed- , asNameEn = "Available-for-sale securities"- , asNameJa = "その他有価証券"- , asLabelJa = "その他有価証券"- , asDescription = "Asset: Available-for-sale securities (その他有価証券)"- , asAliases = ["その他有価証券"]- }-accountSpec ConsumptionTaxRefundReceivable = Just AccountSpec- { asDivision = Assets- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Consumption tax refund receivable"- , asNameJa = "未収還付消費税"- , asLabelJa = "未収還付消費税"- , asDescription = "Asset: Consumption tax refund receivable (未収還付消費税)"- , asAliases = ["未収還付消費税", "未収消費税"]- }-accountSpec PropertyTaxPayable = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Property tax payable"- , asNameJa = "未払固定資産税"- , asLabelJa = "未払固定資産税"- , asDescription = "Liability: Property tax payable (未払固定資産税)"- , asAliases = ["未払固定資産税"]- }-accountSpec DepositsReceivedFromOfficers = Just AccountSpec- { asDivision = Liability- , asClosing = CloseByDivision- , asIsContra = False- , asFixedCurrent = Current- , asNameEn = "Deposits received from officers"- , asNameJa = "役員預り金"- , asLabelJa = "役員預り金"- , asDescription = "Liability: Deposits received from officers (役員預り金)"- , asAliases = ["役員預り金"]- }-accountSpec AccountTitle = Nothing---- | Derived strict map view. The exhaustive function above remains canonical.+-- | Public metadata and alias projections from the account title table.+module ExchangeAlgebra.Accounting.Account.Registry+ ( AccountSpec(..)+ , AccountSemantics(..)+ , accountAliases+ , jcciAliases+ , accountSpec+ , accountSemantics+ , accountSpecMap+ , concreteAccountTitles+ , classifyAccountContra+ , accountDescriptions+ ) where++import qualified Data.List as L+import qualified Data.Map.Strict as M+import Data.Map.Strict (Map)+import Data.Maybe (mapMaybe)+import Data.Text (Text)++import ExchangeAlgebra.Accounting.Account.Spec (AccountSpec(..), AccountSemantics(..))+import ExchangeAlgebra.Accounting.Account.Title (AccountTitles, Row(..), row)++-- | All concrete account titles in their stable Enum order.+concreteAccountTitles :: [AccountTitles]+concreteAccountTitles =+ [title | title <- [minBound .. maxBound], ConcreteRow {} <- [row title]]++-- | Look up processing and reporting semantics for a concrete account title.+-- The wildcard returns 'Nothing'.+accountSemantics :: AccountTitles -> Maybe AccountSemantics+accountSemantics title = case row title of+ WildcardRow -> Nothing+ ConcreteRow { rowSemantics = semantics } -> Just semantics++-- | Every accepted non-canonical alias for an account. Base aliases come first,+-- followed by JCCI 2022 aliases, with duplicates removed.+accountAliases :: AccountTitles -> [Text]+accountAliases title = L.nub (baseAliases <> jcciAliases title)+ where+ baseAliases = maybe [] asAliases (accountSpec title)++-- | Return the JCCI 2022 account-name aliases for a title.+jcciAliases :: AccountTitles -> [Text]+jcciAliases title = case row title of+ WildcardRow -> []+ ConcreteRow { rowJcciAliases = aliases } -> aliases++-- | Look up metadata for an account title. The wildcard returns 'Nothing'.+--+-- Complexity: O(1)+{-# INLINE accountSpec #-}+accountSpec :: AccountTitles -> Maybe AccountSpec+accountSpec title = case row title of+ WildcardRow -> Nothing+ ConcreteRow { rowSpec = spec } -> Just spec++-- | A strict map of the metadata for all concrete account titles. accountSpecMap :: Map AccountTitles AccountSpec accountSpecMap = M.fromList [ (title, spec)
+ src/ExchangeAlgebra/Accounting/Account/Spec.hs view
@@ -0,0 +1,54 @@+-- | Metadata and processing semantics shared by the account table and registry.+module ExchangeAlgebra.Accounting.Account.Spec+ ( AccountSpec(..)+ , AccountSemantics(..)+ ) where++import Data.Text (Text)++import ExchangeAlgebra.Accounting.Account.Classification+ ( AccountDivision, AccountRole, ClosingRule, DivisionSemantics+ , FixedCurrent, HomeSideSemantics, PostingCapability, ReportingEligibility+ )++-- | All metadata attached to one concrete account title.+data AccountSpec = AccountSpec+ { asDivision :: AccountDivision+ , asClosing :: ClosingRule+ -- ^ Automatic closing policy. @NetIncome@ and @NetLoss@ are explicit+ -- 'NoClose' overrides: their division describes the P\/L presentation+ -- side, so division-derived closing would reverse their intended side.+ -- GrossProfit and OrdinaryProfit retain CloseByDivision for staged+ -- closing. Statement metrics live in+ -- "ExchangeAlgebra.Accounting.Statements.Metric".+ , asIsContra :: Bool+ , asFixedCurrent :: FixedCurrent+ , asNameEn :: Text+ , asNameJa :: Text+ -- | Annotation-free Japanese display label (清書和文表示名) used for+ -- financial-statement lines+ -- ('ExchangeAlgebra.Accounting.Statements.Presentation.presentationLabel') and LLM-facing+ -- names ('ExchangeAlgebra.IO.Input.Assist.safeNameJa'). Unlike 'asNameJa' it never+ -- carries notes, legacy-name+ -- remarks, or constructor identifiers; the JCCI level-2 A-column sweep in+ -- the test suite pins it against the official standard names.+ , asLabelJa :: Text+ , asDescription :: Text+ -- | Registry-local aliases only. Use 'ExchangeAlgebra.Accounting.Account.accountAliases' when constructing a+ -- parser or UI: that function also includes the frozen JCCI overlay.+ , asAliases :: [Text]+ } deriving (Show, Eq)++-- | Processing and reporting semantics attached to a concrete account title.+--+-- This record deliberately does not replace 'AccountSpec.asDivision'. The+-- legacy division remains the exchange-algebra direction input, while this+-- layer states whether that value is a financial-statement classification,+-- a bookkeeping control class, or only an internal direction encoding.+data AccountSemantics = AccountSemantics+ { asemRoles :: [AccountRole]+ , asemPostingCapability :: PostingCapability+ , asemDivisionSemantics :: DivisionSemantics+ , asemHomeSideSemantics :: HomeSideSemantics+ , asemReportingEligibility :: ReportingEligibility+ } deriving (Show, Eq)
src/ExchangeAlgebra/Accounting/Account/Title.hs view
@@ -1,573 +1,5949 @@-{-# OPTIONS_GHC -Wincomplete-patterns -Werror=incomplete-patterns #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE UndecidableInstances #-}-{-# LANGUAGE ExistentialQuantification #-}-{-# LANGUAGE StrictData #-}-{-# LANGUAGE Strict #-}-{-# LANGUAGE DeriveGeneric #-}--module ExchangeAlgebra.Accounting.Account.Title (AccountTitles(..)) where--import ExchangeAlgebra.Algebra.Element.Representation (Element(..))-import ExchangeAlgebra.Algebra.Base.Representation (BaseClass(..))-import GHC.Generics (Generic)-import Data.Hashable (Hashable(..))-import Control.DeepSeq (NFData(..))-import Data.Word (Word16)-import qualified Data.Map.Strict as Map-import qualified Data.Binary as Binary-import qualified Data.Binary.Get as BinaryGet-import qualified Data.Binary.Put as BinaryPut---- ** Account Titles---- | Account titles used as elements of a base.-data AccountTitles = Cash -- ^ Asset: Cash (現金)- | Deposits -- ^ Asset: Savings deposits (普通預金)- | CurrentDeposits -- ^ Asset: Current deposits (当座預金)- | Securities -- ^ Asset: Securities (有価証券)- | InvestmentSecurities -- ^ Asset: Investment securities (投資有価証券)- | InvestmentInAssociate -- ^ Asset: Investment in associate (関係会社株式). Carrying amount under the equity method (持分法適用投資勘定).- | LongTermNationalBonds -- ^ Asset: Long-term national bonds (長期国債)- | ShortTermNationalBonds -- ^ Asset: Short-term national bonds (短期国債)- | Products -- ^ Asset: Products (商品)。分記法用。3 分法 (仕入\/売上\/繰越商品) では 'MerchandiseInventory' を使う- | Machinery -- ^ Asset: Machinery and equipment (機械装置)- | Building -- ^ Asset: Real estate (建物)- | Vehicle -- ^ Asset: Vehicles (車両運搬具)- | StockInvestment -- ^ Asset: Stock investment (株式投資)- | EquipmentInvestment -- ^ Asset: Equipment investment (設備投資)- | LongTermLoansReceivable -- ^ Asset: Long-term loans receivable (長期貸付金)- | AccountsReceivable -- ^ Asset: Accounts receivable (売掛金)- | ShortTermLoansReceivable -- ^ Asset: Short-term loans receivable (短期貸付金)- | ReserveDepositReceivable -- ^ Asset: Reserve deposits, asset side (準備預金, 資産側 — 市中銀行が中央銀行に置く準備預金。SNA\/マクロ系)- | Gold -- ^ Asset: Gold (金)- | GovernmentService -- ^ Asset: Government service (政府サービス。SNA\/マクロ系)- | CapitalStock -- ^ Equity: Capital stock (資本金)- | RetainedEarnings -- ^ Equity: Retained earnings (繰越利益剰余金)- | LongTermLoansPayable -- ^ Liability: Long-term loans payable (長期借入金)- | ShortTermLoansPayable -- ^ Liability: Short-term loans payable (短期借入金)- | LoansPayable -- ^ Liability: Loans payable (借入金)- | ReserveForDepreciation -- ^ Liability: Reserve for depreciation (減価償却引当金 — SNA\/マクロ系の旧称。簿記の間接法には 'AccumulatedDepreciation' (減価償却累計額) を使う)- | DepositPayable -- ^ Liability: Deposits accepted (受入預金 — 銀行側の負債としての預金。SNA\/マクロ系。従業員等からの預り金は 'DepositsReceived')- | LongTermNationalBondsPayable -- ^ Liability: Long-term national bonds payable (長期国債, 発行側)- | ShortTermNationalBondsPayable -- ^ Liability: Short-term national bonds payable (短期国債, 発行側)- | ReserveDepositPayable -- ^ Liability: Reserve deposits, liability side (準備預金, 負債側 — 中央銀行が受け入れる準備預金。SNA\/マクロ系)。※簿記の買掛金は 'AccountsPayable' を使うこと (旧 examples が本科目を買掛金の代用にしていた経緯あり)- | CentralBankNotePayable -- ^ Liability: Central bank notes (発行銀行券。SNA\/マクロ系)- | Depreciation -- ^ Expense: Depreciation (減価償却費)- | AmortizationExpense -- ^ Expense: Amortization expense for intangibles (無形固定資産償却費 — 特許権・商標権・ソフトウェア等の無形資産の償却費。有形の 'Depreciation' (減価償却費) と区別される)- | SalesCost -- ^ Expense: Cost of sales (売上原価)- | BusinessTrip -- ^ Expense: Travel and transportation (旅費交通費)- | Commutation -- ^ Expense: Communication (通信費 — 旧称。新規コードでは 'CommunicationExpenses' を使う)- | UtilitiesExpense -- ^ Expense: Utilities (水道光熱費)- | RentExpense -- ^ Expense: Rent (支払家賃)- | AdvertisingExpense -- ^ Expense: Advertising (広告宣伝費)- | DeliveryExpenses -- ^ Expense: Delivery (発送費)- | SuppliesExpenses -- ^ Expense: Supplies (消耗品費)- | MiscellaneousExpenses -- ^ Expense: Miscellaneous (雑費)- | WageExpenditure -- ^ Expense: Wages (給料)- | InterestExpense -- ^ Expense: Interest expense (支払利息)- | TaxesExpense -- ^ Expense: Taxes (租税公課)- | ConsumptionExpenditure -- ^ Expense: Consumption expenditure (消費支出。SNA\/マクロ系)- | SubsidyExpense -- ^ Expense: Subsidy expenditure (補助金支出。SNA\/マクロ系)- | CentralBankPaymentExpense -- ^ Expense: Central bank payment to treasury (国庫納付金支出。SNA\/マクロ系)- | Purchases -- ^ Expense: Purchases (仕入)- | NetIncome -- ^ Expense: Net income (当期純利益 — 決算振替用。借方側に立つため Expense 区分)- | ValueAdded -- ^ Revenue: Value added (付加価値。SNA\/マクロ系)- | SubsidyIncome -- ^ Revenue: Subsidy income (補助金収入。SNA\/マクロ系)- | NationalBondInterestEarned -- ^ Revenue: National bond interest earned (国債利息収入)- | DepositInterestEarned -- ^ Revenue: Deposit interest earned (預金利息収入)- | GrossProfit -- ^ Revenue: Gross profit (売上総利益 — 決算振替用)- | OrdinaryProfit -- ^ Revenue: Ordinary profit (経常利益 — 決算振替用)- | InterestEarned -- ^ Revenue: Interest earned (受取利息)- | ReceiptFee -- ^ Revenue: Receipt fee (受取手数料。支払側は 'PaymentFees')- | RentalIncome -- ^ Revenue: Rental income (受取家賃)- | WageEarned -- ^ Revenue: Wage income (賃金収入。SNA\/マクロ系)- | TaxesRevenue -- ^ Revenue: Tax revenue (租税収入。SNA\/マクロ系)- | CentralBankPaymentIncome -- ^ Revenue: Central bank payment to treasury (国庫納付金収入。SNA\/マクロ系)- | Sales -- ^ Revenue: Sales (売上)- | EquityInEarningsOfInvestee -- ^ Revenue: Equity in earnings of investee- -- (持分法による投資利益). Recognized under the equity method.- | NetLoss -- ^ Revenue: Net loss (当期純損失 — 決算振替用。貸方側に立つため Revenue 区分)- -- Elementary bookkeeping (日商簿記 3 級水準) additions.- -- Appended before the 'AccountTitle' wildcard so that only the- -- wildcard's Enum/Binary ordinal shifts (existing serialized- -- bases remain compatible).- --- -- Assets (資産)- | PettyCash -- ^ Asset: Petty cash (小口現金)- | NotesReceivable -- ^ Asset: Notes receivable (受取手形)- | ElectronicallyRecordedReceivable -- ^ Asset: Electronically recorded monetary claims (電子記録債権)- | CreditCardReceivable -- ^ Asset: Credit card receivable (クレジット売掛金)- | NotesLoansReceivable -- ^ Asset: Loans receivable on notes (手形貸付金)- | MerchandiseInventory -- ^ Asset: Merchandise inventory (繰越商品). Use under the periodic/3-account method (3 分法: Purchases\/Sales\/MerchandiseInventory). For 分記法, which records the cost of the goods and the gain on sales at each sale, use 'Products' instead.- | AdvancesPaid -- ^ Asset: Advances paid (前払金)- | PrepaidExpenses -- ^ Asset: Prepaid expenses (前払費用), deferral account (経過勘定)- | AccruedRevenue -- ^ Asset: Accrued revenue (未収収益), accrual account (経過勘定)- | OtherReceivables -- ^ Asset: Other receivables (未収入金)- | PaymentsOnBehalf -- ^ Asset: Payments made on behalf (立替金)- | SuspensePayments -- ^ Asset: Suspense payments (仮払金)- | ConsumptionTaxPaid -- ^ Asset: Consumption tax paid (仮払消費税)- | PrepaidCorporateIncomeTaxes -- ^ Asset: Prepaid corporate income taxes (仮払法人税等)- | Land -- ^ Asset: Land (土地)- | Fixtures -- ^ Asset: Fixtures and equipment (備品)- | Patent -- ^ Asset: Patent (特許権)- | Trademark -- ^ Asset: Trademark (商標権)- | Software -- ^ Asset: Software (ソフトウェア)- | CashOverShort -- ^ Asset: Cash over and short (現金過不足), a temporary/suspense account cleared at closing to MiscellaneousIncome\/MiscellaneousLoss- -- Liability (負債)- | AccountsPayable -- ^ Liability: Accounts payable (買掛金)- | NotesPayable -- ^ Liability: Notes payable (支払手形)- | ElectronicallyRecordedObligations -- ^ Liability: Electronically recorded monetary obligations (電子記録債務)- | NotesLoansPayable -- ^ Liability: Loans payable on notes (手形借入金)- | BankOverdraft -- ^ Liability: Bank overdraft (当座借越)- | AdvancesReceived -- ^ Liability: Advances received (前受金)- | UnearnedRevenue -- ^ Liability: Unearned revenue (前受収益), deferral account (経過勘定)- | AccruedExpenses -- ^ Liability: Accrued expenses (未払費用), accrual account (経過勘定)- | OtherPayables -- ^ Liability: Other payables (未払金)- | DepositsReceived -- ^ Liability: Deposits received (預り金)- | SuspenseReceipts -- ^ Liability: Suspense receipts (仮受金)- | ConsumptionTaxReceived -- ^ Liability: Consumption tax received (仮受消費税)- | AccruedConsumptionTax -- ^ Liability: Accrued (unpaid) consumption tax (未払消費税)- | AccruedCorporateIncomeTaxes -- ^ Liability: Accrued (unpaid) corporate income taxes (未払法人税等)- | UnpaidDividends -- ^ Liability: Unpaid dividends (未払配当金)- | AllowanceForDoubtfulAccounts -- ^ Asset (contra): Allowance for doubtful accounts (貸倒引当金), a credit-balance valuation account (評価勘定) deducted from receivables. Division is Assets with @isContra = True@ (Definition 7 amendment, 0.5.0.0); home side stays Credit, values stay non-negative, Hat\/Not structure intact. B\/S deduction (net) presentation is the ExchangeAlgebra.IO.Output module's job.- | AccumulatedDepreciation -- ^ Asset (contra): Accumulated depreciation (減価償却累計額), valuation account (評価勘定) under the indirect method (間接法), deducted from the related depreciable assets. Division is Assets with @isContra = True@ for the same reason as 'AllowanceForDoubtfulAccounts'. This is the canonical bookkeeping account for accumulated depreciation; the existing 'ReserveForDepreciation' is retained as the legacy SNA\/macro-accounting name.- -- Equity (資本)- | LegalRetainedEarnings -- ^ Equity: Legal (appropriated) retained earnings reserve (利益準備金)- | CumulativeTranslationAdjustment -- ^ Equity: Cumulative translation adjustment (為替換算調整勘定; 在外子会社等の外貨建財務諸表の換算差額を計上する OCI/資本の部の項目)- -- Cost (費用)- | ProvisionForDoubtfulAccounts -- ^ Expense: Provision for doubtful accounts (貸倒引当金繰入)- | BadDebtLoss -- ^ Expense: Bad debt loss (貸倒損失)- | LossOnSalesOfFixedAssets -- ^ Expense: Loss on sales of fixed assets (固定資産売却損)- | LossOnSalesOfNotesReceivable -- ^ Expense: Loss on sales of notes receivable (手形売却損)- | PaymentFees -- ^ Expense: Payment fees / fees paid (支払手数料), the debit counterpart of 'ReceiptFee'- | MiscellaneousLoss -- ^ Expense: Miscellaneous loss (雑損)- | CorporateIncomeTaxes -- ^ Expense: Corporate income taxes (法人税等)- | CommunicationExpenses -- ^ Expense: Communication expenses (通信費). Explicitly named counterpart of the legacy 'Commutation' (also "Communication"); 'Commutation' is retained for backward compatibility.- -- Revenue (収益)- | GainOnSalesOfFixedAssets -- ^ Revenue: Gain on sales of fixed assets (固定資産売却益)- | RecoveryOfBadDebts -- ^ Revenue: Recovery of bad debts written off (償却債権取立益)- | MiscellaneousIncome -- ^ Revenue: Miscellaneous income (雑益)- | ReversalOfAllowanceForDoubtfulAccounts -- ^ Revenue: Reversal of allowance for doubtful accounts (貸倒引当金戻入). Credit counterpart used by the 差額補充法/洗替法 when the estimated allowance is smaller than the existing balance (the excess of 'AllowanceForDoubtfulAccounts' is released).- -- V-Land 2: JCCI grade-2 commercial-bookkeeping vocabulary.- | TimeDeposits -- ^ Asset: Time deposits (定期預金)- | LoansReceivable -- ^ Asset: Loans receivable (貸付金)- | GiftCertificatesReceived -- ^ Asset: Gift certificates received (受取商品券)- | SecurityDepositsPaid -- ^ Asset: Guarantee deposits (差入保証金)- | SuppliesOnHand -- ^ Asset: Supplies (貯蔵品)- | ContractAssets -- ^ Asset: Contract assets (契約資産)- | IncomeTaxesRefundReceivable -- ^ Asset: Income taxes refund receivable (未収還付法人税等)- | WorkInProcess -- ^ Asset: Work in process (仕掛品)- | DeferredTaxAssets -- ^ Asset: Deferred tax assets (繰延税金資産)- | LeasedAssets -- ^ Asset: Leased assets (リース資産)- | ToolsAndInstruments -- ^ Asset: Tools and instruments (工具器具)- | ConstructionInProgress -- ^ Asset: Construction in progress (建設仮勘定)- | Goodwill -- ^ Asset: Goodwill (のれん)- | SoftwareInProgress -- ^ Asset: Software in progress (ソフトウェア仮勘定)- | LongTermPrepaidExpenses -- ^ Asset: Long-term prepaid expenses (長期前払費用)- | DishonoredNotesReceivable -- ^ Asset: Dishonored notes receivable (不渡手形)- | PrepaidPensionCost -- ^ Asset: Prepaid pension costs (前払年金費用)- | NetDefinedBenefitAsset -- ^ Asset: Retirement benefit asset (退職給付に係る資産)- | DepositsInSpecialAccounts -- ^ Asset: Deposits in special accounts (別段預金)- | Structures -- ^ Asset: Structures (構築物)- | LeaseholdRights -- ^ Asset: Leasehold interests in land (借地権)- | NonOperatingNotesReceivable -- ^ Asset: Non-operating notes receivable (営業外受取手形)- | NonOperatingElectronicallyRecordedReceivable -- ^ Asset: Electronically recorded monetary claims - non-operating (営業外電子記録債権)- | RefundLiabilities -- ^ Liability: Refund liabilities (返金負債)- | NonOperatingNotesPayable -- ^ Liability: Non-operating notes payable (営業外支払手形)- | NonOperatingElectronicallyRecordedObligations -- ^ Liability: Electronically recorded obligations - non-operating (営業外電子記録債務)- | BonusesPayable -- ^ Liability: Accrued bonuses (未払賞与)- | AllowanceForRepairs -- ^ Liability: Provision for repairs (修繕引当金)- | AllowanceForProductWarranties -- ^ Liability: Provision for warranties (商品保証引当金)- | AllowanceForBonuses -- ^ Liability: Provision for bonuses (賞与引当金)- | DeferredTaxLiabilities -- ^ Liability: Deferred tax liabilities (繰延税金負債)- | LeaseObligations -- ^ Liability: Lease liabilities (リース債務)- | GuaranteeDepositsReceived -- ^ Liability: Guarantee deposits received (預り保証金)- | AllowanceForRetirementBenefits -- ^ Liability: Provision for retirement benefits (退職給付引当金)- | LongTermOtherPayables -- ^ Liability: Long-term accounts payable - other (長期未払金)- | NetDefinedBenefitLiability -- ^ Liability: Retirement benefit liability (退職給付に係る負債)- | StockSubscriptionDeposits -- ^ Equity: Deposits for subscriptions of shares (株式申込証拠金)- | LegalCapitalSurplus -- ^ Equity: Legal capital surplus (資本準備金)- | OtherCapitalSurplus -- ^ Equity: Other capital surplus (その他資本剰余金)- | DividendEqualizationReserve -- ^ Equity: Reserve for dividend equalization (配当平均積立金)- | RepairFundReserve -- ^ Equity: Reserve for repairs (修繕積立金)- | ConstructionFundReserve -- ^ Equity: Reserve for new construction (新築積立金)- | GeneralReserve -- ^ Equity: General reserve (別途積立金)- | ValuationDifferenceOnOtherSecurities -- ^ Equity: Valuation difference on available-for-sale securities (その他有価証券評価差額金)- | NonControllingInterests -- ^ Equity: Non-controlling interests (非支配株主持分)- | CapitalSurplus -- ^ Equity: Capital surplus (資本剰余金)- | EarnedSurplus -- ^ Equity: Retained earnings (利益剰余金)- | ServiceRevenue -- ^ Revenue: Service revenue (役務収益)- | OperatingRevenue -- ^ Revenue: Operating revenue (営業収益)- | GainOnSalesOfSecurities -- ^ Revenue: Gain on sale of securities (有価証券売却益)- | GainOnValuationOfSecurities -- ^ Revenue: Gain on valuation of securities (有価証券評価益)- | DividendsReceived -- ^ Revenue: Dividend income (受取配当金)- | InterestOnSecurities -- ^ Revenue: Interest on securities (有価証券利息)- | GainOnSalesOfInvestmentSecurities -- ^ Revenue: Gain on sale of investment securities (投資有価証券売却益)- | InsuranceGain -- ^ Revenue: Gain on insurance claims (保険差益)- | GainOnBargainPurchase -- ^ Revenue: Gain on bargain purchase (負ののれん発生益)- | ReversalOfAllowanceForRepairs -- ^ Revenue: Reversal of provision for repairs (修繕引当金戻入)- | ReversalOfAllowanceForProductWarranties -- ^ Revenue: Reversal of provision for warranties (商品保証引当金戻入)- | GainOnDonationOfFixedAssets -- ^ Revenue: Gain on receipt of donated non-current assets (固定資産受贈益)- | GainOnNationalSubsidies -- ^ Revenue: Gain on receipt of national subsidies (国庫補助金受贈益)- | GainOnConstructionGrants -- ^ Revenue: Gain on contribution received for construction (工事負担金受贈益)- | LandRentReceived -- ^ Revenue: Rental income from land (受取地代)- | SalesRebates -- ^ Revenue: Sales rebates (売上割戻)- | CostOfServices -- ^ Expense: Cost of services (役務原価)- | OperatingExpenses -- ^ Expense: Operating expenses (営業費用)- | InventoryShrinkageLoss -- ^ Expense: Inventory shrinkage loss (棚卸減耗損)- | LossOnValuationOfMerchandise -- ^ Expense: Valuation loss on goods (商品評価損)- | Bonuses -- ^ Expense: Bonuses (賞与)- | RetirementBenefitExpenses -- ^ Expense: Retirement benefit expenses (退職給付費用)- | ProvisionForRepairs -- ^ Expense: Provision for repairs (修繕引当金繰入)- | ProvisionForBonuses -- ^ Expense: Provision for bonuses (賞与引当金繰入)- | ProvisionForProductWarranties -- ^ Expense: Provision for warranties (商品保証引当金繰入)- | ResearchAndDevelopmentExpenses -- ^ Expense: Research and development expenses (研究開発費)- | AmortizationOfGoodwill -- ^ Expense: Amortization of goodwill (のれん償却)- | AmortizationOfSoftware -- ^ Expense: Amortization of software (ソフトウェア償却)- | AmortizationOfPatents -- ^ Expense: Amortization of patent rights (特許権償却)- | LeaseExpenses -- ^ Expense: Lease expenses (支払リース料)- | IncorporationExpenses -- ^ Expense: Organization expenses (創立費)- | StockIssuanceCosts -- ^ Expense: Share issuance costs (株式交付費)- | BusinessCommencementExpenses -- ^ Expense: Business commencement expenses (開業費)- | DevelopmentExpenses -- ^ Expense: Development expenses (開発費)- | LossOnSalesOfElectronicallyRecordedReceivables -- ^ Expense: Loss on sale of electronically recorded monetary claims (電子記録債権売却損)- | LossOnSalesOfReceivables -- ^ Expense: Loss on sale of receivables (債権売却損)- | LossOnSalesOfSecurities -- ^ Expense: Loss on sale of securities (有価証券売却損)- | LossOnValuationOfSecurities -- ^ Expense: Loss on valuation of securities (有価証券評価損)- | LossOnSalesOfInvestmentSecurities -- ^ Expense: Loss on sale of investment securities (投資有価証券売却損)- | LossOnFire -- ^ Expense: Loss on fire (火災損失)- | LossOnRetirementOfFixedAssets -- ^ Expense: Loss on retirement of non-current assets (固定資産除却損)- | LossOnReductionOfFixedAssets -- ^ Expense: Loss on tax purpose reduction entry of non-current assets (固定資産圧縮損)- | AdditionalIncomeTaxesForPriorPeriods -- ^ Expense: Additional income taxes for prior periods (追徴法人税等)- | RefundOfIncomeTaxes -- ^ Expense: Refund of income taxes (還付法人税等)- | PurchaseRebates -- ^ Expense: Purchase rebates (仕入割戻)- | WelfareExpenses -- ^ Expense: Welfare expenses (福利厚生費)- | MaintenanceExpenses -- ^ Expense: Maintenance expenses (保守費)- | StatutoryWelfareExpenses -- ^ Expense: Legal welfare expenses (法定福利費)- | LandRentPaid -- ^ Expense: Rent expenses on land (支払地代)- | InsuranceExpense -- ^ Expense: Insurance expenses (保険料)- | RepairsExpense -- ^ Expense: Repair expenses (修繕費)- | StorageExpenses -- ^ Expense: Storage costs (保管費)- | MembershipFees -- ^ Expense: Membership fees (諸会費)- | IncomeSummary -- ^ Asset: Income summary (損益)- | SuspenseAccount -- ^ Asset: Suspense account (未決算)- | ForeignExchangeGains -- ^ Revenue: Foreign exchange gains (為替差益)- | ForeignExchangeLosses -- ^ Expense: Foreign exchange losses (為替差損)- | ContraAccountForGuaranteeObligations -- ^ Asset: Contra account for guarantee obligations (保証債務見返)- | GuaranteeObligations -- ^ Liability: Guarantee obligations (保証債務)- | IncomeTaxesAdjustment -- ^ Expense: Income taxes - deferred (法人税等調整額)- | BranchCurrentAccount -- ^ Asset: Branch current account (支店)- | HeadOfficeCurrentAccount -- ^ Asset: Head office current account (本店)- | NetIncomeAttributableToNCI -- ^ Expense: Profit attributable to non-controlling interests (非支配株主に帰属する当期純利益)- | NetLossAttributableToNCI -- ^ Revenue: Loss attributable to non-controlling interests (非支配株主に帰属する当期純損失)- | TradingSecurities -- ^ Asset: Trading securities (売買目的有価証券)- | HeldToMaturityBonds -- ^ Asset: Held-to-maturity bonds (満期保有目的債券)- | SubsidiaryStocks -- ^ Asset: Shares of subsidiaries (子会社株式)- | AffiliateStocks -- ^ Asset: Shares of associates (関連会社株式)- | AvailableForSaleSecurities -- ^ Asset: Available-for-sale securities (その他有価証券)- | ConsumptionTaxRefundReceivable -- ^ Asset: Consumption tax refund receivable (未収還付消費税)- | PropertyTaxPayable -- ^ Liability: Property tax payable (未払固定資産税)- | DepositsReceivedFromOfficers -- ^ Liability: Deposits received from officers (役員預り金)- | EntertainmentExpenses -- ^ Expense: Entertainment expenses (交際費)- | MeetingExpenses -- ^ Expense: Meeting expenses (会議費)- | NewspaperBooksExpenses -- ^ Expense: Newspapers and books (新聞図書費)- | RawMaterials -- ^ Asset: Raw materials (原材料)- | GoodsInTransit -- ^ Asset: Goods in transit (未着品)- | SalesAllowances -- ^ Revenue: Sales allowances (売上値引)- | PurchaseAllowances -- ^ Expense: Purchase allowances (仕入値引)- | ReversalOfAllowanceForBonuses- -- ^ Revenue: Reversal of provision for bonuses (賞与引当金戻入)- | AccountTitle -- ^ Wildcard (ワイルドカード — 任意の科目にマッチ。projWithBase 等の問い合わせ用で, 実 posting には使わない)- deriving (Show, Ord, Eq, Enum, Generic, Bounded)---- Commutation の実用法は examples の文脈から「通信費」であることが確認済--- (2026-06-11 調査)。Enum/Binary 序数の安定のため削除はせず, 新名称への移行を促す。-{-# DEPRECATED Commutation "通信費 (communication expenses) — use 'CommunicationExpenses' instead" #-}--instance NFData AccountTitles--instance Hashable AccountTitles where- {-# INLINE hashWithSalt #-}- hashWithSalt salt x = hashWithSalt salt (fromEnum x)---- | Serialize a title as a two-byte big-endian code: @0x8000 + n@, where--- @n@ is the title's fixed number from 'accountCode', or @0xFFFF@ for the--- wildcard 'AccountTitle'. The high bit marks the 0.6 encoding: bytes written--- by 0.5.x (the declaration index, always below @0x8000@) and unknown codes--- fail to decode, so a title added later never shifts an existing code.-instance Binary.Binary AccountTitles where- {-# INLINE put #-}- put = BinaryPut.putWord16be . accountCode- {-# INLINE get #-}- get = do- code <- BinaryGet.getWord16be- case Map.lookup code accountTitlesByCode of- Just title -> pure title- Nothing -> fail ("AccountTitles: unknown or unmarked code " ++ show code)---- | The fixed wire code of each title. The case is total and written out, so--- adding a title without a code fails to compile. The numbers are the--- declaration indices of develop at this change, frozen; a new title--- takes the next unused number wherever it is declared. Decoding uses the--- inverse table built from this function, not a second hand-written table.-accountCode :: AccountTitles -> Word16-accountCode title = case title of- Cash -> 0x8000- Deposits -> 0x8001- CurrentDeposits -> 0x8002- Securities -> 0x8003- InvestmentSecurities -> 0x8004- InvestmentInAssociate -> 0x8005- LongTermNationalBonds -> 0x8006- ShortTermNationalBonds -> 0x8007- Products -> 0x8008- Machinery -> 0x8009- Building -> 0x800A- Vehicle -> 0x800B- StockInvestment -> 0x800C- EquipmentInvestment -> 0x800D- LongTermLoansReceivable -> 0x800E- AccountsReceivable -> 0x800F- ShortTermLoansReceivable -> 0x8010- ReserveDepositReceivable -> 0x8011- Gold -> 0x8012- GovernmentService -> 0x8013- CapitalStock -> 0x8014- RetainedEarnings -> 0x8015- LongTermLoansPayable -> 0x8016- ShortTermLoansPayable -> 0x8017- LoansPayable -> 0x8018- ReserveForDepreciation -> 0x8019- DepositPayable -> 0x801A- LongTermNationalBondsPayable -> 0x801B- ShortTermNationalBondsPayable -> 0x801C- ReserveDepositPayable -> 0x801D- CentralBankNotePayable -> 0x801E- Depreciation -> 0x801F- AmortizationExpense -> 0x8020- SalesCost -> 0x8021- BusinessTrip -> 0x8022- Commutation -> 0x8023- UtilitiesExpense -> 0x8024- RentExpense -> 0x8025- AdvertisingExpense -> 0x8026- DeliveryExpenses -> 0x8027- SuppliesExpenses -> 0x8028- MiscellaneousExpenses -> 0x8029- WageExpenditure -> 0x802A- InterestExpense -> 0x802B- TaxesExpense -> 0x802C- ConsumptionExpenditure -> 0x802D- SubsidyExpense -> 0x802E- CentralBankPaymentExpense -> 0x802F- Purchases -> 0x8030- NetIncome -> 0x8031- ValueAdded -> 0x8032- SubsidyIncome -> 0x8033- NationalBondInterestEarned -> 0x8034- DepositInterestEarned -> 0x8035- GrossProfit -> 0x8036- OrdinaryProfit -> 0x8037- InterestEarned -> 0x8038- ReceiptFee -> 0x8039- RentalIncome -> 0x803A- WageEarned -> 0x803B- TaxesRevenue -> 0x803C- CentralBankPaymentIncome -> 0x803D- Sales -> 0x803E- EquityInEarningsOfInvestee -> 0x803F- NetLoss -> 0x8040- PettyCash -> 0x8041- NotesReceivable -> 0x8042- ElectronicallyRecordedReceivable -> 0x8043- CreditCardReceivable -> 0x8044- NotesLoansReceivable -> 0x8045- MerchandiseInventory -> 0x8046- AdvancesPaid -> 0x8047- PrepaidExpenses -> 0x8048- AccruedRevenue -> 0x8049- OtherReceivables -> 0x804A- PaymentsOnBehalf -> 0x804B- SuspensePayments -> 0x804C- ConsumptionTaxPaid -> 0x804D- PrepaidCorporateIncomeTaxes -> 0x804E- Land -> 0x804F- Fixtures -> 0x8050- Patent -> 0x8051- Trademark -> 0x8052- Software -> 0x8053- CashOverShort -> 0x8054- AccountsPayable -> 0x8055- NotesPayable -> 0x8056- ElectronicallyRecordedObligations -> 0x8057- NotesLoansPayable -> 0x8058- BankOverdraft -> 0x8059- AdvancesReceived -> 0x805A- UnearnedRevenue -> 0x805B- AccruedExpenses -> 0x805C- OtherPayables -> 0x805D- DepositsReceived -> 0x805E- SuspenseReceipts -> 0x805F- ConsumptionTaxReceived -> 0x8060- AccruedConsumptionTax -> 0x8061- AccruedCorporateIncomeTaxes -> 0x8062- UnpaidDividends -> 0x8063- AllowanceForDoubtfulAccounts -> 0x8064- AccumulatedDepreciation -> 0x8065- LegalRetainedEarnings -> 0x8066- CumulativeTranslationAdjustment -> 0x8067- ProvisionForDoubtfulAccounts -> 0x8068- BadDebtLoss -> 0x8069- LossOnSalesOfFixedAssets -> 0x806A- LossOnSalesOfNotesReceivable -> 0x806B- PaymentFees -> 0x806C- MiscellaneousLoss -> 0x806D- CorporateIncomeTaxes -> 0x806E- CommunicationExpenses -> 0x806F- GainOnSalesOfFixedAssets -> 0x8070- RecoveryOfBadDebts -> 0x8071- MiscellaneousIncome -> 0x8072- ReversalOfAllowanceForDoubtfulAccounts -> 0x8073- TimeDeposits -> 0x8074- LoansReceivable -> 0x8075- GiftCertificatesReceived -> 0x8076- SecurityDepositsPaid -> 0x8077- SuppliesOnHand -> 0x8078- ContractAssets -> 0x8079- IncomeTaxesRefundReceivable -> 0x807A- WorkInProcess -> 0x807B- DeferredTaxAssets -> 0x807C- LeasedAssets -> 0x807D- ToolsAndInstruments -> 0x807E- ConstructionInProgress -> 0x807F- Goodwill -> 0x8080- SoftwareInProgress -> 0x8081- LongTermPrepaidExpenses -> 0x8082- DishonoredNotesReceivable -> 0x8083- PrepaidPensionCost -> 0x8084- NetDefinedBenefitAsset -> 0x8085- DepositsInSpecialAccounts -> 0x8086- Structures -> 0x8087- LeaseholdRights -> 0x8088- NonOperatingNotesReceivable -> 0x8089- NonOperatingElectronicallyRecordedReceivable -> 0x808A- RefundLiabilities -> 0x808B- NonOperatingNotesPayable -> 0x808C- NonOperatingElectronicallyRecordedObligations -> 0x808D- BonusesPayable -> 0x808E- AllowanceForRepairs -> 0x808F- AllowanceForProductWarranties -> 0x8090- AllowanceForBonuses -> 0x8091- DeferredTaxLiabilities -> 0x8092- LeaseObligations -> 0x8093- GuaranteeDepositsReceived -> 0x8094- AllowanceForRetirementBenefits -> 0x8095- LongTermOtherPayables -> 0x8096- NetDefinedBenefitLiability -> 0x8097- StockSubscriptionDeposits -> 0x8098- LegalCapitalSurplus -> 0x8099- OtherCapitalSurplus -> 0x809A- DividendEqualizationReserve -> 0x809B- RepairFundReserve -> 0x809C- ConstructionFundReserve -> 0x809D- GeneralReserve -> 0x809E- ValuationDifferenceOnOtherSecurities -> 0x809F- NonControllingInterests -> 0x80A0- CapitalSurplus -> 0x80A1- EarnedSurplus -> 0x80A2- ServiceRevenue -> 0x80A3- OperatingRevenue -> 0x80A4- GainOnSalesOfSecurities -> 0x80A5- GainOnValuationOfSecurities -> 0x80A6- DividendsReceived -> 0x80A7- InterestOnSecurities -> 0x80A8- GainOnSalesOfInvestmentSecurities -> 0x80A9- InsuranceGain -> 0x80AA- GainOnBargainPurchase -> 0x80AB- ReversalOfAllowanceForRepairs -> 0x80AC- ReversalOfAllowanceForProductWarranties -> 0x80AD- GainOnDonationOfFixedAssets -> 0x80AE- GainOnNationalSubsidies -> 0x80AF- GainOnConstructionGrants -> 0x80B0- LandRentReceived -> 0x80B1- SalesRebates -> 0x80B2- CostOfServices -> 0x80B3- OperatingExpenses -> 0x80B4- InventoryShrinkageLoss -> 0x80B5- LossOnValuationOfMerchandise -> 0x80B6- Bonuses -> 0x80B7- RetirementBenefitExpenses -> 0x80B8- ProvisionForRepairs -> 0x80B9- ProvisionForBonuses -> 0x80BA- ProvisionForProductWarranties -> 0x80BB- ResearchAndDevelopmentExpenses -> 0x80BC- AmortizationOfGoodwill -> 0x80BD- AmortizationOfSoftware -> 0x80BE- AmortizationOfPatents -> 0x80BF- LeaseExpenses -> 0x80C0- IncorporationExpenses -> 0x80C1- StockIssuanceCosts -> 0x80C2- BusinessCommencementExpenses -> 0x80C3- DevelopmentExpenses -> 0x80C4- LossOnSalesOfElectronicallyRecordedReceivables -> 0x80C5- LossOnSalesOfReceivables -> 0x80C6- LossOnSalesOfSecurities -> 0x80C7- LossOnValuationOfSecurities -> 0x80C8- LossOnSalesOfInvestmentSecurities -> 0x80C9- LossOnFire -> 0x80CA- LossOnRetirementOfFixedAssets -> 0x80CB- LossOnReductionOfFixedAssets -> 0x80CC- AdditionalIncomeTaxesForPriorPeriods -> 0x80CD- RefundOfIncomeTaxes -> 0x80CE- PurchaseRebates -> 0x80CF- WelfareExpenses -> 0x80D0- MaintenanceExpenses -> 0x80D1- StatutoryWelfareExpenses -> 0x80D2- LandRentPaid -> 0x80D3- InsuranceExpense -> 0x80D4- RepairsExpense -> 0x80D5- StorageExpenses -> 0x80D6- MembershipFees -> 0x80D7- IncomeSummary -> 0x80D8- SuspenseAccount -> 0x80D9- ForeignExchangeGains -> 0x80DA- ForeignExchangeLosses -> 0x80DB- ContraAccountForGuaranteeObligations -> 0x80DC- GuaranteeObligations -> 0x80DD- IncomeTaxesAdjustment -> 0x80DE- BranchCurrentAccount -> 0x80DF- HeadOfficeCurrentAccount -> 0x80E0- NetIncomeAttributableToNCI -> 0x80E1- NetLossAttributableToNCI -> 0x80E2- TradingSecurities -> 0x80E3- HeldToMaturityBonds -> 0x80E4- SubsidiaryStocks -> 0x80E5- AffiliateStocks -> 0x80E6- AvailableForSaleSecurities -> 0x80E7- ConsumptionTaxRefundReceivable -> 0x80E8- PropertyTaxPayable -> 0x80E9- DepositsReceivedFromOfficers -> 0x80EA- EntertainmentExpenses -> 0x80EB- MeetingExpenses -> 0x80EC- NewspaperBooksExpenses -> 0x80ED- RawMaterials -> 0x80EE- GoodsInTransit -> 0x80EF- SalesAllowances -> 0x80F0- PurchaseAllowances -> 0x80F1- ReversalOfAllowanceForBonuses -> 0x80F2- AccountTitle -> 0xFFFF---- | Inverse of the fixed codes, shared by every decode.-accountTitlesByCode :: Map.Map Word16 AccountTitles-accountTitlesByCode = Map.fromList [(accountCode title, title) | title <- [minBound .. maxBound]]--instance Element AccountTitles where- {-# INLINE wildcard #-}- wildcard = AccountTitle-----instance BaseClass AccountTitles where-+{-# OPTIONS_GHC -Werror=incomplete-patterns -Werror=missing-fields #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE ExistentialQuantification #-}+{-# LANGUAGE StrictData #-}+{-# LANGUAGE Strict #-}+{-# LANGUAGE DeriveGeneric #-}++-- | This module is large because it keeps the complete account title table in one place.+--+-- To add an account title, add one constructor line and one equation for 'row'.+-- Assign an unused wire code and keep retired codes such as @0x8023@ reserved.+-- For a title listed in the JCCI 2022 fixture, enter its aliases in fixture order.+-- For a JCCI title, add a matching pattern definition and a @COMPLETE@ entry+-- to @ExchangeAlgebra.Accounting.Account.Jcci@, along with its export and signature entry.+module ExchangeAlgebra.Accounting.Account.Title+ ( AccountTitles(..)+ , Row(..)+ , row+ , isJcciTitle+ ) where++import ExchangeAlgebra.Algebra.Element.Representation (Element(..))+import ExchangeAlgebra.Algebra.Base.Representation (BaseClass(..))+import GHC.Generics (Generic)+import Data.Hashable (Hashable(..))+import Control.DeepSeq (NFData(..))+import Data.Text (Text)+import Data.Word (Word16)+import ExchangeAlgebra.Accounting.Account.Classification+import ExchangeAlgebra.Accounting.Account.Spec (AccountSpec(..), AccountSemantics(..))+import qualified Data.Map.Strict as Map+import qualified Data.Binary as Binary+import qualified Data.Binary.Get as BinaryGet+import qualified Data.Binary.Put as BinaryPut++-- ** Account Titles++data AccountTitles = Cash -- ^ Asset: Cash (現金)+ | Deposits -- ^ Asset: Savings deposits (普通預金)+ | CurrentDeposits -- ^ Asset: Current deposits (当座預金)+ | Securities -- ^ Asset: Securities (有価証券)+ | InvestmentSecurities -- ^ Asset: Investment securities (投資有価証券)+ | InvestmentInAssociate -- ^ Asset: Investment in associate (関係会社株式). Carrying amount under the equity method (持分法適用投資勘定).+ | LongTermNationalBonds -- ^ Asset: Long-term national bonds (長期国債)+ | ShortTermNationalBonds -- ^ Asset: Short-term national bonds (短期国債)+ | Products -- ^ Asset: Products (商品)。分記法用。3 分法 (仕入\/売上\/繰越商品) では 'MerchandiseInventory' を使う+ | Machinery -- ^ Asset: Machinery and equipment (機械装置)+ | Building -- ^ Asset: Buildings (建物)+ | Vehicle -- ^ Asset: Vehicles (車両運搬具)+ | StockInvestment -- ^ Asset: Stock investment (株式投資)+ | EquipmentInvestment -- ^ Asset: Equipment investment (設備投資)+ | LongTermLoansReceivable -- ^ Asset: Long-term loans receivable (長期貸付金)+ | AccountsReceivable -- ^ Asset: Accounts receivable (売掛金)+ | ShortTermLoansReceivable -- ^ Asset: Short-term loans receivable (短期貸付金)+ | ReserveDepositReceivable -- ^ Asset: Reserve deposits, asset side (準備預金, 資産側 — 市中銀行が中央銀行に置く準備預金。SNA\/マクロ系)+ | Gold -- ^ Asset: Gold (金)+ | GovernmentService -- ^ Asset: Government service (政府サービス。SNA\/マクロ系)+ | CapitalStock -- ^ Equity: Capital stock (資本金)+ | RetainedEarnings -- ^ Equity: Retained earnings brought forward (繰越利益剰余金)+ | LongTermLoansPayable -- ^ Liability: Long-term loans payable (長期借入金)+ | ShortTermLoansPayable -- ^ Liability: Short-term loans payable (短期借入金)+ | LoansPayable -- ^ Liability: Loans payable (借入金)+ | ReserveForDepreciation -- ^ Liability: Reserve for depreciation (減価償却引当金 — SNA\/マクロ系の旧称。簿記の間接法には 'AccumulatedDepreciation' (減価償却累計額) を使う)+ | DepositPayable -- ^ Liability: Deposits accepted (受入預金 — 銀行側の負債としての預金。SNA\/マクロ系。従業員等からの預り金は 'DepositsReceived')+ | LongTermNationalBondsPayable -- ^ Liability: Long-term national bonds payable (長期国債, 発行側)+ | ShortTermNationalBondsPayable -- ^ Liability: Short-term national bonds payable (短期国債, 発行側)+ | ReserveDepositPayable -- ^ Liability: Reserve deposits, liability side (準備預金, 負債側 — 中央銀行が受け入れる準備預金。SNA\/マクロ系)。※簿記の買掛金は 'AccountsPayable' を使うこと (旧 examples が本科目を買掛金の代用にしていた経緯あり)+ | CentralBankNotePayable -- ^ Liability: Central bank notes (発行銀行券。SNA\/マクロ系)+ | Depreciation -- ^ Expense: Depreciation (減価償却費)+ | AmortizationExpense -- ^ Expense: Amortization expense for intangibles (無形固定資産償却費 — 特許権・商標権・ソフトウェア等の無形資産の償却費。有形の 'Depreciation' (減価償却費) と区別される)+ | SalesCost -- ^ Expense: Cost of sales (売上原価)+ | BusinessTrip -- ^ Expense: Travel and transportation (旅費交通費)+ | UtilitiesExpense -- ^ Expense: Utilities (水道光熱費)+ | RentExpense -- ^ Expense: Rent (支払家賃)+ | AdvertisingExpense -- ^ Expense: Advertising (広告宣伝費)+ | DeliveryExpenses -- ^ Expense: Delivery (発送費)+ | SuppliesExpenses -- ^ Expense: Supplies expense (消耗品費)+ | MiscellaneousExpenses -- ^ Expense: Miscellaneous (雑費)+ | WageExpenditure -- ^ Expense: Wages (給料)+ | InterestExpense -- ^ Expense: Interest expense (支払利息)+ | TaxesExpense -- ^ Expense: Taxes (租税公課)+ | ConsumptionExpenditure -- ^ Expense: Consumption expenditure (消費支出。SNA\/マクロ系)+ | SubsidyExpense -- ^ Expense: Subsidy expenditure (補助金支出。SNA\/マクロ系)+ | CentralBankPaymentExpense -- ^ Expense: Payment to national treasury (国庫納付金支出。SNA\/マクロ系)+ | Purchases -- ^ Expense: Purchases (仕入)+ | NetIncome -- ^ Expense: Net income (当期純利益 — 決算振替用。借方側に立つため Expense 区分)+ | ValueAdded -- ^ Revenue: Value added (付加価値。SNA\/マクロ系)+ | SubsidyIncome -- ^ Revenue: Subsidy income (補助金収入。SNA\/マクロ系)+ | NationalBondInterestEarned -- ^ Revenue: National bond interest earned (国債利息収入)+ | DepositInterestEarned -- ^ Revenue: Deposit interest earned (預金利息収入)+ | GrossProfit -- ^ Revenue: Gross profit (売上総利益 — 決算振替用)+ | OrdinaryProfit -- ^ Revenue: Ordinary profit (経常利益 — 決算振替用)+ | InterestEarned -- ^ Revenue: Interest earned (受取利息)+ | ReceiptFee -- ^ Revenue: Receipt fee (受取手数料。支払側は 'PaymentFees')+ | RentalIncome -- ^ Revenue: Rental income (受取家賃)+ | WageEarned -- ^ Revenue: Wage income (賃金収入。SNA\/マクロ系)+ | TaxesRevenue -- ^ Revenue: Tax revenue (租税収入。SNA\/マクロ系)+ | CentralBankPaymentIncome -- ^ Revenue: Central bank payment received (国庫納付金収入。SNA\/マクロ系)+ | Sales -- ^ Revenue: Sales (売上)+ | EquityInEarningsOfInvestee -- ^ Revenue: Equity in earnings of investee+ -- (持分法による投資利益). Recognized under the equity method.+ | NetLoss -- ^ Revenue: Net loss (当期純損失 — 決算振替用。貸方側に立つため Revenue 区分)+ -- Elementary bookkeeping (日商簿記 3 級水準) additions.+ -- Appended before the 'AccountTitle' wildcard so that only the+ -- wildcard's Enum/Binary ordinal shifts (existing serialized+ -- bases remain compatible).+ --+ -- Assets (資産)+ | PettyCash -- ^ Asset: Petty cash (小口現金)+ | NotesReceivable -- ^ Asset: Notes receivable (受取手形)+ | ElectronicallyRecordedReceivable -- ^ Asset: Electronically recorded monetary claims (電子記録債権)+ | CreditCardReceivable -- ^ Asset: Credit card receivable (クレジット売掛金)+ | NotesLoansReceivable -- ^ Asset: Loans receivable on notes (手形貸付金)+ | MerchandiseInventory -- ^ Asset: Merchandise inventory (繰越商品). Use under the periodic/3-account method (3 分法: Purchases\/Sales\/MerchandiseInventory). For 分記法, which records the cost of the goods and the gain on sales at each sale, use 'Products' instead.+ | AdvancesPaid -- ^ Asset: Advances paid (前払金)+ | PrepaidExpenses -- ^ Asset: Prepaid expenses (前払費用), deferral account (経過勘定)+ | AccruedRevenue -- ^ Asset: Accrued revenue (未収収益), accrual account (経過勘定)+ | OtherReceivables -- ^ Asset: Other receivables (未収入金)+ | PaymentsOnBehalf -- ^ Asset: Payments made on behalf (立替金)+ | SuspensePayments -- ^ Asset: Suspense payments (仮払金)+ | ConsumptionTaxPaid -- ^ Asset: Consumption tax paid (仮払消費税)+ | PrepaidCorporateIncomeTaxes -- ^ Asset: Prepaid corporate income taxes (仮払法人税等)+ | Land -- ^ Asset: Land (土地)+ | Fixtures -- ^ Asset: Fixtures and equipment (備品)+ | Patent -- ^ Asset: Patent (特許権)+ | Trademark -- ^ Asset: Trademark (商標権)+ | Software -- ^ Asset: Software (ソフトウェア)+ | CashOverShort -- ^ Asset: Cash over and short (現金過不足), a temporary/suspense account cleared at closing to MiscellaneousIncome\/MiscellaneousLoss+ -- Liability (負債)+ | AccountsPayable -- ^ Liability: Accounts payable (買掛金)+ | NotesPayable -- ^ Liability: Notes payable (支払手形)+ | ElectronicallyRecordedObligations -- ^ Liability: Electronically recorded monetary obligations (電子記録債務)+ | NotesLoansPayable -- ^ Liability: Loans payable on notes (手形借入金)+ | BankOverdraft -- ^ Liability: Bank overdraft (当座借越)+ | AdvancesReceived -- ^ Liability: Advances received (前受金)+ | UnearnedRevenue -- ^ Liability: Unearned revenue (前受収益), deferral account (経過勘定)+ | AccruedExpenses -- ^ Liability: Accrued expenses (未払費用), accrual account (経過勘定)+ | OtherPayables -- ^ Liability: Other payables (未払金)+ | DepositsReceived -- ^ Liability: Deposits received (預り金)+ | SuspenseReceipts -- ^ Liability: Suspense receipts (仮受金)+ | ConsumptionTaxReceived -- ^ Liability: Consumption tax received (仮受消費税)+ | AccruedConsumptionTax -- ^ Liability: Accrued (unpaid) consumption tax (未払消費税)+ | AccruedCorporateIncomeTaxes -- ^ Liability: Accrued (unpaid) corporate income taxes (未払法人税等)+ | UnpaidDividends -- ^ Liability: Unpaid dividends (未払配当金)+ | AllowanceForDoubtfulAccounts -- ^ Asset (contra): Allowance for doubtful accounts (貸倒引当金), a credit-balance valuation account (評価勘定) deducted from receivables. Division is Assets with @isContra = True@ (Definition 7 amendment, 0.5.0.0); home side stays Credit, values stay non-negative, Hat\/Not structure intact. B\/S deduction (net) presentation is the ExchangeAlgebra.IO.Output module's job.+ | AccumulatedDepreciation -- ^ Asset (contra): Accumulated depreciation (減価償却累計額), valuation account (評価勘定) under the indirect method (間接法), deducted from the related depreciable assets. Division is Assets with @isContra = True@ for the same reason as 'AllowanceForDoubtfulAccounts'. This is the canonical bookkeeping account for accumulated depreciation; the existing 'ReserveForDepreciation' is retained as the legacy SNA\/macro-accounting name.+ -- Equity (資本)+ | LegalRetainedEarnings -- ^ Equity: Legal (appropriated) retained earnings reserve (利益準備金)+ | CumulativeTranslationAdjustment -- ^ Equity: Cumulative translation adjustment (為替換算調整勘定; 在外子会社等の外貨建財務諸表の換算差額を計上する OCI/資本の部の項目)+ -- Cost (費用)+ | ProvisionForDoubtfulAccounts -- ^ Expense: Provision for doubtful accounts (貸倒引当金繰入)+ | BadDebtLoss -- ^ Expense: Bad debt loss (貸倒損失)+ | LossOnSalesOfFixedAssets -- ^ Expense: Loss on sales of fixed assets (固定資産売却損)+ | LossOnSalesOfNotesReceivable -- ^ Expense: Loss on sales of notes receivable (手形売却損)+ | PaymentFees -- ^ Expense: Payment fees / fees paid (支払手数料), the debit counterpart of 'ReceiptFee'+ | MiscellaneousLoss -- ^ Expense: Miscellaneous loss (雑損)+ | CorporateIncomeTaxes -- ^ Expense: Corporate income taxes (法人税等)+ | CommunicationExpenses -- ^ Expense: Communication expenses (通信費)+ -- Revenue (収益)+ | GainOnSalesOfFixedAssets -- ^ Revenue: Gain on sales of fixed assets (固定資産売却益)+ | RecoveryOfBadDebts -- ^ Revenue: Recovery of bad debts written off (償却債権取立益)+ | MiscellaneousIncome -- ^ Revenue: Miscellaneous income (雑益)+ | ReversalOfAllowanceForDoubtfulAccounts -- ^ Revenue: Reversal of allowance for doubtful accounts (貸倒引当金戻入). Credit counterpart used by the 差額補充法/洗替法 when the estimated allowance is smaller than the existing balance (the excess of 'AllowanceForDoubtfulAccounts' is released).+ -- V-Land 2: JCCI grade-2 commercial-bookkeeping vocabulary.+ | TimeDeposits -- ^ Asset: Time deposits (定期預金)+ | LoansReceivable -- ^ Asset: Loans receivable (貸付金)+ | GiftCertificatesReceived -- ^ Asset: Gift certificates received (受取商品券)+ | SecurityDepositsPaid -- ^ Asset: Guarantee deposits (差入保証金)+ | SuppliesOnHand -- ^ Asset: Supplies on hand (貯蔵品)+ | ContractAssets -- ^ Asset: Contract assets (契約資産)+ | IncomeTaxesRefundReceivable -- ^ Asset: Income taxes refund receivable (未収還付法人税等)+ | WorkInProcess -- ^ Asset: Work in process (仕掛品)+ | DeferredTaxAssets -- ^ Asset: Deferred tax assets (繰延税金資産)+ | LeasedAssets -- ^ Asset: Leased assets (リース資産)+ | ToolsAndInstruments -- ^ Asset: Tools and instruments (工具器具)+ | ConstructionInProgress -- ^ Asset: Construction in progress (建設仮勘定)+ | Goodwill -- ^ Asset: Goodwill (のれん)+ | SoftwareInProgress -- ^ Asset: Software in progress (ソフトウェア仮勘定)+ | LongTermPrepaidExpenses -- ^ Asset: Long-term prepaid expenses (長期前払費用)+ | DishonoredNotesReceivable -- ^ Asset: Dishonored notes receivable (不渡手形)+ | PrepaidPensionCost -- ^ Asset: Prepaid pension costs (前払年金費用)+ | NetDefinedBenefitAsset -- ^ Asset: Retirement benefit asset (退職給付に係る資産)+ | DepositsInSpecialAccounts -- ^ Asset: Deposits in special accounts (別段預金)+ | Structures -- ^ Asset: Structures (構築物)+ | LeaseholdRights -- ^ Asset: Leasehold interests in land (借地権)+ | NonOperatingNotesReceivable -- ^ Asset: Non-operating notes receivable (営業外受取手形)+ | NonOperatingElectronicallyRecordedReceivable -- ^ Asset: Electronically recorded monetary claims - non-operating (営業外電子記録債権)+ | RefundLiabilities -- ^ Liability: Refund liabilities (返金負債)+ | NonOperatingNotesPayable -- ^ Liability: Non-operating notes payable (営業外支払手形)+ | NonOperatingElectronicallyRecordedObligations -- ^ Liability: Electronically recorded obligations - non-operating (営業外電子記録債務)+ | BonusesPayable -- ^ Liability: Accrued bonuses (未払賞与)+ | AllowanceForRepairs -- ^ Liability: Allowance for repairs (修繕引当金)+ | AllowanceForProductWarranties -- ^ Liability: Allowance for warranties (商品保証引当金)+ | AllowanceForBonuses -- ^ Liability: Allowance for bonuses (賞与引当金)+ | DeferredTaxLiabilities -- ^ Liability: Deferred tax liabilities (繰延税金負債)+ | LeaseObligations -- ^ Liability: Lease liabilities (リース債務)+ | GuaranteeDepositsReceived -- ^ Liability: Guarantee deposits received (預り保証金)+ | AllowanceForRetirementBenefits -- ^ Liability: Provision for retirement benefits (退職給付引当金)+ | LongTermOtherPayables -- ^ Liability: Long-term accounts payable - other (長期未払金)+ | NetDefinedBenefitLiability -- ^ Liability: Retirement benefit liability (退職給付に係る負債)+ | StockSubscriptionDeposits -- ^ Equity: Deposits for subscriptions of shares (株式申込証拠金)+ | LegalCapitalSurplus -- ^ Equity: Legal capital surplus (資本準備金)+ | OtherCapitalSurplus -- ^ Equity: Other capital surplus (その他資本剰余金)+ | DividendEqualizationReserve -- ^ Equity: Reserve for dividend equalization (配当平均積立金)+ | RepairFundReserve -- ^ Equity: Reserve for repairs (修繕積立金)+ | ConstructionFundReserve -- ^ Equity: Reserve for new construction (新築積立金)+ | GeneralReserve -- ^ Equity: General reserve (別途積立金)+ | ValuationDifferenceOnOtherSecurities -- ^ Equity: Valuation difference on available-for-sale securities (その他有価証券評価差額金)+ | NonControllingInterests -- ^ Equity: Non-controlling interests (非支配株主持分)+ | CapitalSurplus -- ^ Equity: Capital surplus (資本剰余金)+ | EarnedSurplus -- ^ Equity: Retained earnings (利益剰余金)+ | ServiceRevenue -- ^ Revenue: Service revenue (役務収益)+ | OperatingRevenue -- ^ Revenue: Operating revenue (営業収益)+ | GainOnSalesOfSecurities -- ^ Revenue: Gain on sale of securities (有価証券売却益)+ | GainOnValuationOfSecurities -- ^ Revenue: Gain on valuation of securities (有価証券評価益)+ | DividendsReceived -- ^ Revenue: Dividend income (受取配当金)+ | InterestOnSecurities -- ^ Revenue: Interest on securities (有価証券利息)+ | GainOnSalesOfInvestmentSecurities -- ^ Revenue: Gain on sale of investment securities (投資有価証券売却益)+ | InsuranceGain -- ^ Revenue: Gain on insurance claims (保険差益)+ | GainOnBargainPurchase -- ^ Revenue: Gain on bargain purchase (負ののれん発生益)+ | ReversalOfAllowanceForRepairs -- ^ Revenue: Reversal of allowance for repairs (修繕引当金戻入)+ | ReversalOfAllowanceForProductWarranties -- ^ Revenue: Reversal of allowance for warranties (商品保証引当金戻入)+ | GainOnDonationOfFixedAssets -- ^ Revenue: Gain on receipt of donated non-current assets (固定資産受贈益)+ | GainOnNationalSubsidies -- ^ Revenue: Gain on receipt of national subsidies (国庫補助金受贈益)+ | GainOnConstructionGrants -- ^ Revenue: Gain on contribution received for construction (工事負担金受贈益)+ | LandRentReceived -- ^ Revenue: Rental income from land (受取地代)+ | SalesRebates -- ^ Revenue: Sales rebates (売上割戻)+ | CostOfServices -- ^ Expense: Cost of services (役務原価)+ | OperatingExpenses -- ^ Expense: Operating expenses (営業費用)+ | InventoryShrinkageLoss -- ^ Expense: Inventory shrinkage loss (棚卸減耗損)+ | LossOnValuationOfMerchandise -- ^ Expense: Valuation loss on goods (商品評価損)+ | Bonuses -- ^ Expense: Bonuses (賞与)+ | RetirementBenefitExpenses -- ^ Expense: Retirement benefit expenses (退職給付費用)+ | ProvisionForRepairs -- ^ Expense: Provision for repairs (修繕引当金繰入)+ | ProvisionForBonuses -- ^ Expense: Provision for bonuses (賞与引当金繰入)+ | ProvisionForProductWarranties -- ^ Expense: Provision for warranties (商品保証引当金繰入)+ | ResearchAndDevelopmentExpenses -- ^ Expense: Research and development expenses (研究開発費)+ | AmortizationOfGoodwill -- ^ Expense: Amortization of goodwill (のれん償却)+ | AmortizationOfSoftware -- ^ Expense: Amortization of software (ソフトウェア償却)+ | AmortizationOfPatents -- ^ Expense: Amortization of patent rights (特許権償却)+ | LeaseExpenses -- ^ Expense: Lease expenses (支払リース料)+ | IncorporationExpenses -- ^ Expense: Organization expenses (創立費)+ | StockIssuanceCosts -- ^ Expense: Share issuance costs (株式交付費)+ | BusinessCommencementExpenses -- ^ Expense: Business commencement expenses (開業費)+ | DevelopmentExpenses -- ^ Expense: Development expenses (開発費)+ | LossOnSalesOfElectronicallyRecordedReceivables -- ^ Expense: Loss on sale of electronically recorded monetary claims (電子記録債権売却損)+ | LossOnSalesOfReceivables -- ^ Expense: Loss on sale of receivables (債権売却損)+ | LossOnSalesOfSecurities -- ^ Expense: Loss on sale of securities (有価証券売却損)+ | LossOnValuationOfSecurities -- ^ Expense: Loss on valuation of securities (有価証券評価損)+ | LossOnSalesOfInvestmentSecurities -- ^ Expense: Loss on sale of investment securities (投資有価証券売却損)+ | LossOnFire -- ^ Expense: Loss on fire (火災損失)+ | LossOnRetirementOfFixedAssets -- ^ Expense: Loss on retirement of non-current assets (固定資産除却損)+ | LossOnReductionOfFixedAssets -- ^ Expense: Loss on tax purpose reduction entry of non-current assets (固定資産圧縮損)+ | AdditionalIncomeTaxesForPriorPeriods -- ^ Expense: Additional income taxes for prior periods (追徴法人税等)+ | RefundOfIncomeTaxes -- ^ Expense: Refund of income taxes (還付法人税等)+ | PurchaseRebates -- ^ Expense: Purchase rebates (仕入割戻)+ | WelfareExpenses -- ^ Expense: Welfare expenses (福利厚生費)+ | MaintenanceExpenses -- ^ Expense: Maintenance expenses (保守費)+ | StatutoryWelfareExpenses -- ^ Expense: Legal welfare expenses (法定福利費)+ | LandRentPaid -- ^ Expense: Rent expenses on land (支払地代)+ | InsuranceExpense -- ^ Expense: Insurance expenses (保険料)+ | RepairsExpense -- ^ Expense: Repair expenses (修繕費)+ | StorageExpenses -- ^ Expense: Storage costs (保管費)+ | MembershipFees -- ^ Expense: Membership fees (諸会費)+ | IncomeSummary -- ^ Asset: Income summary (損益)+ | SuspenseAccount -- ^ Asset: Suspense account (未決算)+ | ForeignExchangeGains -- ^ Revenue: Foreign exchange gains (為替差益)+ | ForeignExchangeLosses -- ^ Expense: Foreign exchange losses (為替差損)+ | ContraAccountForGuaranteeObligations -- ^ Asset: Contra account for guarantee obligations (保証債務見返)+ | GuaranteeObligations -- ^ Liability: Guarantee obligations (保証債務)+ | IncomeTaxesAdjustment -- ^ Expense: Income taxes - deferred (法人税等調整額)+ | BranchCurrentAccount -- ^ Asset: Branch current account (支店)+ | HeadOfficeCurrentAccount -- ^ Asset: Head office current account (本店)+ | NetIncomeAttributableToNCI -- ^ Expense: Profit attributable to non-controlling interests (非支配株主に帰属する当期純利益)+ | NetLossAttributableToNCI -- ^ Revenue: Loss attributable to non-controlling interests (非支配株主に帰属する当期純損失)+ | TradingSecurities -- ^ Asset: Trading securities (売買目的有価証券)+ | HeldToMaturityBonds -- ^ Asset: Held-to-maturity bonds (満期保有目的債券)+ | SubsidiaryStocks -- ^ Asset: Shares of subsidiaries (子会社株式)+ | AffiliateStocks -- ^ Asset: Shares of associates (関連会社株式)+ | AvailableForSaleSecurities -- ^ Asset: Available-for-sale securities (その他有価証券)+ | ConsumptionTaxRefundReceivable -- ^ Asset: Consumption tax refund receivable (未収還付消費税)+ | PropertyTaxPayable -- ^ Liability: Property tax payable (未払固定資産税)+ | DepositsReceivedFromOfficers -- ^ Liability: Deposits received from officers (役員預り金)+ | EntertainmentExpenses -- ^ Expense: Entertainment expenses (交際費)+ | MeetingExpenses -- ^ Expense: Meeting expenses (会議費)+ | NewspaperBooksExpenses -- ^ Expense: Newspapers and books (新聞図書費)+ | RawMaterials -- ^ Asset: Raw materials (原材料)+ | GoodsInTransit -- ^ Asset: Goods in transit (未着品)+ | SalesAllowances -- ^ Revenue: Sales allowances (売上値引)+ | PurchaseAllowances -- ^ Expense: Purchase allowances (仕入値引)+ | ReversalOfAllowanceForBonuses+ -- ^ Revenue: Reversal of allowance for bonuses (賞与引当金戻入)+ | DirectorsCompensations+ -- ^ Expense: Remuneration for directors (役員報酬)+ | AccountTitle -- ^ Wildcard (ワイルドカード — 任意の科目にマッチ。projWithBase 等の問い合わせ用で, 実 posting には使わない)+ deriving (Show, Ord, Eq, Enum, Generic, Bounded)++-- | Account title schemes covered by the table.+data Scheme = Jcci | Macro++-- | Wire code and, for a concrete account title, its metadata and aliases.+data Row+ = WildcardRow+ | ConcreteRow+ { rowCode :: Word16+ , rowScheme :: Scheme+ , rowSpec :: ~AccountSpec+ , rowSemantics :: ~AccountSemantics+ , rowJcciAliases :: ~[Text]+ }++-- | Look up the row for any account title.+row :: AccountTitles -> Row+row Cash = ConcreteRow+ { rowCode = 0x8000+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Cash"+ , asNameJa = "現金"+ , asLabelJa = "現金"+ , asDescription = "Asset: Cash (現金)"+ , asAliases = ["現金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["現金"]+ }+row Deposits = ConcreteRow+ { rowCode = 0x8001+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Savings deposits"+ , asNameJa = "普通預金"+ , asLabelJa = "普通預金"+ , asDescription = "Asset: Savings deposits (普通預金)"+ , asAliases = ["普通預金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["普通預金", "銀行預金", "普通預金○○銀行"]+ }+row CurrentDeposits = ConcreteRow+ { rowCode = 0x8002+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Current deposits"+ , asNameJa = "当座預金"+ , asLabelJa = "当座預金"+ , asDescription = "Asset: Current deposits (当座預金)"+ , asAliases = ["当座預金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["当座預金", "当座預金○○銀行"]+ }+row Securities = ConcreteRow+ { rowCode = 0x8003+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Securities"+ , asNameJa = "有価証券"+ , asLabelJa = "有価証券"+ , asDescription = "Asset: Securities (有価証券)"+ , asAliases = ["有価証券"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["有価証券"]+ }+row InvestmentSecurities = ConcreteRow+ { rowCode = 0x8004+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Investment securities"+ , asNameJa = "投資有価証券"+ , asLabelJa = "投資有価証券"+ , asDescription = "Asset: Investment securities (投資有価証券)"+ , asAliases = ["投資有価証券"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["投資有価証券"]+ }+row InvestmentInAssociate = ConcreteRow+ { rowCode = 0x8005+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Investment in associate"+ , asNameJa = "関係会社株式"+ , asLabelJa = "関係会社株式"+ , asDescription = "Asset: Investment in associate (関係会社株式). Carrying amount under the equity method (持分法適用投資勘定)."+ , asAliases = []+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row LongTermNationalBonds = ConcreteRow+ { rowCode = 0x8006+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Long-term national bonds"+ , asNameJa = "長期国債"+ , asLabelJa = "長期国債"+ , asDescription = "Asset: Long-term national bonds (長期国債)"+ , asAliases = ["長期国債"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row ShortTermNationalBonds = ConcreteRow+ { rowCode = 0x8007+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Short-term national bonds"+ , asNameJa = "短期国債"+ , asLabelJa = "短期国債"+ , asDescription = "Asset: Short-term national bonds (短期国債)"+ , asAliases = ["短期国債"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row Products = ConcreteRow+ { rowCode = 0x8008+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Products"+ , asNameJa = "商品"+ , asLabelJa = "商品"+ , asDescription = "Asset: Products (商品)。分記法用。3 分法 (仕入/売上/繰越商品) では 'MerchandiseInventory' を使う"+ , asAliases = ["商品"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["商品"]+ }+row Machinery = ConcreteRow+ { rowCode = 0x8009+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Machinery and equipment"+ , asNameJa = "機械装置"+ , asLabelJa = "機械装置"+ , asDescription = "Asset: Machinery and equipment (機械装置)"+ , asAliases = ["機械装置"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["機械装置", "機械"]+ }+row Building = ConcreteRow+ { rowCode = 0x800A+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Buildings"+ , asNameJa = "建物"+ , asLabelJa = "建物"+ , asDescription = "Asset: Buildings (建物)"+ , asAliases = ["建物"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["建物"]+ }+row Vehicle = ConcreteRow+ { rowCode = 0x800B+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Vehicles"+ , asNameJa = "車両運搬具"+ , asLabelJa = "車両運搬具"+ , asDescription = "Asset: Vehicles (車両運搬具)"+ , asAliases = ["車両運搬具"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["車両運搬具", "車両", "運搬具"]+ }+row StockInvestment = ConcreteRow+ { rowCode = 0x800C+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Stock investment"+ , asNameJa = "株式投資"+ , asLabelJa = "株式投資"+ , asDescription = "Asset: Stock investment (株式投資)"+ , asAliases = ["株式投資"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row EquipmentInvestment = ConcreteRow+ { rowCode = 0x800D+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Equipment investment"+ , asNameJa = "設備投資"+ , asLabelJa = "設備投資"+ , asDescription = "Asset: Equipment investment (設備投資)"+ , asAliases = ["設備投資"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row LongTermLoansReceivable = ConcreteRow+ { rowCode = 0x800E+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Long-term loans receivable"+ , asNameJa = "長期貸付金"+ , asLabelJa = "長期貸付金"+ , asDescription = "Asset: Long-term loans receivable (長期貸付金)"+ , asAliases = ["長期貸付金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["長期貸付金"]+ }+row AccountsReceivable = ConcreteRow+ { rowCode = 0x800F+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Accounts receivable"+ , asNameJa = "売掛金"+ , asLabelJa = "売掛金"+ , asDescription = "Asset: Accounts receivable (売掛金)"+ , asAliases = ["売掛金", "a/r", "accounts receivable"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["売掛金", "〇〇商店"]+ }+row ShortTermLoansReceivable = ConcreteRow+ { rowCode = 0x8010+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Short-term loans receivable"+ , asNameJa = "短期貸付金"+ , asLabelJa = "短期貸付金"+ , asDescription = "Asset: Short-term loans receivable (短期貸付金)"+ , asAliases = ["短期貸付金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["短期貸付金"]+ }+row ReserveDepositReceivable = ConcreteRow+ { rowCode = 0x8011+ , rowScheme = Macro+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Reserve deposits, asset side"+ , asNameJa = "準備預金, 資産側 — 市中銀行が中央銀行に置く準備預金。SNA/マクロ系"+ , asLabelJa = "準備預金"+ , asDescription = "Asset: Reserve deposits, asset side (準備預金, 資産側 — 市中銀行が中央銀行に置く準備預金。SNA/マクロ系)"+ , asAliases = ["準備預金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row Gold = ConcreteRow+ { rowCode = 0x8012+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Gold"+ , asNameJa = "金"+ , asLabelJa = "金"+ , asDescription = "Asset: Gold (金)"+ , asAliases = ["金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row GovernmentService = ConcreteRow+ { rowCode = 0x8013+ , rowScheme = Macro+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Government service"+ , asNameJa = "政府サービス。SNA/マクロ系"+ , asLabelJa = "政府サービス"+ , asDescription = "Asset: Government service (政府サービス。SNA/マクロ系)"+ , asAliases = ["政府サービス"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row CapitalStock = ConcreteRow+ { rowCode = 0x8014+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Equity+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Capital stock"+ , asNameJa = "資本金"+ , asLabelJa = "資本金"+ , asDescription = "Equity: Capital stock (資本金)"+ , asAliases = ["資本金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Equity+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["資本金"]+ }+row RetainedEarnings = ConcreteRow+ { rowCode = 0x8015+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Equity+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Retained earnings brought forward"+ , asNameJa = "繰越利益剰余金"+ , asLabelJa = "繰越利益剰余金"+ , asDescription = "Equity: Retained earnings brought forward (繰越利益剰余金)"+ , asAliases = ["繰越利益剰余金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Equity+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["繰越利益剰余金"]+ }+row LongTermLoansPayable = ConcreteRow+ { rowCode = 0x8016+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Long-term loans payable"+ , asNameJa = "長期借入金"+ , asLabelJa = "長期借入金"+ , asDescription = "Liability: Long-term loans payable (長期借入金)"+ , asAliases = ["長期借入金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["長期借入金"]+ }+row ShortTermLoansPayable = ConcreteRow+ { rowCode = 0x8017+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Short-term loans payable"+ , asNameJa = "短期借入金"+ , asLabelJa = "短期借入金"+ , asDescription = "Liability: Short-term loans payable (短期借入金)"+ , asAliases = ["短期借入金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["短期借入金"]+ }+row LoansPayable = ConcreteRow+ { rowCode = 0x8018+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Loans payable"+ , asNameJa = "借入金"+ , asLabelJa = "借入金"+ , asDescription = "Liability: Loans payable (借入金)"+ , asAliases = ["借入金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["借入金", "銀行借入金", "役員借入金"]+ }+row ReserveForDepreciation = ConcreteRow+ { rowCode = 0x8019+ , rowScheme = Macro+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Reserve for depreciation"+ , asNameJa = "減価償却引当金 — SNA/マクロ系の旧称。簿記の間接法には 'AccumulatedDepreciation' (減価償却累計額) を使う"+ , asLabelJa = "減価償却引当金"+ , asDescription = "Liability: Reserve for depreciation (減価償却引当金 — SNA/マクロ系の旧称。簿記の間接法には 'AccumulatedDepreciation' (減価償却累計額) を使う)"+ , asAliases = ["減価償却引当金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row DepositPayable = ConcreteRow+ { rowCode = 0x801A+ , rowScheme = Macro+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Deposits accepted"+ , asNameJa = "受入預金 — 銀行側の負債としての預金。SNA/マクロ系。従業員等からの預り金は 'DepositsReceived'"+ , asLabelJa = "受入預金"+ , asDescription = "Liability: Deposits accepted (受入預金 — 銀行側の負債としての預金。SNA/マクロ系。従業員等からの預り金は 'DepositsReceived')"+ , asAliases = ["受入預金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row LongTermNationalBondsPayable = ConcreteRow+ { rowCode = 0x801B+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Long-term national bonds payable"+ , asNameJa = "長期国債, 発行側"+ , asLabelJa = "長期国債"+ , asDescription = "Liability: Long-term national bonds payable (長期国債, 発行側)"+ , asAliases = ["長期国債"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row ShortTermNationalBondsPayable = ConcreteRow+ { rowCode = 0x801C+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Short-term national bonds payable"+ , asNameJa = "短期国債, 発行側"+ , asLabelJa = "短期国債"+ , asDescription = "Liability: Short-term national bonds payable (短期国債, 発行側)"+ , asAliases = ["短期国債"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row ReserveDepositPayable = ConcreteRow+ { rowCode = 0x801D+ , rowScheme = Macro+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Reserve deposits, liability side"+ , asNameJa = "準備預金, 負債側 — 中央銀行が受け入れる準備預金。SNA/マクロ系"+ , asLabelJa = "準備預金"+ , asDescription = "Liability: Reserve deposits, liability side (準備預金, 負債側 — 中央銀行が受け入れる準備預金。SNA/マクロ系)。※簿記の買掛金は 'AccountsPayable' を使うこと (旧 examples が本科目を買掛金の代用にしていた経緯あり)"+ , asAliases = ["準備預金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row CentralBankNotePayable = ConcreteRow+ { rowCode = 0x801E+ , rowScheme = Macro+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Central bank notes"+ , asNameJa = "発行銀行券。SNA/マクロ系"+ , asLabelJa = "発行銀行券"+ , asDescription = "Liability: Central bank notes (発行銀行券。SNA/マクロ系)"+ , asAliases = ["発行銀行券"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row Depreciation = ConcreteRow+ { rowCode = 0x801F+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Depreciation"+ , asNameJa = "減価償却費"+ , asLabelJa = "減価償却費"+ , asDescription = "Expense: Depreciation (減価償却費)"+ , asAliases = ["減価償却費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["減価償却費", "建物減価償却費", "備品減価償却費"]+ }+row AmortizationExpense = ConcreteRow+ { rowCode = 0x8020+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Amortization expense for intangibles"+ , asNameJa = "無形固定資産償却費 — 特許権・商標権・ソフトウェア等の無形資産の償却費。有形の 'Depreciation' (減価償却費) と区別される"+ , asLabelJa = "無形固定資産償却費"+ , asDescription = "Expense: Amortization expense for intangibles (無形固定資産償却費 — 特許権・商標権・ソフトウェア等の無形資産の償却費。有形の 'Depreciation' (減価償却費) と区別される)"+ , asAliases = []+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row SalesCost = ConcreteRow+ { rowCode = 0x8021+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Cost of sales"+ , asNameJa = "売上原価"+ , asLabelJa = "売上原価"+ , asDescription = "Expense: Cost of sales (売上原価)"+ , asAliases = ["売上原価", "cogs", "cost of sales"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["売上原価"]+ }+row BusinessTrip = ConcreteRow+ { rowCode = 0x8022+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Travel and transportation"+ , asNameJa = "旅費交通費"+ , asLabelJa = "旅費交通費"+ , asDescription = "Expense: Travel and transportation (旅費交通費)"+ , asAliases = ["旅費交通費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["旅費交通費", "旅費", "交通費"]+ }+row UtilitiesExpense = ConcreteRow+ { rowCode = 0x8024+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Utilities"+ , asNameJa = "水道光熱費"+ , asLabelJa = "水道光熱費"+ , asDescription = "Expense: Utilities (水道光熱費)"+ , asAliases = ["水道光熱費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["水道光熱費", "光熱水費"]+ }+row RentExpense = ConcreteRow+ { rowCode = 0x8025+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Rent"+ , asNameJa = "支払家賃"+ , asLabelJa = "支払家賃"+ , asDescription = "Expense: Rent (支払家賃)"+ , asAliases = ["支払家賃"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["支払家賃", "地代家賃", "支払賃借料", "支払不動産賃借料"]+ }+row AdvertisingExpense = ConcreteRow+ { rowCode = 0x8026+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Advertising"+ , asNameJa = "広告宣伝費"+ , asLabelJa = "広告宣伝費"+ , asDescription = "Expense: Advertising (広告宣伝費)"+ , asAliases = ["広告宣伝費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["広告宣伝費", "広告費", "広告料", "宣伝費"]+ }+row DeliveryExpenses = ConcreteRow+ { rowCode = 0x8027+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Delivery"+ , asNameJa = "発送費"+ , asLabelJa = "発送費"+ , asDescription = "Expense: Delivery (発送費)"+ , asAliases = ["発送費", "荷造運賃"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["発送費", "支払運賃", "発送運賃"]+ }+row SuppliesExpenses = ConcreteRow+ { rowCode = 0x8028+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Supplies expense"+ , asNameJa = "消耗品費"+ , asLabelJa = "消耗品費"+ , asDescription = "Expense: Supplies expense (消耗品費)"+ , asAliases = ["消耗品費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["消耗品費", "事務用消耗品費"]+ }+row MiscellaneousExpenses = ConcreteRow+ { rowCode = 0x8029+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Miscellaneous"+ , asNameJa = "雑費"+ , asLabelJa = "雑費"+ , asDescription = "Expense: Miscellaneous (雑費)"+ , asAliases = ["雑費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["雑費"]+ }+row WageExpenditure = ConcreteRow+ { rowCode = 0x802A+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Wages"+ , asNameJa = "給料"+ , asLabelJa = "給料"+ , asDescription = "Expense: Wages (給料)"+ , asAliases = ["給料"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["給料", "給料手当", "賃金給料"]+ }+row InterestExpense = ConcreteRow+ { rowCode = 0x802B+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Interest expense"+ , asNameJa = "支払利息"+ , asLabelJa = "支払利息"+ , asDescription = "Expense: Interest expense (支払利息)"+ , asAliases = ["支払利息"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["支払利息"]+ }+row TaxesExpense = ConcreteRow+ { rowCode = 0x802C+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Taxes"+ , asNameJa = "租税公課"+ , asLabelJa = "租税公課"+ , asDescription = "Expense: Taxes (租税公課)"+ , asAliases = ["租税公課"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["租税公課", "公租公課", "固定資産税", "印紙税"]+ }+row ConsumptionExpenditure = ConcreteRow+ { rowCode = 0x802D+ , rowScheme = Macro+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Consumption expenditure"+ , asNameJa = "消費支出。SNA/マクロ系"+ , asLabelJa = "消費支出"+ , asDescription = "Expense: Consumption expenditure (消費支出。SNA/マクロ系)"+ , asAliases = ["消費支出"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row SubsidyExpense = ConcreteRow+ { rowCode = 0x802E+ , rowScheme = Macro+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Subsidy expenditure"+ , asNameJa = "補助金支出。SNA/マクロ系"+ , asLabelJa = "補助金支出"+ , asDescription = "Expense: Subsidy expenditure (補助金支出。SNA/マクロ系)"+ , asAliases = ["補助金支出"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row CentralBankPaymentExpense = ConcreteRow+ { rowCode = 0x802F+ , rowScheme = Macro+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Payment to national treasury"+ , asNameJa = "国庫納付金支出。SNA/マクロ系"+ , asLabelJa = "国庫納付金支出"+ , asDescription = "Expense: Payment to national treasury (国庫納付金支出。SNA/マクロ系)"+ , asAliases = ["国庫納付金支出"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row Purchases = ConcreteRow+ { rowCode = 0x8030+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Purchases"+ , asNameJa = "仕入"+ , asLabelJa = "仕入"+ , asDescription = "Expense: Purchases (仕入)"+ , asAliases = ["仕入"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["仕入"]+ }+row NetIncome = ConcreteRow+ { rowCode = 0x8031+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = NoClose+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Net income"+ , asNameJa = "当期純利益 — 決算振替用。借方側に立つため Expense 区分"+ , asLabelJa = "当期純利益"+ , asDescription = "Expense: Net income (当期純利益 — 決算振替用。借方側に立つため Expense 区分)"+ , asAliases = ["当期純利益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [PeriodResult]+ , asemPostingCapability = EngineGeneratedOnly+ , asemDivisionSemantics = DirectionEncoding Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = DerivedPresentation+ }+ , rowJcciAliases = []+ }+row ValueAdded = ConcreteRow+ { rowCode = 0x8032+ , rowScheme = Macro+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Value added"+ , asNameJa = "付加価値。SNA/マクロ系"+ , asLabelJa = "付加価値"+ , asDescription = "Revenue: Value added (付加価値。SNA/マクロ系)"+ , asAliases = ["付加価値"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row SubsidyIncome = ConcreteRow+ { rowCode = 0x8033+ , rowScheme = Macro+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Subsidy income"+ , asNameJa = "補助金収入。SNA/マクロ系"+ , asLabelJa = "補助金収入"+ , asDescription = "Revenue: Subsidy income (補助金収入。SNA/マクロ系)"+ , asAliases = ["補助金収入"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row NationalBondInterestEarned = ConcreteRow+ { rowCode = 0x8034+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "National bond interest earned"+ , asNameJa = "国債利息収入"+ , asLabelJa = "国債利息収入"+ , asDescription = "Revenue: National bond interest earned (国債利息収入)"+ , asAliases = ["国債利息収入"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row DepositInterestEarned = ConcreteRow+ { rowCode = 0x8035+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Deposit interest earned"+ , asNameJa = "預金利息収入"+ , asLabelJa = "預金利息収入"+ , asDescription = "Revenue: Deposit interest earned (預金利息収入)"+ , asAliases = ["預金利息収入"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row GrossProfit = ConcreteRow+ { rowCode = 0x8036+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Gross profit"+ , asNameJa = "売上総利益 — 決算振替用"+ , asLabelJa = "売上総利益"+ , asDescription = "Revenue: Gross profit (売上総利益 — 決算振替用)"+ , asAliases = ["売上総利益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [ReportingSubtotal]+ , asemPostingCapability = EngineGeneratedOnly+ , asemDivisionSemantics = DirectionEncoding Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = DerivedPresentation+ }+ , rowJcciAliases = []+ }+row OrdinaryProfit = ConcreteRow+ { rowCode = 0x8037+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Ordinary profit"+ , asNameJa = "経常利益 — 決算振替用"+ , asLabelJa = "経常利益"+ , asDescription = "Revenue: Ordinary profit (経常利益 — 決算振替用)"+ , asAliases = ["経常利益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [ReportingSubtotal]+ , asemPostingCapability = EngineGeneratedOnly+ , asemDivisionSemantics = DirectionEncoding Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = DerivedPresentation+ }+ , rowJcciAliases = []+ }+row InterestEarned = ConcreteRow+ { rowCode = 0x8038+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Interest earned"+ , asNameJa = "受取利息"+ , asLabelJa = "受取利息"+ , asDescription = "Revenue: Interest earned (受取利息)"+ , asAliases = ["受取利息"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["受取利息"]+ }+row ReceiptFee = ConcreteRow+ { rowCode = 0x8039+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Receipt fee"+ , asNameJa = "受取手数料。支払側は 'PaymentFees'"+ , asLabelJa = "受取手数料"+ , asDescription = "Revenue: Receipt fee (受取手数料。支払側は 'PaymentFees')"+ , asAliases = ["受取手数料"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["受取手数料"]+ }+row RentalIncome = ConcreteRow+ { rowCode = 0x803A+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Rental income"+ , asNameJa = "受取家賃"+ , asLabelJa = "受取家賃"+ , asDescription = "Revenue: Rental income (受取家賃)"+ , asAliases = ["受取家賃"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["受取家賃"]+ }+row WageEarned = ConcreteRow+ { rowCode = 0x803B+ , rowScheme = Macro+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Wage income"+ , asNameJa = "賃金収入。SNA/マクロ系"+ , asLabelJa = "賃金収入"+ , asDescription = "Revenue: Wage income (賃金収入。SNA/マクロ系)"+ , asAliases = ["賃金収入"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row TaxesRevenue = ConcreteRow+ { rowCode = 0x803C+ , rowScheme = Macro+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Tax revenue"+ , asNameJa = "租税収入。SNA/マクロ系"+ , asLabelJa = "租税収入"+ , asDescription = "Revenue: Tax revenue (租税収入。SNA/マクロ系)"+ , asAliases = ["租税収入"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row CentralBankPaymentIncome = ConcreteRow+ { rowCode = 0x803D+ , rowScheme = Macro+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Central bank payment received"+ , asNameJa = "国庫納付金収入。SNA/マクロ系"+ , asLabelJa = "国庫納付金収入"+ , asDescription = "Revenue: Central bank payment received (国庫納付金収入。SNA/マクロ系)"+ , asAliases = ["国庫納付金収入"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row Sales = ConcreteRow+ { rowCode = 0x803E+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Sales"+ , asNameJa = "売上"+ , asLabelJa = "売上"+ , asDescription = "Revenue: Sales (売上)"+ , asAliases = ["売上"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["売上"]+ }+row EquityInEarningsOfInvestee = ConcreteRow+ { rowCode = 0x803F+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Equity in earnings of investee"+ , asNameJa = "持分法による投資利益"+ , asLabelJa = "持分法による投資利益"+ , asDescription = "Revenue: Equity in earnings of investee (持分法による投資利益). Recognized under the equity method."+ , asAliases = []+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = ConsolidationOnly+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = ContextualPresentation+ }+ , rowJcciAliases = []+ }+row NetLoss = ConcreteRow+ { rowCode = 0x8040+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = NoClose+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Net loss"+ , asNameJa = "当期純損失 — 決算振替用。貸方側に立つため Revenue 区分"+ , asLabelJa = "当期純損失"+ , asDescription = "Revenue: Net loss (当期純損失 — 決算振替用。貸方側に立つため Revenue 区分)"+ , asAliases = ["当期純損失"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [PeriodResult]+ , asemPostingCapability = EngineGeneratedOnly+ , asemDivisionSemantics = DirectionEncoding Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = DerivedPresentation+ }+ , rowJcciAliases = []+ }+row PettyCash = ConcreteRow+ { rowCode = 0x8041+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Petty cash"+ , asNameJa = "小口現金"+ , asLabelJa = "小口現金"+ , asDescription = "Asset: Petty cash (小口現金)"+ , asAliases = ["小口現金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["小口現金"]+ }+row NotesReceivable = ConcreteRow+ { rowCode = 0x8042+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Notes receivable"+ , asNameJa = "受取手形"+ , asLabelJa = "受取手形"+ , asDescription = "Asset: Notes receivable (受取手形)"+ , asAliases = ["受取手形"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["受取手形"]+ }+row ElectronicallyRecordedReceivable = ConcreteRow+ { rowCode = 0x8043+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Electronically recorded monetary claims"+ , asNameJa = "電子記録債権"+ , asLabelJa = "電子記録債権"+ , asDescription = "Asset: Electronically recorded monetary claims (電子記録債権)"+ , asAliases = ["電子記録債権"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["電子記録債権"]+ }+row CreditCardReceivable = ConcreteRow+ { rowCode = 0x8044+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Credit card receivable"+ , asNameJa = "クレジット売掛金"+ , asLabelJa = "クレジット売掛金"+ , asDescription = "Asset: Credit card receivable (クレジット売掛金)"+ , asAliases = ["クレジット売掛金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["クレジット売掛金"]+ }+row NotesLoansReceivable = ConcreteRow+ { rowCode = 0x8045+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Loans receivable on notes"+ , asNameJa = "手形貸付金"+ , asLabelJa = "手形貸付金"+ , asDescription = "Asset: Loans receivable on notes (手形貸付金)"+ , asAliases = ["手形貸付金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["貸付金", "手形貸付金"]+ }+row MerchandiseInventory = ConcreteRow+ { rowCode = 0x8046+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Merchandise inventory"+ , asNameJa = "繰越商品"+ , asLabelJa = "繰越商品"+ , asDescription = "Asset: Merchandise inventory (繰越商品). Use under the periodic/3-account method (3 分法: Purchases/Sales/MerchandiseInventory). For 分記法, which records the cost of the goods and the gain on sales at each sale, use 'Products' instead."+ , asAliases = ["繰越商品"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["繰越商品"]+ }+row AdvancesPaid = ConcreteRow+ { rowCode = 0x8047+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Advances paid"+ , asNameJa = "前払金"+ , asLabelJa = "前払金"+ , asDescription = "Asset: Advances paid (前払金)"+ , asAliases = ["前払金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["前払金", "前渡金"]+ }+row PrepaidExpenses = ConcreteRow+ { rowCode = 0x8048+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Prepaid expenses"+ , asNameJa = "前払費用"+ , asLabelJa = "前払費用"+ , asDescription = "Asset: Prepaid expenses (前払費用), deferral account (経過勘定)"+ , asAliases = ["前払費用"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["前払費用", "前払保険料"]+ }+row AccruedRevenue = ConcreteRow+ { rowCode = 0x8049+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Accrued revenue"+ , asNameJa = "未収収益"+ , asLabelJa = "未収収益"+ , asDescription = "Asset: Accrued revenue (未収収益), accrual account (経過勘定)"+ , asAliases = ["未収収益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["未収収益", "未収家賃"]+ }+row OtherReceivables = ConcreteRow+ { rowCode = 0x804A+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Other receivables"+ , asNameJa = "未収入金"+ , asLabelJa = "未収入金"+ , asDescription = "Asset: Other receivables (未収入金)"+ , asAliases = ["未収入金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["未収入金", "未収金"]+ }+row PaymentsOnBehalf = ConcreteRow+ { rowCode = 0x804B+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Payments made on behalf"+ , asNameJa = "立替金"+ , asLabelJa = "立替金"+ , asDescription = "Asset: Payments made on behalf (立替金)"+ , asAliases = ["立替金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["立替金", "従業員立替金"]+ }+row SuspensePayments = ConcreteRow+ { rowCode = 0x804C+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Suspense payments"+ , asNameJa = "仮払金"+ , asLabelJa = "仮払金"+ , asDescription = "Asset: Suspense payments (仮払金)"+ , asAliases = ["仮払金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [SuspenseOrClearingAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = BookkeepingControlClass Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = ContextualPresentation+ }+ , rowJcciAliases = ["仮払金"]+ }+row ConsumptionTaxPaid = ConcreteRow+ { rowCode = 0x804D+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Consumption tax paid"+ , asNameJa = "仮払消費税"+ , asLabelJa = "仮払消費税"+ , asDescription = "Asset: Consumption tax paid (仮払消費税)"+ , asAliases = ["仮払消費税"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["仮払金", "仮払消費税"]+ }+row PrepaidCorporateIncomeTaxes = ConcreteRow+ { rowCode = 0x804E+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Prepaid corporate income taxes"+ , asNameJa = "仮払法人税等"+ , asLabelJa = "仮払法人税等"+ , asDescription = "Asset: Prepaid corporate income taxes (仮払法人税等)"+ , asAliases = ["仮払法人税等"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["仮払金", "仮払法人税等"]+ }+row Land = ConcreteRow+ { rowCode = 0x804F+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Land"+ , asNameJa = "土地"+ , asLabelJa = "土地"+ , asDescription = "Asset: Land (土地)"+ , asAliases = ["土地"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["土地"]+ }+row Fixtures = ConcreteRow+ { rowCode = 0x8050+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Fixtures and equipment"+ , asNameJa = "備品"+ , asLabelJa = "備品"+ , asDescription = "Asset: Fixtures and equipment (備品)"+ , asAliases = ["備品", "器具備品"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["備品"]+ }+row Patent = ConcreteRow+ { rowCode = 0x8051+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Patent"+ , asNameJa = "特許権"+ , asLabelJa = "特許権"+ , asDescription = "Asset: Patent (特許権)"+ , asAliases = ["特許権"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["特許権"]+ }+row Trademark = ConcreteRow+ { rowCode = 0x8052+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Trademark"+ , asNameJa = "商標権"+ , asLabelJa = "商標権"+ , asDescription = "Asset: Trademark (商標権)"+ , asAliases = ["商標権"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["商標権"]+ }+row Software = ConcreteRow+ { rowCode = 0x8053+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Software"+ , asNameJa = "ソフトウェア"+ , asLabelJa = "ソフトウェア"+ , asDescription = "Asset: Software (ソフトウェア)"+ , asAliases = ["ソフトウェア"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["ソフトウェア"]+ }+row CashOverShort = ConcreteRow+ { rowCode = 0x8054+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Cash over and short"+ , asNameJa = "現金過不足"+ , asLabelJa = "現金過不足"+ , asDescription = "Asset: Cash over and short (現金過不足), a temporary/suspense account cleared at closing to MiscellaneousIncome/MiscellaneousLoss"+ , asAliases = ["現金過不足"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [SuspenseOrClearingAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = BookkeepingControlClass Assets+ , asemHomeSideSemantics = ContextDependentHomeSide+ , asemReportingEligibility = NotPresented+ }+ , rowJcciAliases = ["現金過不足"]+ }+row AccountsPayable = ConcreteRow+ { rowCode = 0x8055+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Accounts payable"+ , asNameJa = "買掛金"+ , asLabelJa = "買掛金"+ , asDescription = "Liability: Accounts payable (買掛金)"+ , asAliases = ["買掛金", "a/p", "accounts payable"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["〇〇商店", "買掛金"]+ }+row NotesPayable = ConcreteRow+ { rowCode = 0x8056+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Notes payable"+ , asNameJa = "支払手形"+ , asLabelJa = "支払手形"+ , asDescription = "Liability: Notes payable (支払手形)"+ , asAliases = ["支払手形"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["支払手形"]+ }+row ElectronicallyRecordedObligations = ConcreteRow+ { rowCode = 0x8057+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Electronically recorded monetary obligations"+ , asNameJa = "電子記録債務"+ , asLabelJa = "電子記録債務"+ , asDescription = "Liability: Electronically recorded monetary obligations (電子記録債務)"+ , asAliases = ["電子記録債務"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["電子記録債務"]+ }+row NotesLoansPayable = ConcreteRow+ { rowCode = 0x8058+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Loans payable on notes"+ , asNameJa = "手形借入金"+ , asLabelJa = "手形借入金"+ , asDescription = "Liability: Loans payable on notes (手形借入金)"+ , asAliases = ["手形借入金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["借入金", "手形借入金"]+ }+row BankOverdraft = ConcreteRow+ { rowCode = 0x8059+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Bank overdraft"+ , asNameJa = "当座借越"+ , asLabelJa = "当座借越"+ , asDescription = "Liability: Bank overdraft (当座借越)"+ , asAliases = ["当座借越"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["借入金", "当座借越"]+ }+row AdvancesReceived = ConcreteRow+ { rowCode = 0x805A+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Advances received"+ , asNameJa = "前受金"+ , asLabelJa = "前受金"+ , asDescription = "Liability: Advances received (前受金)"+ , asAliases = ["前受金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["前受金", "契約負債"]+ }+row UnearnedRevenue = ConcreteRow+ { rowCode = 0x805B+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Unearned revenue"+ , asNameJa = "前受収益"+ , asLabelJa = "前受収益"+ , asDescription = "Liability: Unearned revenue (前受収益), deferral account (経過勘定)"+ , asAliases = ["前受収益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["前受収益", "前受地代"]+ }+row AccruedExpenses = ConcreteRow+ { rowCode = 0x805C+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Accrued expenses"+ , asNameJa = "未払費用"+ , asLabelJa = "未払費用"+ , asDescription = "Liability: Accrued expenses (未払費用), accrual account (経過勘定)"+ , asAliases = ["未払費用"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["未払費用", "未払利息"]+ }+row OtherPayables = ConcreteRow+ { rowCode = 0x805D+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Other payables"+ , asNameJa = "未払金"+ , asLabelJa = "未払金"+ , asDescription = "Liability: Other payables (未払金)"+ , asAliases = ["未払金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["未払金"]+ }+row DepositsReceived = ConcreteRow+ { rowCode = 0x805E+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Deposits received"+ , asNameJa = "預り金"+ , asLabelJa = "預り金"+ , asDescription = "Liability: Deposits received (預り金)"+ , asAliases = ["預り金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["預り金", "従業員預り金", "所得税預り金", "住民税預り金", "社会保険料預り金"]+ }+row SuspenseReceipts = ConcreteRow+ { rowCode = 0x805F+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Suspense receipts"+ , asNameJa = "仮受金"+ , asLabelJa = "仮受金"+ , asDescription = "Liability: Suspense receipts (仮受金)"+ , asAliases = ["仮受金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [SuspenseOrClearingAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = BookkeepingControlClass Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = ContextualPresentation+ }+ , rowJcciAliases = ["仮受金"]+ }+row ConsumptionTaxReceived = ConcreteRow+ { rowCode = 0x8060+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Consumption tax received"+ , asNameJa = "仮受消費税"+ , asLabelJa = "仮受消費税"+ , asDescription = "Liability: Consumption tax received (仮受消費税)"+ , asAliases = ["仮受消費税"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["仮受金", "仮受消費税"]+ }+row AccruedConsumptionTax = ConcreteRow+ { rowCode = 0x8061+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Accrued (unpaid) consumption tax"+ , asNameJa = "未払消費税"+ , asLabelJa = "未払消費税"+ , asDescription = "Liability: Accrued (unpaid) consumption tax (未払消費税)"+ , asAliases = ["未払消費税"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["未払金", "未払消費税"]+ }+row AccruedCorporateIncomeTaxes = ConcreteRow+ { rowCode = 0x8062+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Accrued (unpaid) corporate income taxes"+ , asNameJa = "未払法人税等"+ , asLabelJa = "未払法人税等"+ , asDescription = "Liability: Accrued (unpaid) corporate income taxes (未払法人税等)"+ , asAliases = ["未払法人税等"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["未払法人税等"]+ }+row UnpaidDividends = ConcreteRow+ { rowCode = 0x8063+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Unpaid dividends"+ , asNameJa = "未払配当金"+ , asLabelJa = "未払配当金"+ , asDescription = "Liability: Unpaid dividends (未払配当金)"+ , asAliases = ["未払配当金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["未払配当金", "未払株主配当金"]+ }+row AllowanceForDoubtfulAccounts = ConcreteRow+ { rowCode = 0x8064+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = True+ , asFixedCurrent = Current+ , asNameEn = "Allowance for doubtful accounts"+ , asNameJa = "貸倒引当金"+ , asLabelJa = "貸倒引当金"+ , asDescription = "Asset (contra): Allowance for doubtful accounts (貸倒引当金), a credit-balance valuation account (評価勘定) deducted from receivables. Home side is Credit because it is a contra asset (isContra); values stay non-negative and the Hat/Not structure is intact. B/S deduction (net) presentation is the ExchangeAlgebra.IO.Output module's job."+ , asAliases = ["貸倒引当金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount, ContraAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["貸倒引当金"]+ }+row AccumulatedDepreciation = ConcreteRow+ { rowCode = 0x8065+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = True+ , asFixedCurrent = Fixed+ , asNameEn = "Accumulated depreciation"+ , asNameJa = "減価償却累計額"+ , asLabelJa = "減価償却累計額"+ , asDescription = "Asset (contra): Accumulated depreciation (減価償却累計額), a credit-balance valuation account (評価勘定) under the indirect method (間接法), deducted from the related depreciable assets. Home side is Credit because it is a contra asset (isContra). This is the canonical bookkeeping account for accumulated depreciation; the existing 'ReserveForDepreciation' is retained as the legacy SNA/macro-accounting name."+ , asAliases = ["減価償却累計額"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount, ContraAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["建物減価償却累計額", "減価償却累計額", "備品減価償却累計額", "車両運搬具減価償却累計額", "車両減価償却累計額"]+ }+row LegalRetainedEarnings = ConcreteRow+ { rowCode = 0x8066+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Equity+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Legal (appropriated) retained earnings reserve"+ , asNameJa = "利益準備金"+ , asLabelJa = "利益準備金"+ , asDescription = "Equity: Legal (appropriated) retained earnings reserve (利益準備金)"+ , asAliases = ["利益準備金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Equity+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["利益準備金"]+ }+row CumulativeTranslationAdjustment = ConcreteRow+ { rowCode = 0x8067+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Equity+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Cumulative translation adjustment"+ , asNameJa = "為替換算調整勘定; 在外子会社等の外貨建財務諸表の換算差額を計上する OCI/資本の部の項目"+ , asLabelJa = "為替換算調整勘定"+ , asDescription = "Equity: Cumulative translation adjustment (為替換算調整勘定; 在外子会社等の外貨建財務諸表の換算差額を計上する OCI/資本の部の項目)"+ , asAliases = []+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = ConsolidationOnly+ , asemDivisionSemantics = StatementDivision Equity+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = ContextualPresentation+ }+ , rowJcciAliases = []+ }+row ProvisionForDoubtfulAccounts = ConcreteRow+ { rowCode = 0x8068+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Provision for doubtful accounts"+ , asNameJa = "貸倒引当金繰入"+ , asLabelJa = "貸倒引当金繰入"+ , asDescription = "Expense: Provision for doubtful accounts (貸倒引当金繰入)"+ , asAliases = ["貸倒引当金繰入"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["貸倒引当金繰入", "貸倒引当金繰入額"]+ }+row BadDebtLoss = ConcreteRow+ { rowCode = 0x8069+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Bad debt loss"+ , asNameJa = "貸倒損失"+ , asLabelJa = "貸倒損失"+ , asDescription = "Expense: Bad debt loss (貸倒損失)"+ , asAliases = ["貸倒損失"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["貸倒損失"]+ }+row LossOnSalesOfFixedAssets = ConcreteRow+ { rowCode = 0x806A+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Loss on sales of fixed assets"+ , asNameJa = "固定資産売却損"+ , asLabelJa = "固定資産売却損"+ , asDescription = "Expense: Loss on sales of fixed assets (固定資産売却損)"+ , asAliases = ["固定資産売却損"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["固定資産売却損", "備品売却損", "建物売却損", "土地売却損"]+ }+row LossOnSalesOfNotesReceivable = ConcreteRow+ { rowCode = 0x806B+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Loss on sales of notes receivable"+ , asNameJa = "手形売却損"+ , asLabelJa = "手形売却損"+ , asDescription = "Expense: Loss on sales of notes receivable (手形売却損)"+ , asAliases = ["手形売却損"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["手形売却損"]+ }+row PaymentFees = ConcreteRow+ { rowCode = 0x806C+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Payment fees / fees paid"+ , asNameJa = "支払手数料"+ , asLabelJa = "支払手数料"+ , asDescription = "Expense: Payment fees / fees paid (支払手数料), the debit counterpart of 'ReceiptFee'"+ , asAliases = ["支払手数料"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["支払手数料", "販売手数料"]+ }+row MiscellaneousLoss = ConcreteRow+ { rowCode = 0x806D+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Miscellaneous loss"+ , asNameJa = "雑損"+ , asLabelJa = "雑損"+ , asDescription = "Expense: Miscellaneous loss (雑損)"+ , asAliases = ["雑損"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["雑損", "雑損失"]+ }+row CorporateIncomeTaxes = ConcreteRow+ { rowCode = 0x806E+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Corporate income taxes"+ , asNameJa = "法人税等"+ , asLabelJa = "法人税等"+ , asDescription = "Expense: Corporate income taxes (法人税等)"+ , asAliases = ["法人税等"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["法人税、住民税及び事業税", "法人税等"]+ }+row CommunicationExpenses = ConcreteRow+ { rowCode = 0x806F+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Communication expenses"+ , asNameJa = "通信費"+ , asLabelJa = "通信費"+ , asDescription = "Expense: Communication expenses (通信費)"+ , asAliases = ["通信費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["通信費"]+ }+row GainOnSalesOfFixedAssets = ConcreteRow+ { rowCode = 0x8070+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Gain on sales of fixed assets"+ , asNameJa = "固定資産売却益"+ , asLabelJa = "固定資産売却益"+ , asDescription = "Revenue: Gain on sales of fixed assets (固定資産売却益)"+ , asAliases = ["固定資産売却益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["固定資産売却益", "備品売却益", "土地売却益", "建物売却益"]+ }+row RecoveryOfBadDebts = ConcreteRow+ { rowCode = 0x8071+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Recovery of bad debts written off"+ , asNameJa = "償却債権取立益"+ , asLabelJa = "償却債権取立益"+ , asDescription = "Revenue: Recovery of bad debts written off (償却債権取立益)"+ , asAliases = ["償却債権取立益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["償却債権取立益"]+ }+row MiscellaneousIncome = ConcreteRow+ { rowCode = 0x8072+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Miscellaneous income"+ , asNameJa = "雑益"+ , asLabelJa = "雑益"+ , asDescription = "Revenue: Miscellaneous income (雑益)"+ , asAliases = ["雑益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["雑益", "雑収入", "雑収益"]+ }+row ReversalOfAllowanceForDoubtfulAccounts = ConcreteRow+ { rowCode = 0x8073+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Reversal of allowance for doubtful accounts"+ , asNameJa = "貸倒引当金戻入"+ , asLabelJa = "貸倒引当金戻入"+ , asDescription = "Revenue: Reversal of allowance for doubtful accounts (貸倒引当金戻入). Credit counterpart used by the 差額補充法/洗替法 when the estimated allowance is smaller than the existing balance (the excess of 'AllowanceForDoubtfulAccounts' is released)."+ , asAliases = ["貸倒引当金戻入"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["貸倒引当金戻入", "貸倒引当金戻入益"]+ }+row TimeDeposits = ConcreteRow+ { rowCode = 0x8074+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Time deposits"+ , asNameJa = "定期預金"+ , asLabelJa = "定期預金"+ , asDescription = "Asset: Time deposits (定期預金)"+ , asAliases = ["定期預金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["銀行預金", "定期預金", "定期預金○○銀行"]+ }+row LoansReceivable = ConcreteRow+ { rowCode = 0x8075+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Loans receivable"+ , asNameJa = "貸付金"+ , asLabelJa = "貸付金"+ , asDescription = "Asset: Loans receivable (貸付金)"+ , asAliases = ["貸付金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["貸付金", "従業員貸付金", "役員貸付金"]+ }+row GiftCertificatesReceived = ConcreteRow+ { rowCode = 0x8076+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Gift certificates received"+ , asNameJa = "受取商品券"+ , asLabelJa = "受取商品券"+ , asDescription = "Asset: Gift certificates received (受取商品券)"+ , asAliases = ["受取商品券"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["受取商品券"]+ }+row SecurityDepositsPaid = ConcreteRow+ { rowCode = 0x8077+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Guarantee deposits"+ , asNameJa = "差入保証金"+ , asLabelJa = "差入保証金"+ , asDescription = "Asset: Guarantee deposits (差入保証金)"+ , asAliases = ["差入保証金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["差入保証金"]+ }+row SuppliesOnHand = ConcreteRow+ { rowCode = 0x8078+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Supplies on hand"+ , asNameJa = "貯蔵品"+ , asLabelJa = "貯蔵品"+ , asDescription = "Asset: Supplies on hand (貯蔵品)"+ , asAliases = ["貯蔵品"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["貯蔵品"]+ }+row ContractAssets = ConcreteRow+ { rowCode = 0x8079+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Contract assets"+ , asNameJa = "契約資産"+ , asLabelJa = "契約資産"+ , asDescription = "Asset: Contract assets (契約資産)"+ , asAliases = ["契約資産"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["契約資産"]+ }+row IncomeTaxesRefundReceivable = ConcreteRow+ { rowCode = 0x807A+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Income taxes refund receivable"+ , asNameJa = "未収還付法人税等"+ , asLabelJa = "未収還付法人税等"+ , asDescription = "Asset: Income taxes refund receivable (未収還付法人税等)"+ , asAliases = ["未収還付法人税等"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["未収還付法人税等"]+ }+row WorkInProcess = ConcreteRow+ { rowCode = 0x807B+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Work in process"+ , asNameJa = "仕掛品"+ , asLabelJa = "仕掛品"+ , asDescription = "Asset: Work in process (仕掛品)"+ , asAliases = ["仕掛品"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["仕掛品"]+ }+row DeferredTaxAssets = ConcreteRow+ { rowCode = 0x807C+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Deferred tax assets"+ , asNameJa = "繰延税金資産"+ , asLabelJa = "繰延税金資産"+ , asDescription = "Asset: Deferred tax assets (繰延税金資産)"+ , asAliases = ["繰延税金資産"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["繰延税金資産"]+ }+row LeasedAssets = ConcreteRow+ { rowCode = 0x807D+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Leased assets"+ , asNameJa = "リース資産"+ , asLabelJa = "リース資産"+ , asDescription = "Asset: Leased assets (リース資産)"+ , asAliases = ["リース資産"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["リース資産"]+ }+row ToolsAndInstruments = ConcreteRow+ { rowCode = 0x807E+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Tools and instruments"+ , asNameJa = "工具器具"+ , asLabelJa = "工具器具"+ , asDescription = "Asset: Tools and instruments (工具器具)"+ , asAliases = ["工具器具"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["工具器具"]+ }+row ConstructionInProgress = ConcreteRow+ { rowCode = 0x807F+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Construction in progress"+ , asNameJa = "建設仮勘定"+ , asLabelJa = "建設仮勘定"+ , asDescription = "Asset: Construction in progress (建設仮勘定)"+ , asAliases = ["建設仮勘定"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["建設仮勘定", "建設仮", "建設前渡金", "建設仮払金"]+ }+row Goodwill = ConcreteRow+ { rowCode = 0x8080+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Goodwill"+ , asNameJa = "のれん"+ , asLabelJa = "のれん"+ , asDescription = "Asset: Goodwill (のれん)"+ , asAliases = ["のれん"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["のれん"]+ }+row SoftwareInProgress = ConcreteRow+ { rowCode = 0x8081+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Software in progress"+ , asNameJa = "ソフトウェア仮勘定"+ , asLabelJa = "ソフトウェア仮勘定"+ , asDescription = "Asset: Software in progress (ソフトウェア仮勘定)"+ , asAliases = ["ソフトウェア仮勘定"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["ソフトウェア仮勘定"]+ }+row LongTermPrepaidExpenses = ConcreteRow+ { rowCode = 0x8082+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Long-term prepaid expenses"+ , asNameJa = "長期前払費用"+ , asLabelJa = "長期前払費用"+ , asDescription = "Asset: Long-term prepaid expenses (長期前払費用)"+ , asAliases = ["長期前払費用"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["長期前払費用"]+ }+row DishonoredNotesReceivable = ConcreteRow+ { rowCode = 0x8083+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Dishonored notes receivable"+ , asNameJa = "不渡手形"+ , asLabelJa = "不渡手形"+ , asDescription = "Asset: Dishonored notes receivable (不渡手形)"+ , asAliases = ["不渡手形"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["不渡手形"]+ }+row PrepaidPensionCost = ConcreteRow+ { rowCode = 0x8084+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Prepaid pension costs"+ , asNameJa = "前払年金費用"+ , asLabelJa = "前払年金費用"+ , asDescription = "Asset: Prepaid pension costs (前払年金費用)"+ , asAliases = ["前払年金費用"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["前払年金費用"]+ }+row NetDefinedBenefitAsset = ConcreteRow+ { rowCode = 0x8085+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Retirement benefit asset"+ , asNameJa = "退職給付に係る資産"+ , asLabelJa = "退職給付に係る資産"+ , asDescription = "Asset: Retirement benefit asset (退職給付に係る資産)"+ , asAliases = ["退職給付に係る資産"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["退職給付に係る資産"]+ }+row DepositsInSpecialAccounts = ConcreteRow+ { rowCode = 0x8086+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Deposits in special accounts"+ , asNameJa = "別段預金"+ , asLabelJa = "別段預金"+ , asDescription = "Asset: Deposits in special accounts (別段預金)"+ , asAliases = ["別段預金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["銀行預金", "別段預金"]+ }+row Structures = ConcreteRow+ { rowCode = 0x8087+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Structures"+ , asNameJa = "構築物"+ , asLabelJa = "構築物"+ , asDescription = "Asset: Structures (構築物)"+ , asAliases = ["構築物"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["構築物"]+ }+row LeaseholdRights = ConcreteRow+ { rowCode = 0x8088+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Leasehold interests in land"+ , asNameJa = "借地権"+ , asLabelJa = "借地権"+ , asDescription = "Asset: Leasehold interests in land (借地権)"+ , asAliases = ["借地権"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["借地権"]+ }+row NonOperatingNotesReceivable = ConcreteRow+ { rowCode = 0x8089+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Non-operating notes receivable"+ , asNameJa = "営業外受取手形"+ , asLabelJa = "営業外受取手形"+ , asDescription = "Asset: Non-operating notes receivable (営業外受取手形)"+ , asAliases = ["営業外受取手形"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["営業外受取手形"]+ }+row NonOperatingElectronicallyRecordedReceivable = ConcreteRow+ { rowCode = 0x808A+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Electronically recorded monetary claims - non-operating"+ , asNameJa = "営業外電子記録債権"+ , asLabelJa = "営業外電子記録債権"+ , asDescription = "Asset: Electronically recorded monetary claims - non-operating (営業外電子記録債権)"+ , asAliases = ["営業外電子記録債権"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["営業外電子記録債権"]+ }+row RefundLiabilities = ConcreteRow+ { rowCode = 0x808B+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Refund liabilities"+ , asNameJa = "返金負債"+ , asLabelJa = "返金負債"+ , asDescription = "Liability: Refund liabilities (返金負債)"+ , asAliases = ["返金負債"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["返金負債"]+ }+row NonOperatingNotesPayable = ConcreteRow+ { rowCode = 0x808C+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Non-operating notes payable"+ , asNameJa = "営業外支払手形"+ , asLabelJa = "営業外支払手形"+ , asDescription = "Liability: Non-operating notes payable (営業外支払手形)"+ , asAliases = ["営業外支払手形"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["営業外支払手形"]+ }+row NonOperatingElectronicallyRecordedObligations = ConcreteRow+ { rowCode = 0x808D+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Electronically recorded obligations - non-operating"+ , asNameJa = "営業外電子記録債務"+ , asLabelJa = "営業外電子記録債務"+ , asDescription = "Liability: Electronically recorded obligations - non-operating (営業外電子記録債務)"+ , asAliases = ["営業外電子記録債務"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["営業外電子記録債務"]+ }+row BonusesPayable = ConcreteRow+ { rowCode = 0x808E+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Accrued bonuses"+ , asNameJa = "未払賞与"+ , asLabelJa = "未払賞与"+ , asDescription = "Liability: Accrued bonuses (未払賞与)"+ , asAliases = ["未払賞与"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["未払賞与", "未払役員賞与", "未払賞与金"]+ }+row AllowanceForRepairs = ConcreteRow+ { rowCode = 0x808F+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Allowance for repairs"+ , asNameJa = "修繕引当金"+ , asLabelJa = "修繕引当金"+ , asDescription = "Liability: Allowance for repairs (修繕引当金)"+ , asAliases = ["修繕引当金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["修繕引当金", "特別修繕引当金"]+ }+row AllowanceForProductWarranties = ConcreteRow+ { rowCode = 0x8090+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Allowance for warranties"+ , asNameJa = "商品保証引当金"+ , asLabelJa = "商品保証引当金"+ , asDescription = "Liability: Allowance for warranties (商品保証引当金)"+ , asAliases = ["商品保証引当金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["商品保証引当金", "製品保証引当金"]+ }+row AllowanceForBonuses = ConcreteRow+ { rowCode = 0x8091+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Allowance for bonuses"+ , asNameJa = "賞与引当金"+ , asLabelJa = "賞与引当金"+ , asDescription = "Liability: Allowance for bonuses (賞与引当金)"+ , asAliases = ["賞与引当金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["賞与引当金", "役員賞与引当金"]+ }+row DeferredTaxLiabilities = ConcreteRow+ { rowCode = 0x8092+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Deferred tax liabilities"+ , asNameJa = "繰延税金負債"+ , asLabelJa = "繰延税金負債"+ , asDescription = "Liability: Deferred tax liabilities (繰延税金負債)"+ , asAliases = ["繰延税金負債"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["繰延税金負債"]+ }+row LeaseObligations = ConcreteRow+ { rowCode = 0x8093+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Lease liabilities"+ , asNameJa = "リース債務"+ , asLabelJa = "リース債務"+ , asDescription = "Liability: Lease liabilities (リース債務)"+ , asAliases = ["リース債務"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["リース債務"]+ }+row GuaranteeDepositsReceived = ConcreteRow+ { rowCode = 0x8094+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Guarantee deposits received"+ , asNameJa = "預り保証金"+ , asLabelJa = "預り保証金"+ , asDescription = "Liability: Guarantee deposits received (預り保証金)"+ , asAliases = ["預り保証金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["預り保証金", "受入保証金"]+ }+row AllowanceForRetirementBenefits = ConcreteRow+ { rowCode = 0x8095+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Provision for retirement benefits"+ , asNameJa = "退職給付引当金"+ , asLabelJa = "退職給付引当金"+ , asDescription = "Liability: Provision for retirement benefits (退職給付引当金)"+ , asAliases = ["退職給付引当金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["退職給付引当金"]+ }+row LongTermOtherPayables = ConcreteRow+ { rowCode = 0x8096+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Long-term accounts payable - other"+ , asNameJa = "長期未払金"+ , asLabelJa = "長期未払金"+ , asDescription = "Liability: Long-term accounts payable - other (長期未払金)"+ , asAliases = ["長期未払金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["長期未払金"]+ }+row NetDefinedBenefitLiability = ConcreteRow+ { rowCode = 0x8097+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Retirement benefit liability"+ , asNameJa = "退職給付に係る負債"+ , asLabelJa = "退職給付に係る負債"+ , asDescription = "Liability: Retirement benefit liability (退職給付に係る負債)"+ , asAliases = ["退職給付に係る負債"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["退職給付に係る負債"]+ }+row StockSubscriptionDeposits = ConcreteRow+ { rowCode = 0x8098+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Equity+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Deposits for subscriptions of shares"+ , asNameJa = "株式申込証拠金"+ , asLabelJa = "株式申込証拠金"+ , asDescription = "Equity: Deposits for subscriptions of shares (株式申込証拠金)"+ , asAliases = ["株式申込証拠金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Equity+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["株式申込証拠金", "申込証拠金", "新株式申込証拠金"]+ }+row LegalCapitalSurplus = ConcreteRow+ { rowCode = 0x8099+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Equity+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Legal capital surplus"+ , asNameJa = "資本準備金"+ , asLabelJa = "資本準備金"+ , asDescription = "Equity: Legal capital surplus (資本準備金)"+ , asAliases = ["資本準備金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Equity+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["資本準備金", "株式払込剰余金"]+ }+row OtherCapitalSurplus = ConcreteRow+ { rowCode = 0x809A+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Equity+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Other capital surplus"+ , asNameJa = "その他資本剰余金"+ , asLabelJa = "その他資本剰余金"+ , asDescription = "Equity: Other capital surplus (その他資本剰余金)"+ , asAliases = ["その他資本剰余金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Equity+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["その他資本剰余金"]+ }+row DividendEqualizationReserve = ConcreteRow+ { rowCode = 0x809B+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Equity+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Reserve for dividend equalization"+ , asNameJa = "配当平均積立金"+ , asLabelJa = "配当平均積立金"+ , asDescription = "Equity: Reserve for dividend equalization (配当平均積立金)"+ , asAliases = ["配当平均積立金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Equity+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["配当平均積立金"]+ }+row RepairFundReserve = ConcreteRow+ { rowCode = 0x809C+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Equity+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Reserve for repairs"+ , asNameJa = "修繕積立金"+ , asLabelJa = "修繕積立金"+ , asDescription = "Equity: Reserve for repairs (修繕積立金)"+ , asAliases = ["修繕積立金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Equity+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["修繕積立金"]+ }+row ConstructionFundReserve = ConcreteRow+ { rowCode = 0x809D+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Equity+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Reserve for new construction"+ , asNameJa = "新築積立金"+ , asLabelJa = "新築積立金"+ , asDescription = "Equity: Reserve for new construction (新築積立金)"+ , asAliases = ["新築積立金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Equity+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["新築積立金"]+ }+row GeneralReserve = ConcreteRow+ { rowCode = 0x809E+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Equity+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "General reserve"+ , asNameJa = "別途積立金"+ , asLabelJa = "別途積立金"+ , asDescription = "Equity: General reserve (別途積立金)"+ , asAliases = ["別途積立金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Equity+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["別途積立金"]+ }+row ValuationDifferenceOnOtherSecurities = ConcreteRow+ { rowCode = 0x809F+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Equity+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Valuation difference on available-for-sale securities"+ , asNameJa = "その他有価証券評価差額金"+ , asLabelJa = "その他有価証券評価差額金"+ , asDescription = "Equity: Valuation difference on available-for-sale securities (その他有価証券評価差額金)"+ , asAliases = ["その他有価証券評価差額金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Equity+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["その他有価証券評価差額金"]+ }+row NonControllingInterests = ConcreteRow+ { rowCode = 0x80A0+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Equity+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Non-controlling interests"+ , asNameJa = "非支配株主持分"+ , asLabelJa = "非支配株主持分"+ , asDescription = "Equity: Non-controlling interests (非支配株主持分)"+ , asAliases = ["非支配株主持分"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [AttributionAccount]+ , asemPostingCapability = ConsolidationOnly+ , asemDivisionSemantics = StatementDivision Equity+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = ContextualPresentation+ }+ , rowJcciAliases = ["非支配株主持分"]+ }+row CapitalSurplus = ConcreteRow+ { rowCode = 0x80A1+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Equity+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Capital surplus"+ , asNameJa = "資本剰余金"+ , asLabelJa = "資本剰余金"+ , asDescription = "Equity: Capital surplus (資本剰余金)"+ , asAliases = ["資本剰余金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Equity+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["資本剰余金"]+ }+row EarnedSurplus = ConcreteRow+ { rowCode = 0x80A2+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Equity+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Retained earnings"+ , asNameJa = "利益剰余金"+ , asLabelJa = "利益剰余金"+ , asDescription = "Equity: Retained earnings (利益剰余金)"+ , asAliases = ["利益剰余金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Equity+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["利益剰余金"]+ }+row ServiceRevenue = ConcreteRow+ { rowCode = 0x80A3+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Service revenue"+ , asNameJa = "役務収益"+ , asLabelJa = "役務収益"+ , asDescription = "Revenue: Service revenue (役務収益)"+ , asAliases = ["役務収益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["役務収益", "営業収益"]+ }+row OperatingRevenue = ConcreteRow+ { rowCode = 0x80A4+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Operating revenue"+ , asNameJa = "営業収益"+ , asLabelJa = "営業収益"+ , asDescription = "Revenue: Operating revenue (営業収益)"+ , asAliases = ["営業収益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["営業収益"]+ }+row GainOnSalesOfSecurities = ConcreteRow+ { rowCode = 0x80A5+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Gain on sale of securities"+ , asNameJa = "有価証券売却益"+ , asLabelJa = "有価証券売却益"+ , asDescription = "Revenue: Gain on sale of securities (有価証券売却益)"+ , asAliases = ["有価証券売却益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["有価証券売却益", "有価証券売買益", "有価証券運用益"]+ }+row GainOnValuationOfSecurities = ConcreteRow+ { rowCode = 0x80A6+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Gain on valuation of securities"+ , asNameJa = "有価証券評価益"+ , asLabelJa = "有価証券評価益"+ , asDescription = "Revenue: Gain on valuation of securities (有価証券評価益)"+ , asAliases = ["有価証券評価益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["有価証券運用益", "有価証券評価益", "有価証券評価損益", "有価証券運用損益"]+ }+row DividendsReceived = ConcreteRow+ { rowCode = 0x80A7+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Dividend income"+ , asNameJa = "受取配当金"+ , asLabelJa = "受取配当金"+ , asDescription = "Revenue: Dividend income (受取配当金)"+ , asAliases = ["受取配当金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["受取配当金"]+ }+row InterestOnSecurities = ConcreteRow+ { rowCode = 0x80A8+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Interest on securities"+ , asNameJa = "有価証券利息"+ , asLabelJa = "有価証券利息"+ , asDescription = "Revenue: Interest on securities (有価証券利息)"+ , asAliases = ["有価証券利息"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["有価証券利息", "受取社債利息"]+ }+row GainOnSalesOfInvestmentSecurities = ConcreteRow+ { rowCode = 0x80A9+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Gain on sale of investment securities"+ , asNameJa = "投資有価証券売却益"+ , asLabelJa = "投資有価証券売却益"+ , asDescription = "Revenue: Gain on sale of investment securities (投資有価証券売却益)"+ , asAliases = ["投資有価証券売却益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["投資有価証券売却益", "その他有価証券売却益"]+ }+row InsuranceGain = ConcreteRow+ { rowCode = 0x80AA+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Gain on insurance claims"+ , asNameJa = "保険差益"+ , asLabelJa = "保険差益"+ , asDescription = "Revenue: Gain on insurance claims (保険差益)"+ , asAliases = ["保険差益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["保険差益"]+ }+row GainOnBargainPurchase = ConcreteRow+ { rowCode = 0x80AB+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Gain on bargain purchase"+ , asNameJa = "負ののれん発生益"+ , asLabelJa = "負ののれん発生益"+ , asDescription = "Revenue: Gain on bargain purchase (負ののれん発生益)"+ , asAliases = ["負ののれん発生益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["負ののれん発生益"]+ }+row ReversalOfAllowanceForRepairs = ConcreteRow+ { rowCode = 0x80AC+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Reversal of allowance for repairs"+ , asNameJa = "修繕引当金戻入"+ , asLabelJa = "修繕引当金戻入"+ , asDescription = "Revenue: Reversal of allowance for repairs (修繕引当金戻入)"+ , asAliases = ["修繕引当金戻入"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["修繕引当金戻入"]+ }+row ReversalOfAllowanceForProductWarranties = ConcreteRow+ { rowCode = 0x80AD+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Reversal of allowance for warranties"+ , asNameJa = "商品保証引当金戻入"+ , asLabelJa = "商品保証引当金戻入"+ , asDescription = "Revenue: Reversal of allowance for warranties (商品保証引当金戻入)"+ , asAliases = ["商品保証引当金戻入"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["商品保証引当金戻入", "製品保証引当金戻入"]+ }+row GainOnDonationOfFixedAssets = ConcreteRow+ { rowCode = 0x80AE+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Gain on receipt of donated non-current assets"+ , asNameJa = "固定資産受贈益"+ , asLabelJa = "固定資産受贈益"+ , asDescription = "Revenue: Gain on receipt of donated non-current assets (固定資産受贈益)"+ , asAliases = ["固定資産受贈益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["固定資産受贈益"]+ }+row GainOnNationalSubsidies = ConcreteRow+ { rowCode = 0x80AF+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Gain on receipt of national subsidies"+ , asNameJa = "国庫補助金受贈益"+ , asLabelJa = "国庫補助金受贈益"+ , asDescription = "Revenue: Gain on receipt of national subsidies (国庫補助金受贈益)"+ , asAliases = ["国庫補助金受贈益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["国庫補助金受贈益"]+ }+row GainOnConstructionGrants = ConcreteRow+ { rowCode = 0x80B0+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Gain on contribution received for construction"+ , asNameJa = "工事負担金受贈益"+ , asLabelJa = "工事負担金受贈益"+ , asDescription = "Revenue: Gain on contribution received for construction (工事負担金受贈益)"+ , asAliases = ["工事負担金受贈益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["工事負担金受贈益"]+ }+row LandRentReceived = ConcreteRow+ { rowCode = 0x80B1+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Rental income from land"+ , asNameJa = "受取地代"+ , asLabelJa = "受取地代"+ , asDescription = "Revenue: Rental income from land (受取地代)"+ , asAliases = ["受取地代"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["受取地代"]+ }+row SalesRebates = ConcreteRow+ { rowCode = 0x80B2+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = True+ , asFixedCurrent = Other+ , asNameEn = "Sales rebates"+ , asNameJa = "売上割戻"+ , asLabelJa = "売上割戻"+ , asDescription = "Revenue: Sales rebates (売上割戻)"+ , asAliases = ["売上割戻"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount, ContraAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["売上割戻"]+ }+row CostOfServices = ConcreteRow+ { rowCode = 0x80B3+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Cost of services"+ , asNameJa = "役務原価"+ , asLabelJa = "役務原価"+ , asDescription = "Expense: Cost of services (役務原価)"+ , asAliases = ["役務原価"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["役務原価", "営業費用"]+ }+row OperatingExpenses = ConcreteRow+ { rowCode = 0x80B4+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Operating expenses"+ , asNameJa = "営業費用"+ , asLabelJa = "営業費用"+ , asDescription = "Expense: Operating expenses (営業費用)"+ , asAliases = ["営業費用"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["営業費用"]+ }+row InventoryShrinkageLoss = ConcreteRow+ { rowCode = 0x80B5+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Inventory shrinkage loss"+ , asNameJa = "棚卸減耗損"+ , asLabelJa = "棚卸減耗損"+ , asDescription = "Expense: Inventory shrinkage loss (棚卸減耗損)"+ , asAliases = ["棚卸減耗損"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["棚卸減耗損", "棚卸減耗費"]+ }+row LossOnValuationOfMerchandise = ConcreteRow+ { rowCode = 0x80B6+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Valuation loss on goods"+ , asNameJa = "商品評価損"+ , asLabelJa = "商品評価損"+ , asDescription = "Expense: Valuation loss on goods (商品評価損)"+ , asAliases = ["商品評価損"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["商品評価損", "棚卸評価損"]+ }+row Bonuses = ConcreteRow+ { rowCode = 0x80B7+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Bonuses"+ , asNameJa = "賞与"+ , asLabelJa = "賞与"+ , asDescription = "Expense: Bonuses (賞与)"+ , asAliases = ["賞与"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["賞与", "役員賞与"]+ }+row RetirementBenefitExpenses = ConcreteRow+ { rowCode = 0x80B8+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Retirement benefit expenses"+ , asNameJa = "退職給付費用"+ , asLabelJa = "退職給付費用"+ , asDescription = "Expense: Retirement benefit expenses (退職給付費用)"+ , asAliases = ["退職給付費用"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["退職給付費用", "退職給付引当金繰入", "退職給付引当損"]+ }+row ProvisionForRepairs = ConcreteRow+ { rowCode = 0x80B9+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Provision for repairs"+ , asNameJa = "修繕引当金繰入"+ , asLabelJa = "修繕引当金繰入"+ , asDescription = "Expense: Provision for repairs (修繕引当金繰入)"+ , asAliases = ["修繕引当金繰入"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["修繕引当金繰入", "特別修繕引当金繰入"]+ }+row ProvisionForBonuses = ConcreteRow+ { rowCode = 0x80BA+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Provision for bonuses"+ , asNameJa = "賞与引当金繰入"+ , asLabelJa = "賞与引当金繰入"+ , asDescription = "Expense: Provision for bonuses (賞与引当金繰入)"+ , asAliases = ["賞与引当金繰入"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["賞与引当金繰入", "役員賞与引当金繰入"]+ }+row ProvisionForProductWarranties = ConcreteRow+ { rowCode = 0x80BB+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Provision for warranties"+ , asNameJa = "商品保証引当金繰入"+ , asLabelJa = "商品保証引当金繰入"+ , asDescription = "Expense: Provision for warranties (商品保証引当金繰入)"+ , asAliases = ["商品保証引当金繰入"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["商品保証引当金繰入", "製品保証引当金繰入"]+ }+row ResearchAndDevelopmentExpenses = ConcreteRow+ { rowCode = 0x80BC+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Research and development expenses"+ , asNameJa = "研究開発費"+ , asLabelJa = "研究開発費"+ , asDescription = "Expense: Research and development expenses (研究開発費)"+ , asAliases = ["研究開発費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["研究開発費"]+ }+row AmortizationOfGoodwill = ConcreteRow+ { rowCode = 0x80BD+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Amortization of goodwill"+ , asNameJa = "のれん償却"+ , asLabelJa = "のれん償却"+ , asDescription = "Expense: Amortization of goodwill (のれん償却)"+ , asAliases = ["のれん償却"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["のれん償却"]+ }+row AmortizationOfSoftware = ConcreteRow+ { rowCode = 0x80BE+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Amortization of software"+ , asNameJa = "ソフトウェア償却"+ , asLabelJa = "ソフトウェア償却"+ , asDescription = "Expense: Amortization of software (ソフトウェア償却)"+ , asAliases = ["ソフトウェア償却"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["ソフトウェア償却"]+ }+row AmortizationOfPatents = ConcreteRow+ { rowCode = 0x80BF+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Amortization of patent rights"+ , asNameJa = "特許権償却"+ , asLabelJa = "特許権償却"+ , asDescription = "Expense: Amortization of patent rights (特許権償却)"+ , asAliases = ["特許権償却"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["特許権償却"]+ }+row LeaseExpenses = ConcreteRow+ { rowCode = 0x80C0+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Lease expenses"+ , asNameJa = "支払リース料"+ , asLabelJa = "支払リース料"+ , asDescription = "Expense: Lease expenses (支払リース料)"+ , asAliases = ["支払リース料"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["支払リース料"]+ }+row IncorporationExpenses = ConcreteRow+ { rowCode = 0x80C1+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Organization expenses"+ , asNameJa = "創立費"+ , asLabelJa = "創立費"+ , asDescription = "Expense: Organization expenses (創立費)"+ , asAliases = ["創立費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["創立費"]+ }+row StockIssuanceCosts = ConcreteRow+ { rowCode = 0x80C2+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Share issuance costs"+ , asNameJa = "株式交付費"+ , asLabelJa = "株式交付費"+ , asDescription = "Expense: Share issuance costs (株式交付費)"+ , asAliases = ["株式交付費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["株式交付費"]+ }+row BusinessCommencementExpenses = ConcreteRow+ { rowCode = 0x80C3+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Business commencement expenses"+ , asNameJa = "開業費"+ , asLabelJa = "開業費"+ , asDescription = "Expense: Business commencement expenses (開業費)"+ , asAliases = ["開業費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["開業費"]+ }+row DevelopmentExpenses = ConcreteRow+ { rowCode = 0x80C4+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Development expenses"+ , asNameJa = "開発費"+ , asLabelJa = "開発費"+ , asDescription = "Expense: Development expenses (開発費)"+ , asAliases = ["開発費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["開発費"]+ }+row LossOnSalesOfElectronicallyRecordedReceivables = ConcreteRow+ { rowCode = 0x80C5+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Loss on sale of electronically recorded monetary claims"+ , asNameJa = "電子記録債権売却損"+ , asLabelJa = "電子記録債権売却損"+ , asDescription = "Expense: Loss on sale of electronically recorded monetary claims (電子記録債権売却損)"+ , asAliases = ["電子記録債権売却損"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["電子記録債権売却損"]+ }+row LossOnSalesOfReceivables = ConcreteRow+ { rowCode = 0x80C6+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Loss on sale of receivables"+ , asNameJa = "債権売却損"+ , asLabelJa = "債権売却損"+ , asDescription = "Expense: Loss on sale of receivables (債権売却損)"+ , asAliases = ["債権売却損"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["債権売却損"]+ }+row LossOnSalesOfSecurities = ConcreteRow+ { rowCode = 0x80C7+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Loss on sale of securities"+ , asNameJa = "有価証券売却損"+ , asLabelJa = "有価証券売却損"+ , asDescription = "Expense: Loss on sale of securities (有価証券売却損)"+ , asAliases = ["有価証券売却損"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["有価証券売却損", "有価証券売買損", "有価証券運用損"]+ }+row LossOnValuationOfSecurities = ConcreteRow+ { rowCode = 0x80C8+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Loss on valuation of securities"+ , asNameJa = "有価証券評価損"+ , asLabelJa = "有価証券評価損"+ , asDescription = "Expense: Loss on valuation of securities (有価証券評価損)"+ , asAliases = ["有価証券評価損"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["有価証券運用損", "有価証券評価損", "有価証券評価損益", "有価証券運用損益"]+ }+row LossOnSalesOfInvestmentSecurities = ConcreteRow+ { rowCode = 0x80C9+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Loss on sale of investment securities"+ , asNameJa = "投資有価証券売却損"+ , asLabelJa = "投資有価証券売却損"+ , asDescription = "Expense: Loss on sale of investment securities (投資有価証券売却損)"+ , asAliases = ["投資有価証券売却損"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["投資有価証券売却損", "その他有価証券売却損"]+ }+row LossOnFire = ConcreteRow+ { rowCode = 0x80CA+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Loss on fire"+ , asNameJa = "火災損失"+ , asLabelJa = "火災損失"+ , asDescription = "Expense: Loss on fire (火災損失)"+ , asAliases = ["火災損失"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["火災損失", "災害損失"]+ }+row LossOnRetirementOfFixedAssets = ConcreteRow+ { rowCode = 0x80CB+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Loss on retirement of non-current assets"+ , asNameJa = "固定資産除却損"+ , asLabelJa = "固定資産除却損"+ , asDescription = "Expense: Loss on retirement of non-current assets (固定資産除却損)"+ , asAliases = ["固定資産除却損"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["固定資産除却損", "固定資産廃棄損", "備品除却損", "建物除却損", "除却損"]+ }+row LossOnReductionOfFixedAssets = ConcreteRow+ { rowCode = 0x80CC+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Loss on tax purpose reduction entry of non-current assets"+ , asNameJa = "固定資産圧縮損"+ , asLabelJa = "固定資産圧縮損"+ , asDescription = "Expense: Loss on tax purpose reduction entry of non-current assets (固定資産圧縮損)"+ , asAliases = ["固定資産圧縮損"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["固定資産圧縮損", "備品圧縮損", "建物圧縮損", "機械装置圧縮損"]+ }+row AdditionalIncomeTaxesForPriorPeriods = ConcreteRow+ { rowCode = 0x80CD+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Additional income taxes for prior periods"+ , asNameJa = "追徴法人税等"+ , asLabelJa = "追徴法人税等"+ , asDescription = "Expense: Additional income taxes for prior periods (追徴法人税等)"+ , asAliases = ["追徴法人税等"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["追徴法人税等"]+ }+row RefundOfIncomeTaxes = ConcreteRow+ { rowCode = 0x80CE+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = True+ , asFixedCurrent = Other+ , asNameEn = "Refund of income taxes"+ , asNameJa = "還付法人税等"+ , asLabelJa = "還付法人税等"+ , asDescription = "Expense: Refund of income taxes (還付法人税等)"+ , asAliases = ["還付法人税等"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount, ContraAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["還付法人税等"]+ }+row PurchaseRebates = ConcreteRow+ { rowCode = 0x80CF+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = True+ , asFixedCurrent = Other+ , asNameEn = "Purchase rebates"+ , asNameJa = "仕入割戻"+ , asLabelJa = "仕入割戻"+ , asDescription = "Expense: Purchase rebates (仕入割戻)"+ , asAliases = ["仕入割戻"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount, ContraAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["仕入割戻"]+ }+row WelfareExpenses = ConcreteRow+ { rowCode = 0x80D0+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Welfare expenses"+ , asNameJa = "福利厚生費"+ , asLabelJa = "福利厚生費"+ , asDescription = "Expense: Welfare expenses (福利厚生費)"+ , asAliases = ["福利厚生費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["福利厚生費"]+ }+row MaintenanceExpenses = ConcreteRow+ { rowCode = 0x80D1+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Maintenance expenses"+ , asNameJa = "保守費"+ , asLabelJa = "保守費"+ , asDescription = "Expense: Maintenance expenses (保守費)"+ , asAliases = ["保守費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["保守費", "維持費", "支払メンテナンス料"]+ }+row StatutoryWelfareExpenses = ConcreteRow+ { rowCode = 0x80D2+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Legal welfare expenses"+ , asNameJa = "法定福利費"+ , asLabelJa = "法定福利費"+ , asDescription = "Expense: Legal welfare expenses (法定福利費)"+ , asAliases = ["法定福利費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["法定福利費", "社会保険料"]+ }+row LandRentPaid = ConcreteRow+ { rowCode = 0x80D3+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Rent expenses on land"+ , asNameJa = "支払地代"+ , asLabelJa = "支払地代"+ , asDescription = "Expense: Rent expenses on land (支払地代)"+ , asAliases = ["支払地代"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["地代家賃", "支払賃借料", "支払不動産賃借料", "支払地代"]+ }+row InsuranceExpense = ConcreteRow+ { rowCode = 0x80D4+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Insurance expenses"+ , asNameJa = "保険料"+ , asLabelJa = "保険料"+ , asDescription = "Expense: Insurance expenses (保険料)"+ , asAliases = ["保険料"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["保険料", "支払保険料", "火災保険料"]+ }+row RepairsExpense = ConcreteRow+ { rowCode = 0x80D5+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Repair expenses"+ , asNameJa = "修繕費"+ , asLabelJa = "修繕費"+ , asDescription = "Expense: Repair expenses (修繕費)"+ , asAliases = ["修繕費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["修繕費", "支払修繕料", "修理費"]+ }+row StorageExpenses = ConcreteRow+ { rowCode = 0x80D6+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Storage costs"+ , asNameJa = "保管費"+ , asLabelJa = "保管費"+ , asDescription = "Expense: Storage costs (保管費)"+ , asAliases = ["保管費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["保管費", "保管料", "倉庫料"]+ }+row MembershipFees = ConcreteRow+ { rowCode = 0x80D7+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Membership fees"+ , asNameJa = "諸会費"+ , asLabelJa = "諸会費"+ , asDescription = "Expense: Membership fees (諸会費)"+ , asAliases = ["諸会費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["諸会費"]+ }+row IncomeSummary = ConcreteRow+ { rowCode = 0x80D8+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = NoClose+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Income summary"+ , asNameJa = "損益"+ , asLabelJa = "損益"+ , asDescription = "Bookkeeping device: Income summary (損益). Assets/NoClose is a technical debit-side placeholder; it is not a balance-sheet asset and is not automatically closed."+ , asAliases = ["損益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [ClosingDevice]+ , asemPostingCapability = ClosingOnly+ , asemDivisionSemantics = DirectionEncoding Assets+ , asemHomeSideSemantics = ContextDependentHomeSide+ , asemReportingEligibility = NotPresented+ }+ , rowJcciAliases = ["損益"]+ }+row SuspenseAccount = ConcreteRow+ { rowCode = 0x80D9+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Suspense account"+ , asNameJa = "未決算"+ , asLabelJa = "未決算"+ , asDescription = "Asset: Suspense account (未決算)"+ , asAliases = ["未決算"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [SuspenseOrClearingAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = BookkeepingControlClass Assets+ , asemHomeSideSemantics = ContextDependentHomeSide+ , asemReportingEligibility = ContextualPresentation+ }+ , rowJcciAliases = ["未決算", "火災未決算", "保険未決算"]+ }+row ForeignExchangeGains = ConcreteRow+ { rowCode = 0x80DA+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Foreign exchange gains"+ , asNameJa = "為替差益"+ , asLabelJa = "為替差益"+ , asDescription = "Revenue: Foreign exchange gains (為替差益)"+ , asAliases = ["為替差益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["為替差損益", "為替差益"]+ }+row ForeignExchangeLosses = ConcreteRow+ { rowCode = 0x80DB+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Foreign exchange losses"+ , asNameJa = "為替差損"+ , asLabelJa = "為替差損"+ , asDescription = "Expense: Foreign exchange losses (為替差損)"+ , asAliases = ["為替差損"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["為替差損益", "為替差損"]+ }+row ContraAccountForGuaranteeObligations = ConcreteRow+ { rowCode = 0x80DC+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Contra account for guarantee obligations"+ , asNameJa = "保証債務見返"+ , asLabelJa = "保証債務見返"+ , asDescription = "Asset: Contra account for guarantee obligations (保証債務見返)"+ , asAliases = ["保証債務見返"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["保証債務見返"]+ }+row GuaranteeObligations = ConcreteRow+ { rowCode = 0x80DD+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Guarantee obligations"+ , asNameJa = "保証債務"+ , asLabelJa = "保証債務"+ , asDescription = "Liability: Guarantee obligations (保証債務)"+ , asAliases = ["保証債務"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["保証債務"]+ }+row IncomeTaxesAdjustment = ConcreteRow+ { rowCode = 0x80DE+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Income taxes - deferred"+ , asNameJa = "法人税等調整額"+ , asLabelJa = "法人税等調整額"+ , asDescription = "Expense: Income taxes - deferred (法人税等調整額)"+ , asAliases = ["法人税等調整額"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["法人税等調整額"]+ }+row BranchCurrentAccount = ConcreteRow+ { rowCode = 0x80DF+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Branch current account"+ , asNameJa = "支店"+ , asLabelJa = "支店"+ , asDescription = "Asset: Branch current account (支店)"+ , asAliases = ["支店"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [ReciprocalAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = BookkeepingControlClass Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = ContextualPresentation+ }+ , rowJcciAliases = ["支店"]+ }+row HeadOfficeCurrentAccount = ConcreteRow+ { rowCode = 0x80E0+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Head office current account"+ , asNameJa = "本店"+ , asLabelJa = "本店"+ , asDescription = "Liability: Head office current account (本店), the credit-balance reciprocal account in branch books."+ , asAliases = ["本店"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [ReciprocalAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = BookkeepingControlClass Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = ContextualPresentation+ }+ , rowJcciAliases = ["本店"]+ }+row NetIncomeAttributableToNCI = ConcreteRow+ { rowCode = 0x80E1+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = NoClose+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Profit attributable to non-controlling interests"+ , asNameJa = "非支配株主に帰属する当期純利益"+ , asLabelJa = "非支配株主に帰属する当期純利益"+ , asDescription = "Expense: Profit attributable to non-controlling interests (非支配株主に帰属する当期純利益). NoClose: consolidation procedures transfer it separately to non-controlling interests."+ , asAliases = ["非支配株主に帰属する当期純利益"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [AttributionAccount, PeriodResult]+ , asemPostingCapability = ConsolidationOnly+ , asemDivisionSemantics = DirectionEncoding Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = ContextualPresentation+ }+ , rowJcciAliases = ["非支配株主に帰属する当期純利益"]+ }+row NetLossAttributableToNCI = ConcreteRow+ { rowCode = 0x80E2+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = NoClose+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Loss attributable to non-controlling interests"+ , asNameJa = "非支配株主に帰属する当期純損失"+ , asLabelJa = "非支配株主に帰属する当期純損失"+ , asDescription = "Revenue: Loss attributable to non-controlling interests (非支配株主に帰属する当期純損失). NoClose: consolidation procedures transfer it separately to non-controlling interests."+ , asAliases = ["非支配株主に帰属する当期純損失"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [AttributionAccount, PeriodResult]+ , asemPostingCapability = ConsolidationOnly+ , asemDivisionSemantics = DirectionEncoding Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = ContextualPresentation+ }+ , rowJcciAliases = ["非支配株主に帰属する当期純損失"]+ }+row TradingSecurities = ConcreteRow+ { rowCode = 0x80E3+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Trading securities"+ , asNameJa = "売買目的有価証券"+ , asLabelJa = "売買目的有価証券"+ , asDescription = "Asset: Trading securities (売買目的有価証券)"+ , asAliases = ["売買目的有価証券"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["売買目的有価証券", "有価証券"]+ }+row HeldToMaturityBonds = ConcreteRow+ { rowCode = 0x80E4+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Held-to-maturity bonds"+ , asNameJa = "満期保有目的債券"+ , asLabelJa = "満期保有目的債券"+ , asDescription = "Asset: Held-to-maturity bonds (満期保有目的債券)"+ , asAliases = ["満期保有目的債券"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["満期保有目的債券", "投資有価証券"]+ }+row SubsidiaryStocks = ConcreteRow+ { rowCode = 0x80E5+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Shares of subsidiaries"+ , asNameJa = "子会社株式"+ , asLabelJa = "子会社株式"+ , asDescription = "Asset: Shares of subsidiaries (子会社株式)"+ , asAliases = ["子会社株式"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["子会社株式", "関係会社株式"]+ }+row AffiliateStocks = ConcreteRow+ { rowCode = 0x80E6+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Shares of associates"+ , asNameJa = "関連会社株式"+ , asLabelJa = "関連会社株式"+ , asDescription = "Asset: Shares of associates (関連会社株式)"+ , asAliases = ["関連会社株式"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["関係会社株式", "関連会社株式"]+ }+row AvailableForSaleSecurities = ConcreteRow+ { rowCode = 0x80E7+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Fixed+ , asNameEn = "Available-for-sale securities"+ , asNameJa = "その他有価証券"+ , asLabelJa = "その他有価証券"+ , asDescription = "Asset: Available-for-sale securities (その他有価証券)"+ , asAliases = ["その他有価証券"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["投資有価証券", "その他有価証券"]+ }+row ConsumptionTaxRefundReceivable = ConcreteRow+ { rowCode = 0x80E8+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Consumption tax refund receivable"+ , asNameJa = "未収還付消費税"+ , asLabelJa = "未収還付消費税"+ , asDescription = "Asset: Consumption tax refund receivable (未収還付消費税)"+ , asAliases = ["未収還付消費税", "未収消費税"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["未収還付消費税", "未収消費税"]+ }+row PropertyTaxPayable = ConcreteRow+ { rowCode = 0x80E9+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Property tax payable"+ , asNameJa = "未払固定資産税"+ , asLabelJa = "未払固定資産税"+ , asDescription = "Liability: Property tax payable (未払固定資産税)"+ , asAliases = ["未払固定資産税"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["未払固定資産税"]+ }+row DepositsReceivedFromOfficers = ConcreteRow+ { rowCode = 0x80EA+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Liability+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Deposits received from officers"+ , asNameJa = "役員預り金"+ , asLabelJa = "役員預り金"+ , asDescription = "Liability: Deposits received from officers (役員預り金)"+ , asAliases = ["役員預り金"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Liability+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = ["役員預り金"]+ }+row EntertainmentExpenses = ConcreteRow+ { rowCode = 0x80EB+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Entertainment expenses"+ , asNameJa = "交際費"+ , asLabelJa = "交際費"+ , asDescription = "Expense: Entertainment expenses (交際費)"+ , asAliases = ["交際費", "接待交際費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row MeetingExpenses = ConcreteRow+ { rowCode = 0x80EC+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Meeting expenses"+ , asNameJa = "会議費"+ , asLabelJa = "会議費"+ , asDescription = "Expense: Meeting expenses (会議費)"+ , asAliases = ["会議費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row NewspaperBooksExpenses = ConcreteRow+ { rowCode = 0x80ED+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Newspapers and books"+ , asNameJa = "新聞図書費"+ , asLabelJa = "新聞図書費"+ , asDescription = "Expense: Newspapers and books (新聞図書費)"+ , asAliases = ["新聞図書費"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row RawMaterials = ConcreteRow+ { rowCode = 0x80EE+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Raw materials"+ , asNameJa = "原材料"+ , asLabelJa = "原材料"+ , asDescription = "Asset: Raw materials (原材料)"+ , asAliases = ["原材料", "材料"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row GoodsInTransit = ConcreteRow+ { rowCode = 0x80EF+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Assets+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Current+ , asNameEn = "Goods in transit"+ , asNameJa = "未着品"+ , asLabelJa = "未着品"+ , asDescription = "Asset: Goods in transit (未着品)"+ , asAliases = ["未着品"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Assets+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row SalesAllowances = ConcreteRow+ { rowCode = 0x80F0+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = True+ , asFixedCurrent = Other+ , asNameEn = "Sales allowances"+ , asNameJa = "売上値引"+ , asLabelJa = "売上値引"+ , asDescription = "Revenue: Sales allowances (売上値引)"+ , asAliases = ["売上値引"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount, ContraAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row PurchaseAllowances = ConcreteRow+ { rowCode = 0x80F1+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = True+ , asFixedCurrent = Other+ , asNameEn = "Purchase allowances"+ , asNameJa = "仕入値引"+ , asLabelJa = "仕入値引"+ , asDescription = "Expense: Purchase allowances (仕入値引)"+ , asAliases = ["仕入値引"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount, ContraAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row ReversalOfAllowanceForBonuses = ConcreteRow+ { rowCode = 0x80F2+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Revenue+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Reversal of allowance for bonuses"+ , asNameJa = "賞与引当金戻入"+ , asLabelJa = "賞与引当金戻入"+ , asDescription = "Revenue: Reversal of allowance for bonuses (賞与引当金戻入)"+ , asAliases = ["賞与引当金戻入"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Revenue+ , asemHomeSideSemantics = FixedHomeSide Credit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row DirectorsCompensations = ConcreteRow+ { rowCode = 0x80F3+ , rowScheme = Jcci+ , rowSpec = AccountSpec+ { asDivision = Cost+ , asClosing = CloseByDivision+ , asIsContra = False+ , asFixedCurrent = Other+ , asNameEn = "Remuneration for directors (and other officers)"+ , asNameJa = "役員報酬"+ , asLabelJa = "役員報酬"+ , asDescription = "Expense: Remuneration for directors (役員報酬)"+ , asAliases = ["役員報酬"]+ }+ , rowSemantics = AccountSemantics+ { asemRoles = [OrdinaryAccount]+ , asemPostingCapability = OrdinaryPosting+ , asemDivisionSemantics = StatementDivision Cost+ , asemHomeSideSemantics = FixedHomeSide Debit+ , asemReportingEligibility = StatementEligible+ }+ , rowJcciAliases = []+ }+row AccountTitle = WildcardRow++-- | Determine whether the title belongs to the JCCI vocabulary, including the wildcard.+isJcciTitle :: AccountTitles -> Bool+isJcciTitle title = case row title of+ WildcardRow -> True+ ConcreteRow { rowScheme = Jcci } -> True+ ConcreteRow { rowScheme = Macro } -> False++instance NFData AccountTitles++instance Hashable AccountTitles where+ {-# INLINE hashWithSalt #-}+ hashWithSalt salt x = hashWithSalt salt (fromEnum x)++-- | Serialize a title as a two-byte big-endian code: @0x8000 + n@, where+-- @n@ is the title's fixed number from 'accountCode', or @0xFFFF@ for the+-- wildcard 'AccountTitle'. The high bit marks the 0.6 encoding: bytes written+-- by 0.5.x (the declaration index, always below @0x8000@) and unknown codes+-- fail to decode, so a title added later never shifts an existing code.+instance Binary.Binary AccountTitles where+ {-# INLINE put #-}+ put = BinaryPut.putWord16be . accountCode+ {-# INLINE get #-}+ get = do+ code <- BinaryGet.getWord16be+ case Map.lookup code accountTitlesByCode of+ Just title -> pure title+ Nothing -> fail ("AccountTitles: unknown or unmarked code " ++ show code)++-- | The fixed two-byte wire code of a title.+accountCode :: AccountTitles -> Word16+accountCode title = case row title of+ WildcardRow -> 0xFFFF+ ConcreteRow { rowCode = code } -> code++-- | Inverse of the fixed codes, shared by every decode.+accountTitlesByCode :: Map.Map Word16 AccountTitles+accountTitlesByCode = Map.fromList [(accountCode title, title) | title <- [minBound .. maxBound]]++instance Element AccountTitles where+ {-# INLINE wildcard #-}+ wildcard = AccountTitle++instance BaseClass AccountTitles where
+ src/ExchangeAlgebra/Accounting/Account/Vocabulary.hs view
@@ -0,0 +1,95 @@+-- | Account metadata for bases that carry built-in or user-defined titles.+module ExchangeAlgebra.Accounting.Account.Vocabulary+ ( AccountVocabulary(..)+ , classifyAccountDivision+ ) where++import ExchangeAlgebra.Accounting.Account.Classification (AccountDivision, Side(..))+import ExchangeAlgebra.Accounting.Account.Registry+ ( AccountSpec(..), AccountSemantics, accountSpec, accountSemantics+ , classifyAccountContra )+import ExchangeAlgebra.Accounting.Account.Title (AccountTitles(..))+import ExchangeAlgebra.Algebra.Base.Representation (customError)+import ExchangeAlgebra.Algebra.Element.Representation (Element)+import GHC.Stack (HasCallStack)++-- | Supply account metadata for a title type.+--+-- All instances must satisfy these laws under exact equality:+--+-- * For each concrete title @t@, @vocabSpec t@ returns @Just spec@ and+-- @vocabDivision t == asDivision spec@.+-- * @vocabContra t == maybe False asIsContra (vocabSpec t)@.+-- * 'closingTarget' differs from the wildcard, has a specification with+-- division @Equity@, and has @vocabContra closingTarget == False@.+-- * Each endpoint in 'vocabReciprocalPairs' is concrete, has the+-- @ReciprocalAccount@ role in 'vocabSemantics', and is neither a Cost nor+-- a Revenue account. No title occurs more than once across all pairs.+class Element t => AccountVocabulary t where+ -- | Look up a title's specification. The wildcard returns 'Nothing'.+ vocabSpec :: t -> Maybe AccountSpec++ -- | Look up roles, posting capability, and reporting eligibility.+ -- The default returns 'Nothing' when the vocabulary supplies no metadata.+ vocabSemantics :: t -> Maybe AccountSemantics+ vocabSemantics _ = Nothing++ -- | Accounts that cannot have a balance on the given side after correct+ -- processing. Each title must be concrete and appear at most once. Each+ -- side must be 'Debit' or 'Credit'. The default list is empty.+ vocabImpossibleBalanceSides :: [(t, Side)]+ vocabImpossibleBalanceSides = []++ -- | Suspense accounts to check after adjustment. A remaining balance+ -- warrants a warning because the item may still be under investigation.+ -- The default list is empty.+ vocabSuspenseTitles :: [t]+ vocabSuspenseTitles = []++ -- | Additional accounts that closing must clear, even when+ -- 'vocabSemantics' supplies no metadata. The default list is empty.+ vocabAdditionalClosingResidualTitles :: [t]+ vocabAdditionalClosingResidualTitles = []++ -- | Pairs eliminated in a combined report, in audit-event order.+ -- The default list is empty.+ vocabReciprocalPairs :: [(t, t)]+ vocabReciprocalPairs = []++ -- | Name the account that receives revenue and cost balances at closing.+ closingTarget :: t++ -- | Read the account division. A title without a specification raises an error.+ vocabDivision :: HasCallStack => t -> AccountDivision+ vocabDivision t = case vocabSpec t of+ Just spec -> asDivision spec+ Nothing -> customError "account title without a specification (wildcard)"++ -- | Test whether a title denotes a contra account.+ vocabContra :: t -> Bool+ vocabContra = maybe False asIsContra . vocabSpec++instance AccountVocabulary AccountTitles where+ vocabSpec = accountSpec+ vocabSemantics = accountSemantics+ vocabImpossibleBalanceSides =+ [ (Cash, Credit), (PettyCash, Credit)+ , (CapitalStock, Debit), (AccumulatedDepreciation, Debit)+ ]+ vocabSuspenseTitles = [SuspensePayments, SuspenseReceipts, SuspenseAccount]+ vocabAdditionalClosingResidualTitles = [CashOverShort]+ vocabReciprocalPairs = [(BranchCurrentAccount, HeadOfficeCurrentAccount)]+ closingTarget = RetainedEarnings+ vocabDivision = classifyAccountDivision+ vocabContra = classifyAccountContra++-- | Classify an account title into an account division (Assets/Equity/Liability/Cost/Revenue).+--+-- Complexity: O(1)+{-# INLINE classifyAccountDivision #-}+classifyAccountDivision :: HasCallStack => AccountTitles -> AccountDivision+classifyAccountDivision AccountTitle = customError "this is wildcard AccountTitle"+classifyAccountDivision title =+ case accountSpec title of+ Just spec -> asDivision spec+ Nothing -> customError "this is wildcard AccountTitle"
src/ExchangeAlgebra/Accounting/Adjustment.hs view
@@ -5,7 +5,7 @@ Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license == Named closing adjustments (決算整理)
+ src/ExchangeAlgebra/Accounting/Audit.hs view
@@ -0,0 +1,437 @@+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ScopedTypeVariables #-}++{-# OPTIONS_GHC -Wincomplete-patterns -Werror=incomplete-patterns #-}++{- |+Module : ExchangeAlgebra.Accounting.Audit+Description : One function per type of accounting anomaly, reported without blocking.++Role: each function detects one type of accounting anomaly that can be judged+without knowing the correct answer, and returns it as a value. Computation+('ExchangeAlgebra.IO.Input.Admission.admit',+'ExchangeAlgebra.Accounting.Statements.Presentation.present') never consults+these audits; the caller, a person or a language model, decides whether to+stop, correct, or accept each finding.++Layer: Accounting. The audits read account semantics (home side, role,+statement division) from the account vocabulary. The table below describes+the built-in chart of accounts. Callers include model authors, teaching+material, and experiments that check model output.++Every audit returns an 'AuditResult'. Whether a function reports 'Warning' or+'Error' is fixed per function by the table below. Invalid values and wildcard+bases are checked first by every function: if any is found, the function+returns 'Error' with 'StructureFinding' and inspects nothing else. 'Warning'+holds accounting findings only.+++----------------------------+-------------------------------+--------------------------+---------++| Function | Reports | Precondition | Result |++============================+===============================+==========================+=========++| 'impossibleBalances' | Credit balance of cash or | Trial balance including | Error |+| | petty cash, debit balance of | the opening balances | |+| | capital stock or accumulated | | |+| | depreciation | | |++----------------------------+-------------------------------+--------------------------+---------++| 'abnormalBalances' | Balance opposite to a fixed | Trial balance including | Warning |+| | home side, except the | the opening balances | |+| | accounts above | | |++----------------------------+-------------------------------+--------------------------+---------++| 'temporaryAccountBalances' | Balance of suspense payments, | Trial balance after | Warning |+| | suspense receipts, or the | adjustment | |+| | suspense account | | |++----------------------------+-------------------------------+--------------------------+---------++| 'closingResiduals' | Balance that closing must | Trial balance after | Error |+| | clear | closing | |++----------------------------+-------------------------------+--------------------------+---------++| 'duplicateTransactions' | Notes with identical postings | Journal | Warning |++----------------------------+-------------------------------+--------------------------+---------++| 'contraryNominalPostings' | Revenue or expense posting | Journal, one transaction | Warning |+| | opposite to its home side, | per note | |+| | outside closing | | |++----------------------------+-------------------------------+--------------------------+---------+++The trial-balance audits read balances as+'ExchangeAlgebra.Accounting.TrialBalance.Balance.accountBalances' does: the+exact posting sum of each account, its direction determined before rounding+the magnitude once, without a tolerance. A balance that nets to exactly zero is+no balance. The input may hold unaggregated postings; the caller does not need+to apply @bar@ first, and the audits do not aggregate the caller's value.++Preconditions are stated by the function name and its documentation; the+argument types do not enforce them. A trial-balance audit given a partial+period reports balances of that partial period.++Structure issues are ordered by kind (invalid value, wildcard account, wildcard+side), then base and value, with journal issues ordered first by note, while+trial-balance accounting findings are ordered by account.++Read 'AuditResult' and 'Finding' first, then the trial-balance audits, then the+journal audits.+-}+module ExchangeAlgebra.Accounting.Audit+ ( -- * Results+ AuditResult(..)+ , Finding(..)+ , StructureIssue(..)+ , TrialBalanceIssue+ , JournalIssue+ -- * Trial-balance audits+ , ImpossibleBalance+ , ImpossibleBalanceOf(..)+ , impossibleBalances+ , AbnormalBalance+ , AbnormalBalanceOf(..)+ , abnormalBalances+ , TemporaryAccountBalance+ , TemporaryAccountBalanceOf(..)+ , temporaryAccountBalances+ , ClosingResidual+ , ClosingResidualOf(..)+ , closingResiduals+ -- * Journal audits+ , DuplicateTransactions(..)+ , duplicateTransactions+ , ContraryNominalPosting(..)+ , contraryNominalPostings+ ) where++import qualified Data.HashMap.Strict as HM+import Data.List (sort, sortOn)+import Data.List.NonEmpty (NonEmpty(..))+import qualified Data.Map.Strict as M++import ExchangeAlgebra.Accounting.Account.Classification+ ( AccountDivision(..)+ , AccountRole(..)+ , DivisionSemantics(..)+ , HomeSideSemantics(..)+ , PostingCapability(..)+ , Side(..)+ )+import ExchangeAlgebra.Accounting.Account.Registry+ (AccountSemantics(..))+import ExchangeAlgebra.Accounting.Account.Title (AccountTitles)+import ExchangeAlgebra.Accounting.Account.Vocabulary (AccountVocabulary(..))+import ExchangeAlgebra.Accounting.Exchange (ExBaseClass(..))+import ExchangeAlgebra.Accounting.TrialBalance.Balance+ ( AccountBalance(..)+ , accountBalances+ , balanceSide+ )+import ExchangeAlgebra.Algebra.Base.Representation (Hat(..), HatBase, HatBaseClass(hat))+import ExchangeAlgebra.Algebra.Core.Representation (Alg, pattern (:@), foldEntries)+import ExchangeAlgebra.Algebra.Element.Representation (Element(isWildcard))+import ExchangeAlgebra.Algebra.Value.Class (HatVal, isErrorValue)+import ExchangeAlgebra.Journal.Core (Journal, Note(..), toMap)++-- * Results++-- | The outcome of one audit, with structure issues @s@ and accounting+-- findings @f@. A function returns either 'Warning' or 'Error' for accounting+-- findings, fixed by the table in the module header. Structure issues appear+-- only in 'Error'.+--+-- 'Warning' marks a state with legitimate exceptions: it may be a mistake or+-- the result of correct processing. 'Error' marks a state with no legitimate+-- exception: some posting or computation is wrong, or the input cannot be+-- audited.+data AuditResult s f+ = NoProblem -- ^ The audit found nothing.+ | Warning (NonEmpty f) -- ^ Findings that have legitimate exceptions.+ | Error (NonEmpty (Finding s f)) -- ^ Findings without a legitimate exception,+ -- or structure issues.+ deriving (Show, Eq)++-- | An element of 'Error': a structure issue that prevents the audit, or an+-- accounting finding of the audit's own type.+data Finding s f+ = StructureFinding s -- ^ The input cannot be audited.+ | AccountingFinding f -- ^ The anomaly this audit looks for.+ deriving (Show, Eq)++-- | A structural condition that prevents an audit.+-- 'ExchangeAlgebra.Accounting.Statements.Presentation.present' checks the same+-- conditions before presenting statements.+data StructureIssue v b+ = InvalidValue v b -- ^ A value that is not a valid posting value.+ | WildcardAccount b -- ^ A base whose account title is the wildcard.+ | WildcardSide b -- ^ A base whose side is the wildcard @HatNot@.+ deriving (Show, Eq)++-- | Structure issues of a trial balance.+type TrialBalanceIssue v = StructureIssue v (HatBase AccountTitles)++-- | Structure issues of a journal, with the note associated with the affected term.+type JournalIssue n v b = (n, StructureIssue v b)++-- | Check every posting before any operation that determines accounting sides.+-- A standalone zero term is inspected just as in the presentation structure check.+structureIssues+ :: forall v b. (HatVal v, ExBaseClass b)+ => Alg v b+ -> [StructureIssue v b]+structureIssues input =+ [InvalidValue value base | (base, value) <- postings, isErrorValue value]+ ++ [WildcardAccount base | (base, _) <- postings, isWildcard (getAccountTitle base)]+ ++ [WildcardSide base | (base, _) <- postings, hat base == HatNot]+ where+ postings :: [(b, v)]+ postings = sort $ case input of+ value :@ base -> [(base, value)]+ _ -> foldEntries (\entries value base -> (base, value) : entries) [] input++-- | Attach notes to structure issues, including those of the blank note.+journalStructureIssues+ :: (HatVal v, ExBaseClass b, Note n)+ => Journal n v b+ -> [JournalIssue n v b]+journalStructureIssues input =+ [ (note, issue)+ | (note, transaction) <- sortOn fst (HM.toList (toMap input))+ , issue <- structureIssues transaction+ ]++-- | Return warning findings only when the list is nonempty.+warningFindings :: [f] -> AuditResult s f+warningFindings [] = NoProblem+warningFindings (finding : findings) = Warning (finding :| findings)++-- | Return accounting errors only when the list is nonempty.+errorFindings :: [f] -> AuditResult s f+errorFindings [] = NoProblem+errorFindings (finding : findings) =+ Error (AccountingFinding finding :| map AccountingFinding findings)++-- * Trial-balance audits++-- | An account whose balance cannot occur under any correct processing.+data ImpossibleBalanceOf t v = ImpossibleBalance+ { _impossibleAccount :: t -- ^ The account.+ , _impossibleBalance :: AccountBalance v -- ^ Its balance.+ }+ deriving (Show, Eq)++-- | An 'ImpossibleBalanceOf' finding for the built-in chart of accounts.+type ImpossibleBalance = ImpossibleBalanceOf AccountTitles++-- | Report 'Error' for balances on a side listed in 'vocabImpossibleBalanceSides'.+-- The built-in chart checks credit balances of cash and petty cash and debit+-- balances of capital stock and accumulated depreciation.+--+-- Precondition: the trial balance includes the opening balances, so that a+-- balance is the balance of the account and not of a partial period.+--+-- Cash on hand is a counted quantity and cannot be negative; a bank overdraft+-- is a liability, not cash (Kieso, Intermediate Accounting, 2025, p. 6-4).+-- Capital stock is credited on issuance and debited only on retirement of+-- issued shares (p. 14-8). Accumulated depreciation is debited only when a+-- disposal removes the amount already recorded (p. 10-26). A credit balance of+-- current deposits is not reported here; see 'abnormalBalances'.+impossibleBalances+ :: (HatVal v, ExBaseClass (HatBase t), TitleOf (HatBase t) ~ t)+ => Alg v (HatBase t)+ -> AuditResult (StructureIssue v (HatBase t)) (ImpossibleBalanceOf t v)+impossibleBalances input = case structureIssues input of+ issue : issues -> Error (StructureFinding issue :| map StructureFinding issues)+ [] -> errorFindings+ [ ImpossibleBalance title balance+ | (title, balance) <- M.toAscList (accountBalances input)+ , Just (balanceSide balance) == lookup title vocabImpossibleBalanceSides+ ]++-- | An account balance on the side opposite to its home side.+data AbnormalBalanceOf t v = AbnormalBalance+ { _abnormalAccount :: t -- ^ The account.+ , _abnormalHomeSide :: Side -- ^ The side its balance normally has.+ , _abnormalBalance :: AccountBalance v -- ^ Its balance.+ }+ deriving (Show, Eq)++-- | An 'AbnormalBalanceOf' finding for the built-in chart of accounts.+type AbnormalBalance = AbnormalBalanceOf AccountTitles++-- | Report balances on the side opposite to the home side, for ordinary+-- accounts whose home side is fixed. The accounts of 'impossibleBalances' are+-- excluded. Returns 'Warning' when any is found.+--+-- Precondition: the trial balance includes the opening balances.+--+-- Legitimate exceptions: a deficit (debit balance of retained earnings), a+-- credit balance of current deposits before it is reclassified to an+-- overdraft at closing+-- ('ExchangeAlgebra.Accounting.Adjustment.overdraftReclassification'), a debit+-- balance of the allowance for doubtful accounts during the period, a credit+-- balance of an expense after a reversing entry, a credit balance of accounts+-- receivable (advance received), and a debit balance of accounts payable+-- (advance paid).+abnormalBalances+ :: (HatVal v, ExBaseClass (HatBase t), TitleOf (HatBase t) ~ t)+ => Alg v (HatBase t)+ -> AuditResult (StructureIssue v (HatBase t)) (AbnormalBalanceOf t v)+abnormalBalances input = case structureIssues input of+ issue : issues -> Error (StructureFinding issue :| map StructureFinding issues)+ [] -> warningFindings+ [ AbnormalBalance title side balance+ | (title, balance) <- M.toAscList (accountBalances input)+ , title `notElem` map fst vocabImpossibleBalanceSides+ , balance /= NoBalance+ , Just semantics <- [vocabSemantics title]+ , OrdinaryAccount `elem` asemRoles semantics+ , FixedHomeSide side <- [asemHomeSideSemantics semantics]+ , balanceSide balance /= side+ ]++-- | A temporary account that still has a balance.+data TemporaryAccountBalanceOf t v = TemporaryAccountBalance+ { _temporaryAccount :: t -- ^ The account.+ , _temporaryBalance :: AccountBalance v -- ^ Its balance.+ }+ deriving (Show, Eq)++-- | A 'TemporaryAccountBalanceOf' finding for the built-in chart of accounts.+type TemporaryAccountBalance = TemporaryAccountBalanceOf AccountTitles++-- | Report 'Warning' for balances of accounts in 'vocabSuspenseTitles'.+-- The built-in chart includes suspense payments, suspense receipts, and the+-- suspense account. 'closingResiduals' checks cash over and short.+--+-- Precondition: the trial balance is taken after adjustment.+--+-- Legitimate exception: an item still under investigation. A suspense payment+-- or receipt is transferred when its content is settled; there is no general+-- rule that it must be cleared at the period end.+temporaryAccountBalances+ :: (HatVal v, ExBaseClass (HatBase t), TitleOf (HatBase t) ~ t)+ => Alg v (HatBase t)+ -> AuditResult (StructureIssue v (HatBase t)) (TemporaryAccountBalanceOf t v)+temporaryAccountBalances input = case structureIssues input of+ issue : issues -> Error (StructureFinding issue :| map StructureFinding issues)+ [] -> warningFindings+ [ TemporaryAccountBalance title balance+ | (title, balance) <- M.toAscList (accountBalances input)+ , title `elem` vocabSuspenseTitles+ , balance /= NoBalance+ ]++-- | An account that closing must clear but that still has a balance.+data ClosingResidualOf t v = ClosingResidual+ { _residualAccount :: t -- ^ The account.+ , _residualBalance :: AccountBalance v -- ^ Its balance.+ }+ deriving (Show, Eq)++-- | A 'ClosingResidualOf' finding for the built-in chart of accounts.+type ClosingResidual = ClosingResidualOf AccountTitles++-- | Report 'Error' for remaining balances of closing devices, period results,+-- reporting subtotals, revenue accounts, and expense accounts. The check also+-- includes every account in 'vocabAdditionalClosingResidualTitles', even+-- when that account has no semantics.+--+-- Precondition: the trial balance is taken after closing.+closingResiduals+ :: (HatVal v, ExBaseClass (HatBase t), TitleOf (HatBase t) ~ t)+ => Alg v (HatBase t)+ -> AuditResult (StructureIssue v (HatBase t)) (ClosingResidualOf t v)+closingResiduals input = case structureIssues input of+ issue : issues -> Error (StructureFinding issue :| map StructureFinding issues)+ [] -> errorFindings+ [ ClosingResidual title balance+ | (title, balance) <- M.toAscList (accountBalances input)+ , balance /= NoBalance+ , title `elem` vocabAdditionalClosingResidualTitles+ || maybe False mustClear (vocabSemantics title)+ ]+ where+ mustClear :: AccountSemantics -> Bool+ mustClear semantics =+ any (`elem` asemRoles semantics) [ClosingDevice, PeriodResult, ReportingSubtotal]+ || asemDivisionSemantics semantics `elem` [StatementDivision Revenue, StatementDivision Cost]++-- * Journal audits++-- | Notes whose transactions have identical postings. The first note is the+-- smallest; the others follow in ascending order.+data DuplicateTransactions n = DuplicateTransactions n (NonEmpty n)+ deriving (Show, Eq)++-- | Report groups of notes whose postings are equal as multisets of value and+-- base. Posting order is ignored and values are compared exactly, without+-- rounding. The blank note ('ExchangeAlgebra.Journal.Core.plank') is+-- excluded. Groups are listed in ascending order of their first note.+-- Returns 'Warning' when any is found.+--+-- A journal entry posted twice keeps the trial balance in balance, so no+-- balance check can find it (Kieso, p. 2-21).+--+-- Legitimate exception: the same entry repeated on purpose, such as monthly+-- rent.+duplicateTransactions+ :: (HatVal v, ExBaseClass b, Note n)+ => Journal n v b+ -> AuditResult (JournalIssue n v b) (DuplicateTransactions n)+duplicateTransactions (input :: Journal n v b) = case journalStructureIssues input of+ issue : issues -> Error (StructureFinding issue :| map StructureFinding issues)+ [] -> warningFindings+ [ DuplicateTransactions first (next :| rest)+ | first : next : rest <- sortedGroups+ ]+ where+ groups :: M.Map [(v, b)] [n]+ groups = M.fromListWith (++)+ [ ( sort $ foldEntries (\entries value base -> (value, base) : entries) [] transaction+ , [note]+ )+ | (note, transaction) <- HM.toList (toMap input)+ , note /= plank+ ]+ sortedGroups :: [[n]]+ sortedGroups = sort $ map sort $ M.elems groups++-- | A posting to a revenue or expense account on the side opposite to its+-- home side.+data ContraryNominalPosting n v b = ContraryNominalPosting+ { _contraryNote :: n -- ^ The transaction.+ , _contraryValue :: v -- ^ The posted value.+ , _contraryBase :: b -- ^ The posted base.+ }+ deriving (Show, Eq)++-- | Report, within each transaction, postings to revenue or expense accounts+-- on the side opposite to their home side. For contra accounts such as sales+-- allowances, whose home side is debit, a debit posting is normal and a credit+-- posting is reported. Transactions that post to an account reserved for+-- closing (income summary) are excluded. Returns 'Warning' when any is found.+--+-- Precondition: each note holds one transaction.+--+-- Legitimate exceptions: returns and allowances, reversing entries+-- (Kieso, p. 2-55), transfer of purchases to cost of sales, and elimination in+-- consolidation.+contraryNominalPostings+ :: (HatVal v, ExBaseClass b, Note n)+ => Journal n v b+ -> AuditResult (JournalIssue n v b) (ContraryNominalPosting n v b)+contraryNominalPostings (input :: Journal n v b) = case journalStructureIssues input of+ issue : issues -> Error (StructureFinding issue :| map StructureFinding issues)+ [] -> warningFindings+ [ ContraryNominalPosting note value base+ | (note, transaction) <- sortOn fst (HM.toList (toMap input))+ , note /= plank+ , let postings :: [(b, v)]+ postings = foldEntries (\entries value base -> (base, value) : entries) [] transaction+ , all ((/= ClosingOnly) . postingCapability . fst) postings+ , (base, value) <- sort postings+ , Just semantics <- [vocabSemantics (getAccountTitle base)]+ , asemDivisionSemantics semantics `elem`+ [StatementDivision Revenue, StatementDivision Cost]+ , FixedHomeSide home <- [asemHomeSideSemantics semantics]+ , whichSide base /= home+ ]+ where+ postingCapability :: b -> PostingCapability+ postingCapability = maybe NotPostable asemPostingCapability . vocabSemantics . getAccountTitle
src/ExchangeAlgebra/Accounting/Catalog.hs view
@@ -240,6 +240,10 @@ -- ^ Base whose balance closing could not close. With the exact -- t'MoneyDecimal' value type this does not occur; it keeps the -- closing builder total.+ | ClosingTargetRejected AccountTitles Closing.ClosingTargetViolation+ -- ^ Closing target and its first failed check. 'RetainedEarnings'+ -- satisfies the closing-target law, so this does not occur; it keeps+ -- the closing builder total. deriving (Eq, Show) -- * Metadata and parameter checks@@ -494,8 +498,10 @@ generated (Bookkeeping.priorPeriodErrorCorrection mk current prior expense asset) FinalStockCall -> case Closing.closingEntries ledger of Right entries -> generated entries- Left (NonFiniteBalance base) -> Left (ClosingFailed base)- Left (NonFiniteResult _ _ base) -> Left (ClosingFailed base)+ Left (Closing.InvalidClosingTarget title violation) ->+ Left (ClosingTargetRejected title violation)+ Left (Closing.ClosingTransferError (NonFiniteBalance base)) -> Left (ClosingFailed base)+ Left (Closing.ClosingTransferError (NonFiniteResult _ _ base)) -> Left (ClosingFailed base) StraightLineCall asset amount method -> generated (depreciationEntry method asset amount) ConsolidateCall entities eliminations -> let selected = map snd (consolidationKeys entities eliminations)
src/ExchangeAlgebra/Accounting/Closing.hs view
@@ -14,6 +14,12 @@ an existing ledger; use 'settleEntries' for signed nets already computed by the caller. Both preserve the base components other than the account title of each source. +Both close into the 'closingTarget' of the base's title vocabulary+('RetainedEarnings' for 'AccountTitles'). Before reading any input, both check+that target with 'closingTargetViolation' and reject a vocabulary that breaks+the closing-target law, so a model's own title type cannot close into a+revenue, cost, or contra title.+ Import this module qualified alongside "ExchangeAlgebra.Algebra.Core": > import qualified ExchangeAlgebra.Accounting.Closing as Closing@@ -40,25 +46,59 @@ * Preconditions: valid Hat\/Not postings; the ledger includes only entries through the closing date and the call returns @Right entries@. * Relation: adding the entries closes each eligible complete base exactly.- Each reversal has an equal retained-earnings posting on the side selected- by 'closingSide'; non-closing bases and base components other than the account title are retained.-* Observation: exact net per complete base, including 'RetainedEarnings'.+ Each reversal has an equal term at the vocabulary's 'closingTarget' on+ the side selected by 'closingSide'. It keeps the source's base components+ other than the account title. For each combination of those components, the+ exact net of @x .+ entries@ is zero at every closed source. At the closing target it is+ the net of @x@ there plus the sum of @direction * net@ over the closed+ sources, where @direction@ is +1 for 'ClosingKeep' and -1 for+ 'ClosingFlip'; every other base keeps its net in @x@.+* Observation: exact Not-minus-Hat net per base without Hat\/Not, including+ the closing target. * Tolerance: none; the 'HatVal' accumulator and 'splitAccum' preserve exact nets.-* Instances: 'Double' and @MoneyDecimal@ with 'ExBaseClass' bases.+* Instances: 'Double' and @MoneyDecimal@ with 'ExBaseClass' bases whose+ vocabulary satisfies the closing-target law. +=== L2v: vocabulary renaming++* Subject: 'closingEntries' and 'settleEntries'.+* Preconditions: bases @b@ and @b'@ whose vocabularies satisfy the+ closing-target law, and an injective map @g :: BasePart b -> BasePart b'@+ that applies a title map @f@ and keeps every other base component, with+ @closingSide (f x) == closingSide x@ for every title @x@ and+ @f closingTarget == closingTarget@. 'ExchangeAlgebra.Algebra.Core.mapBasePart'+ applies @g@ to a ledger.+* Relation: @fmap (mapBasePart g) (closingEntries x)@ and+ @closingEntries (mapBasePart g x)@ are both @Right@ or both @Left@, and the+ @Right@ entries are equal under the observation. For 'settleEntries' with+ nets @m@ and @m'@ = @m@ with keys mapped by @g@, both results are @Right@ or+ both @Left@; for @Right@, the pairs are matched by source key: the pair of+ @g k@ in the second equals the pair of @k@ in the first mapped by+ @mapBasePart g@. The order of the pairs follows each base type's 'Ord'+ and is not preserved unless @g@ is strictly monotone; for @Left@, the+ reported base can differ for the same reason.+* Observation: @obs@; for 'settleEntries', @obs@ of each matched pair.+* Tolerance: none.+* Instances: 'AccountTitles' and a vocabulary that renames its closing target.+ === L3: balance * Subject: generated transfer and closing entries. * Preconditions: valid postings, concrete accounts, @Relabel@ rules whose actual target and source have equal 'whichSide'; finite totals. The transfer or closing operation being observed returns @Right entries@.+ For closing, the base's 'whatDiv' and 'isContra' agree with the title's+ vocabulary ('vocabDivision' and 'vocabContra'), as the 'ExBaseClass'+ defaults do: 'closingSide' reads the vocabulary, while @decL@ and @decR@+ read 'whichSide' of the base. * Relation: debit total equals credit total. Closing entries also satisfy this relation, because 'closingSide' follows the account's PIMO direction. * Observation: @norm (decL entries)@ and @norm (decR entries)@. * Tolerance: relative @1e-9@ for 'Double'; exact for @MoneyDecimal@.-* Instances: 'Double' and @MoneyDecimal@ with 'ExBaseClass' bases.+* Instances: 'Double' and @MoneyDecimal@ with 'StandardBase' bases, and+ with 'ExBaseClass' bases that keep the 'whatDiv' and 'isContra' defaults. -A relabel from @Not :< Cash@ to @Not :< Sales@ violates L3's side+A rule from @Not :< Cash@ to @Not :< Sales@ violates L3's side precondition: its cancellation and destination are both credits. === L5: non-negativity@@ -75,6 +115,9 @@ -} module ExchangeAlgebra.Accounting.Closing ( ClosingSide(..) , closingSide+ , ClosingTargetViolation(..)+ , closingTargetViolation+ , ClosingError(..) , closingEntries , SettleRule , retainedEarningsRule@@ -98,13 +141,13 @@ ) import ExchangeAlgebra.Algebra.Base.Representation (HatBaseClass(..), Hat(..)) import ExchangeAlgebra.Algebra.Value.Class (HatVal(..), isErrorValue)+import ExchangeAlgebra.Algebra.Element.Representation (Element(..)) import ExchangeAlgebra.Accounting.Exchange (ExBaseClass(..)) import ExchangeAlgebra.Accounting.Account ( AccountTitles(..)- , accountSpec- , asClosing+ , AccountDivision(..)+ , AccountSpec(..)+ , AccountVocabulary(..) , ClosingRule(..)- , classifyAccountDivision- , classifyAccountContra , pimoFromDivision , pimoFlip , PIMO(..)@@ -113,7 +156,7 @@ -- * Closing entries --- | The retained-earnings side selected by a closing account's PIMO direction.+-- | The closing-target side selected by a closing account's PIMO direction. data ClosingSide = ClosingKeep -- ^ IN: retain Hat/Not (revenue or contra cost). | ClosingFlip -- ^ OUT: reverse Hat/Not (cost or contra revenue).@@ -123,23 +166,78 @@ instance Hashable ClosingSide --- | Select the retained-earnings direction for an account eligible for closing.--- Registry NoClose accounts, including NetIncome and NetLoss, are excluded.-closingSide :: AccountTitles -> Maybe ClosingSide-closingSide title = case accountSpec title of+-- | Select the closing-target direction for an account eligible for closing.+-- The direction follows the title's division in 'vocabSpec', flipped for a+-- contra account ('vocabContra'). Three kinds of title are excluded: titles+-- whose specification has 'NoClose' (for 'AccountTitles', NetIncome and+-- NetLoss among others); titles with 'CloseByDivision' whose direction is+-- neither IN nor OUT (asset, liability, and equity titles, including+-- 'RetainedEarnings', whose direction is PS or MS); and titles without a+-- specification, including the wildcard.+-- For 'AccountTitles' the result is the same as before the generalization.+{-# INLINABLE closingSide #-}+{-# SPECIALIZE closingSide :: AccountTitles -> Maybe ClosingSide #-}+closingSide :: AccountVocabulary t => t -> Maybe ClosingSide+closingSide title = case vocabSpec title of Nothing -> Nothing Just spec -> case asClosing spec of NoClose -> Nothing- CloseByDivision -> case direction of+ CloseByDivision -> case direction spec of IN -> Just ClosingKeep OUT -> Just ClosingFlip _ -> Nothing where- direction- | classifyAccountContra title = pimoFlip ordinaryDirection- | otherwise = ordinaryDirection- ordinaryDirection = pimoFromDivision (classifyAccountDivision title)+ direction spec+ | vocabContra title = pimoFlip (pimoFromDivision (asDivision spec))+ | otherwise = pimoFromDivision (asDivision spec) +-- | The first check that a title fails as a closing target.+data ClosingTargetViolation+ = ClosingTargetIsWildcard+ -- ^ The title is the vocabulary's wildcard ('isWildcard').+ | ClosingTargetWithoutSpec+ -- ^ 'vocabSpec' returns 'Nothing' for the title.+ | ClosingTargetNotEquity AccountDivision+ -- ^ The title's division, which is not 'Equity'.+ | ClosingTargetIsContra+ -- ^ The title is an equity contra account ('vocabContra').+ deriving (Eq, Show)++-- | Check a title against the closing-target law of 'AccountVocabulary'.+-- The checks run in this order: the title is not the wildcard+-- ('isWildcard', never the symmetric '.=='), it has a specification, its+-- division is 'Equity', and it is not a contra account. The result is the+-- first failed check, or 'Nothing' when the title can receive closing+-- balances. 'closingEntries' and 'settleEntries' apply it to 'closingTarget'.+--+-- >>> closingTargetViolation RetainedEarnings+-- Nothing+-- >>> closingTargetViolation Sales+-- Just (ClosingTargetNotEquity Revenue)+-- >>> closingTargetViolation AccountTitle+-- Just ClosingTargetIsWildcard+{-# INLINABLE closingTargetViolation #-}+closingTargetViolation :: AccountVocabulary t => t -> Maybe ClosingTargetViolation+closingTargetViolation title+ | isWildcard title = Just ClosingTargetIsWildcard+ | otherwise = case vocabSpec title of+ Nothing -> Just ClosingTargetWithoutSpec+ Just spec+ | asDivision spec /= Equity -> Just (ClosingTargetNotEquity (asDivision spec))+ | vocabContra title -> Just ClosingTargetIsContra+ | otherwise -> Nothing++-- | Failures of 'closingEntries'.+data ClosingError v b+ = InvalidClosingTarget (TitleOf b) ClosingTargetViolation+ -- ^ The vocabulary's 'closingTarget' and its first failed check.+ -- Reported before the ledger is read, so every ledger, including the+ -- empty one, gives this result.+ | ClosingTransferError (TransferApplyError v b)+ -- ^ A balance that cannot be closed: 'NonFiniteBalance' with the base.++deriving instance (Show v, Show b, Show (TitleOf b)) => Show (ClosingError v b)+ -- | Generate closing entries that close each eligible base exactly. -- Supply only postings through the closing date. For each base whose account -- has a 'closingSide', the Hat and Not values are accumulated without@@ -147,29 +245,45 @@ -- winning side. A zero net generates nothing. Otherwise 'splitAccum' splits -- the exact magnitude into finite positive values @d1 >= d2 >= ... >= dk@ -- whose exact sum is the net, and each @di@ becomes one pair: the reversal of--- the base and the posting to 'RetainedEarnings'. @k = 1@ whenever the net is+-- the base and the posting to the vocabulary's 'closingTarget'+-- ('RetainedEarnings' for 'AccountTitles'). @k = 1@ whenever the net is -- representable in the value type. The pairs are not compressed back into one -- pair, so the exact net of every closed base after the entries is zero. -- This folds the source sequences (audit detail) per base, but preserves -- separate target postings from distinct source accounts. It does not call -- @bar@. All base components other than the account title are retained, and no note is attached. ----- 'NonFiniteBalance' is returned when an eligible base has a posting value+-- The closing target is checked first: when @closingTargetViolation+-- closingTarget == Just r@, the result is @Left (InvalidClosingTarget+-- closingTarget r)@ for every ledger, including the empty one.+-- @'ClosingTransferError' ('NonFiniteBalance' base)@ is returned when an+-- eligible base has a posting value -- for which 'valueError' is 'Just' (non-finite or negative), or when its net -- cannot be split ('splitAccum' returns 'Nothing': the rounded net is not -- finite). Side sums beyond the value type's range succeed when the exact -- net is in range. The reported base is the first in ascending 'Ord' order -- after normalizing Hat/Not to Not. No partial result is returned.+-- 'NonFiniteResult' is never returned. --+-- For 'AccountTitles' bases, @Right@ results are equal to those before the+-- generalization, and each former @Left e@ is now @Left (ClosingTransferError e)@.+-- -- Laws (exact arithmetic; observed with 'exactAccum'): for every closed base -- the exact net of @x .+ c@ is zero, where @Right c = closingEntries x@; -- the entries of @c@ have equal exact debit and credit sums; and--- @closingEntries (x .+ c) == Right Zero@.+-- @closingEntries (x .+ c)@ returns @Right z@ with @isZero z@. -- Balance collection is O(s log b), for s postings and b eligible bases.+{-# INLINABLE closingEntries #-} closingEntries :: forall v b. (HatVal v, ExBaseClass b)- => Alg v b -> Either (TransferApplyError v b) (Alg v b)-closingEntries = Map.foldlWithKey' close (Right Zero) . foldEntries collect Map.empty+ => Alg v b -> Either (ClosingError v b) (Alg v b)+closingEntries ledger = case closingTargetViolation target of+ Just violation -> Left (InvalidClosingTarget target violation)+ Nothing -> either (Left . ClosingTransferError) Right+ (Map.foldlWithKey' close (Right Zero) (foldEntries collect Map.empty ledger)) where+ target :: TitleOf b+ target = closingTarget+ collect :: Map b (Bool, Accum v, Accum v) -> v -> b -> Map b (Bool, Accum v, Accum v) collect balances value source = case (hat source, closingSide (getAccountTitle source)) of@@ -208,7 +322,7 @@ Just values -> case closingSide (getAccountTitle balanceBase) of Nothing -> Right Zero Just side -> Right $ mconcat- [ closingPairBy (targetSide side) RetainedEarnings value balanceBase+ [ closingPairBy (targetSide side) target value balanceBase | value <- values ] targetSide :: ClosingSide -> b -> b@@ -216,14 +330,16 @@ ClosingKeep -> id ClosingFlip -> revHat --- | A closing rule containing only its destination account title.--- The private constructor restricts destinations to accounts compatible with--- the closing directions.-newtype SettleRule = SettleRule AccountTitles+-- | A rule that closes eligible accounts into the vocabulary's 'closingTarget'.+-- It carries no title: 'settleEntries' reads the destination from the base+-- type it is called at and checks it with 'closingTargetViolation'. The+-- constructor is private.+data SettleRule = SettleRule --- | Close eligible accounts into 'RetainedEarnings', preserving all other base components.+-- | Close eligible accounts into the vocabulary's 'closingTarget'+-- ('RetainedEarnings' for 'AccountTitles'), preserving all other base components. retainedEarningsRule :: SettleRule-retainedEarningsRule = SettleRule RetainedEarnings+retainedEarningsRule = SettleRule -- | Settlement pairs in strictly ascending source-base order. -- A model returns only @Posting@ built with @entry@ and 'Monoid'. Settlement@@ -240,11 +356,18 @@ -- As a type synonym, it does not enforce finiteness or any numeric range. type SignedNet = Double --- | The first non-finite input net, identified by its complete base.-data SettleError b = NonFiniteNet (BasePart b)+-- | Failures of 'settleEntries'.+data SettleError b+ = NonFiniteNet (BasePart b)+ -- ^ The first non-finite input net, identified by its+ -- complete base.+ | InvalidSettleTarget (TitleOf b) ClosingTargetViolation+ -- ^ The vocabulary's 'closingTarget' and its first failed check.+ -- Reported before any net is read, so every input map, including the+ -- empty one, gives this result. -deriving instance Eq (BasePart b) => Eq (SettleError b)-deriving instance Show (BasePart b) => Show (SettleError b)+deriving instance (Eq (BasePart b), Eq (TitleOf b)) => Eq (SettleError b)+deriving instance (Show (BasePart b), Show (TitleOf b)) => Show (SettleError b) -- | Construct one reversal and destination pair per eligible source base. -- Input values are signed Not-minus-Hat nets. Zero nets, accounts without a@@ -252,8 +375,11 @@ -- finite, non-negative magnitudes equal to the absolute input net; the source -- reversal cancels that net exactly. Other base components are preserved. ----- A non-finite input, including at an excluded key, returns 'Left' with the--- first key in ascending order. Finite magnitudes above+-- The destination is the vocabulary's 'closingTarget'. It is checked first:+-- when @closingTargetViolation closingTarget == Just r@, the result is+-- @Left (InvalidSettleTarget closingTarget r)@ for every input map.+-- A non-finite input, including at an excluded key, returns 'NonFiniteNet' with+-- the first key in ascending order. Finite magnitudes above -- 'ExchangeAlgebra.Algebra.Value.postingUpperBound' are accepted, without passing -- through 'ExchangeAlgebra.Algebra.Posting.posted'. No implicit @bar@ or @compress@ is -- applied. Complexity: O(b) for b input bases.@@ -263,15 +389,21 @@ -- @direction@ is +1 for 'ClosingKeep' and -1 for 'ClosingFlip'. -- Observation: sums of @decL@ and @decR@ lifted to Rational for each pair. -- Tolerance: exact. Instances: 'ExBaseClass' bases with Double posting values.+-- For 'AccountTitles' bases the results are equal to those before the+-- generalization.+{-# INLINABLE settleEntries #-} settleEntries :: forall b. ExBaseClass b => SettleRule -> Map (BasePart b) SignedNet -> Either (SettleError b) (SettlementBatch b)-settleEntries (SettleRule destination) amounts- = case mapMaybe nonFinite (Map.toAscList amounts) of+settleEntries SettleRule amounts = case closingTargetViolation destination of+ Just violation -> Left (InvalidSettleTarget destination violation)+ Nothing -> case mapMaybe nonFinite (Map.toAscList amounts) of first : _ -> Left (NonFiniteNet first) [] -> Right (SettlementBatch (mapMaybe close (Map.toAscList amounts))) where+ destination :: TitleOf b+ destination = closingTarget finite amount = not (isNaN amount || isInfinite amount) nonFinite (coordinates, amount) | finite amount = Nothing@@ -305,7 +437,7 @@ -- finite posting contract of '.@'. closingPairBy :: (HatVal v, ExBaseClass b) => (b -> b)- -> AccountTitles+ -> TitleOf b -> v -> b -> Alg v b
src/ExchangeAlgebra/Accounting/Consolidation.hs view
@@ -1,4 +1,7 @@ {-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -Wincomplete-patterns -Werror=incomplete-patterns #-} {- |@@ -34,10 +37,10 @@ >>> import ExchangeAlgebra.Accounting.Account.Title (AccountTitles(..)) >>> import ExchangeAlgebra.Accounting.Statements.Metric (PeriodResult(..)) >>> import ExchangeAlgebra.Algebra.Value (MoneyDecimal)->>> type TrialBalance = Algebra.Alg MoneyDecimal (HatBase AccountTitles)+>>> import ExchangeAlgebra.Accounting.TrialBalance.Balance (TrialBalance) >>> let cash amount = amount Algebra..@ (Not :< Cash) >>> let equity amount = amount Algebra..@ (Not :< CapitalStock)->>> let capital amount = cash amount Algebra..+ equity amount :: TrialBalance+>>> let capital amount = cash amount Algebra..+ equity amount :: TrialBalance MoneyDecimal >>> let periodResult = PeriodBreakEven :: PeriodResult MoneyDecimal >>> let resultColumns = WorksheetLinkage periodResult periodResult periodResult >>> let retainedColumns = resultColumns NoBalance 0 NoBalance NoBalance@@ -56,12 +59,17 @@ -} module ExchangeAlgebra.Accounting.Consolidation ( LinkField(..)- , TrialBalanceSource(..)- , WorksheetAdjustment(..)+ , TrialBalanceSource+ , TrialBalanceSourceOf(..)+ , WorksheetAdjustment+ , WorksheetAdjustmentOf(..) , WorksheetLinkage(..)- , WorksheetInput(..)- , WorksheetError(..)+ , WorksheetInput+ , WorksheetInputOf(..)+ , WorksheetError+ , WorksheetErrorOf(..) , ValidatedWorksheet+ , ValidatedWorksheetOf , validateConsolidationWorksheet , validatedSources , validatedAdjustments@@ -73,7 +81,7 @@ import qualified Data.List as L import qualified Data.Map.Strict as M -import ExchangeAlgebra.Accounting.Exchange (decL, decR)+import ExchangeAlgebra.Accounting.Exchange (ExBaseClass(TitleOf), decL, decR) import ExchangeAlgebra.Algebra.Core.Representation ( Alg , Redundant((.+)), foldEntries@@ -84,13 +92,18 @@ import ExchangeAlgebra.Accounting.Account.PostingPolicy ( ProcessingContext(ConsolidationWorksheet) , postingAllowedIn- , postingCapabilityFor ) import ExchangeAlgebra.Accounting.Account.Classification- ( PostingCapability )-import ExchangeAlgebra.Accounting.Account.Title (AccountTitles(..))+ ( PostingCapability(NotPostable) )+import ExchangeAlgebra.Accounting.Account.Registry+ ( AccountSemantics(asemPostingCapability) )+import ExchangeAlgebra.Accounting.Account.Vocabulary+ ( AccountVocabulary(vocabSemantics) )+import ExchangeAlgebra.Accounting.Account.Title (AccountTitles) import ExchangeAlgebra.Algebra.Base.Representation- ( Hat(..), HatBase((:<)) )+ ( BaseClass, Hat(..), HatBase((:<)) )+import ExchangeAlgebra.Algebra.Element.Representation+ ( HasElementKeys, Element(isWildcard) ) import ExchangeAlgebra.Accounting.Statements.Metric (PeriodResult(..)) import ExchangeAlgebra.Accounting.TrialBalance.Balance ( AccountBalance(..)@@ -118,22 +131,32 @@ -- balance is accepted as historical input and is therefore not restricted by -- a processing-context posting-capability gate; it is still checked for -- base structure, valid values, and exact balance.-data TrialBalanceSource source v = TrialBalanceSource+data TrialBalanceSourceOf t source v = TrialBalanceSource { _sourceId :: source- , _sourceTrialBalance :: Alg v (HatBase AccountTitles)+ , _sourceTrialBalance :: Alg v (HatBase t) }- deriving (Show) --- | One atomic worksheet adjustment. The member of the redundant algebra need not originate--- from a journal entry, but it must be independently balanced and use only--- components admitted by the consolidation processing context.-data WorksheetAdjustment source adjustment v = WorksheetAdjustment+deriving instance (HatVal v, BaseClass t, HasElementKeys t, Show source)+ => Show (TrialBalanceSourceOf t source v)++-- | A source trial balance for the built-in chart of accounts.+type TrialBalanceSource = TrialBalanceSourceOf AccountTitles++-- | One atomic worksheet adjustment. A member of the redundant algebra represents+-- the adjustment and can be prepared independently of a journal entry. The adjustment+-- must balance on its own and use account titles admitted by the consolidation context.+data WorksheetAdjustmentOf t source adjustment v = WorksheetAdjustment { _adjustmentId :: adjustment , _adjustmentSourceIds :: NonEmpty source- , _adjustmentElement :: Alg v (HatBase AccountTitles)+ , _adjustmentElement :: Alg v (HatBase t) }- deriving (Show) +deriving instance (HatVal v, BaseClass t, HasElementKeys t, Show source, Show adjustment)+ => Show (WorksheetAdjustmentOf t source adjustment v)++-- | A worksheet adjustment for the built-in chart of accounts.+type WorksheetAdjustment = WorksheetAdjustmentOf AccountTitles+ -- | Cross-column equations for the statement of profit or loss (P/L), -- statement of changes in equity (S/S), and balance sheet (B/S). --@@ -166,15 +189,20 @@ deriving (Show, Eq) -- | Unvalidated consolidation worksheet input.-data WorksheetInput source adjustment v = WorksheetInput- { _worksheetSources :: NonEmpty (TrialBalanceSource source v)- , _worksheetAdjustments :: [WorksheetAdjustment source adjustment v]+data WorksheetInputOf t source adjustment v = WorksheetInput+ { _worksheetSources :: NonEmpty (TrialBalanceSourceOf t source v)+ , _worksheetAdjustments :: [WorksheetAdjustmentOf t source adjustment v] , _worksheetLinkage :: WorksheetLinkage v }- deriving (Show) +deriving instance (HatVal v, BaseClass t, HasElementKeys t, Show source, Show adjustment)+ => Show (WorksheetInputOf t source adjustment v)++-- | Worksheet input for the built-in chart of accounts.+type WorksheetInput = WorksheetInputOf AccountTitles+ -- | Every rejected invariant is tied to a source, adjustment, or linkage.-data WorksheetError source adjustment v+data WorksheetErrorOf t source adjustment v = DuplicateSourceId source | DuplicateAdjustmentId adjustment | DuplicateAdjustmentSource adjustment source@@ -187,7 +215,7 @@ | InvalidAdjustmentValue adjustment v | WildcardAdjustmentAccount adjustment | WildcardAdjustmentSide adjustment- | AdjustmentPostingNotAllowed adjustment AccountTitles PostingCapability+ | AdjustmentPostingNotAllowed adjustment t PostingCapability | UnbalancedAdjustment adjustment v v | InvalidLinkAmount LinkField v | NetIncomeAttributionMismatch v v@@ -200,19 +228,37 @@ (AccountBalance v) (AccountBalance v) deriving (Show, Eq) +-- | A validation error for the built-in chart of accounts.+type WorksheetError = WorksheetErrorOf AccountTitles+ -- | A worksheet whose provenance, atomic balance, processing capability, and -- cross-column linkage have all passed validation. The constructor is hidden.-data ValidatedWorksheet source adjustment v = ValidatedWorksheet- (NonEmpty (TrialBalanceSource source v))- [WorksheetAdjustment source adjustment v]+data ValidatedWorksheetOf t source adjustment v = ValidatedWorksheet+ (NonEmpty (TrialBalanceSourceOf t source v))+ [WorksheetAdjustmentOf t source adjustment v] (WorksheetLinkage v) +-- | A validated worksheet for the built-in chart of accounts.+type ValidatedWorksheet = ValidatedWorksheetOf AccountTitles+ -- | Validate a consolidation worksheet without normalizing any algebra term.+-- The worksheet totals debits and credits using the base's @whichSide@.+-- To obtain totals consistent with the vocabulary, use its division and+-- contra flag when classifying the base.+-- Supply eliminations of reciprocal accounts as worksheet adjustments.+--+-- For each concrete title used in an adjustment, supply its posting capability+-- through 'vocabSemantics'. An omitted capability counts as 'NotPostable'.+-- If @vocabSpec t == Nothing@ for a concrete title @t@, evaluating the default+-- @vocabDivision t@ raises an exception. Results are unspecified for instances+-- that violate the vocabulary laws. validateConsolidationWorksheet- :: (HatVal v, Ord source, Ord adjustment)- => WorksheetInput source adjustment v- -> Either (NonEmpty (WorksheetError source adjustment v))- (ValidatedWorksheet source adjustment v)+ :: ( HatVal v, ExBaseClass (HatBase t), TitleOf (HatBase t) ~ t+ , Ord source, Ord adjustment+ )+ => WorksheetInputOf t source adjustment v+ -> Either (NonEmpty (WorksheetErrorOf t source adjustment v))+ (ValidatedWorksheetOf t source adjustment v) validateConsolidationWorksheet input = case errors of [] -> Right (ValidatedWorksheet sources adjustments linkage)@@ -228,19 +274,19 @@ -- | Recover the source trial balances with their provenance intact. validatedSources- :: ValidatedWorksheet source adjustment v- -> NonEmpty (TrialBalanceSource source v)+ :: ValidatedWorksheetOf t source adjustment v+ -> NonEmpty (TrialBalanceSourceOf t source v) validatedSources (ValidatedWorksheet sources _ _) = sources -- | Recover the atomic adjustments with their provenance intact. validatedAdjustments- :: ValidatedWorksheet source adjustment v- -> [WorksheetAdjustment source adjustment v]+ :: ValidatedWorksheetOf t source adjustment v+ -> [WorksheetAdjustmentOf t source adjustment v] validatedAdjustments (ValidatedWorksheet _ adjustments _) = adjustments -- | Recover the validated cross-column linkage values. validatedLinkage- :: ValidatedWorksheet source adjustment v+ :: ValidatedWorksheetOf t source adjustment v -> WorksheetLinkage v validatedLinkage (ValidatedWorksheet _ _ linkage) = linkage @@ -249,9 +295,9 @@ -- calculation projection; inspect the validated source and adjustment lists -- when provenance is required. combinedWorksheet- :: (HatVal v)- => ValidatedWorksheet source adjustment v- -> Alg v (HatBase AccountTitles)+ :: (HatVal v, BaseClass t, HasElementKeys t)+ => ValidatedWorksheetOf t source adjustment v+ -> Alg v (HatBase t) combinedWorksheet (ValidatedWorksheet sources adjustments _) = L.foldl' (.+) mempty (map _sourceTrialBalance (toListNE sources)@@ -259,9 +305,9 @@ duplicateIdErrors :: (Ord source, Ord adjustment)- => NonEmpty (TrialBalanceSource source v)- -> [WorksheetAdjustment source adjustment v]- -> [WorksheetError source adjustment v]+ => NonEmpty (TrialBalanceSourceOf t source v)+ -> [WorksheetAdjustmentOf t source adjustment v]+ -> [WorksheetErrorOf t source adjustment v] duplicateIdErrors sources adjustments = [ DuplicateSourceId sourceId | (sourceId, count) <- M.toList sourceCounts@@ -278,14 +324,14 @@ [ (_adjustmentId adjustment, 1 :: Int) | adjustment <- adjustments ] sourceIds :: Ord source- => NonEmpty (TrialBalanceSource source v)+ => NonEmpty (TrialBalanceSourceOf t source v) -> M.Map source () sourceIds = M.fromList . map (\source -> (_sourceId source, ())) . toListNE validateSource- :: HatVal v- => TrialBalanceSource source v- -> [WorksheetError source adjustment v]+ :: (HatVal v, ExBaseClass (HatBase t))+ => TrialBalanceSourceOf t source v+ -> [WorksheetErrorOf t source adjustment v] validateSource source = structuralErrors ++ balanceErrors where sourceId = _sourceId source@@ -296,7 +342,8 @@ , isErrorValue value ] ++ [ WildcardSourceAccount sourceId- | _ :< AccountTitle <- bases alg+ | _ :< title <- bases alg+ , isWildcard title ] ++ [ WildcardSourceSide sourceId | HatNot :< _ <- bases alg@@ -312,10 +359,10 @@ credit = roundAccum creditState validateAdjustment- :: (HatVal v, Ord source)+ :: (HatVal v, ExBaseClass (HatBase t), TitleOf (HatBase t) ~ t, Ord source) => M.Map source ()- -> WorksheetAdjustment source adjustment v- -> [WorksheetError source adjustment v]+ -> WorksheetAdjustmentOf t source adjustment v+ -> [WorksheetErrorOf t source adjustment v] validateAdjustment knownSources adjustment = provenanceErrors ++ structuralErrors ++ balanceErrors where@@ -328,15 +375,16 @@ , isErrorValue value || not (value > 0) ] ++ [ WildcardAdjustmentAccount adjustmentId- | _ :< AccountTitle <- bases alg+ | _ :< title <- bases alg+ , isWildcard title ] ++ [ WildcardAdjustmentSide adjustmentId | HatNot :< _ <- bases alg ] ++ [ AdjustmentPostingNotAllowed adjustmentId account capability | _ :< account <- bases alg- , account /= AccountTitle- , let capability = postingCapabilityFor account+ , not (isWildcard account)+ , let capability = postingCapabilityOf account , not (postingAllowedIn ConsolidationWorksheet capability) ] refs = toListNE (_adjustmentSourceIds adjustment)@@ -360,10 +408,13 @@ debit = roundAccum debitState credit = roundAccum creditState +postingCapabilityOf :: AccountVocabulary t => t -> PostingCapability+postingCapabilityOf = maybe NotPostable asemPostingCapability . vocabSemantics+ validateWorksheetLinkage :: HatVal v => WorksheetLinkage v- -> [WorksheetError source adjustment v]+ -> [WorksheetErrorOf t source adjustment v] validateWorksheetLinkage linkage | not (null invalidAmounts) = invalidAmounts | otherwise = attributionErrors@@ -517,7 +568,8 @@ (openingDebit, openingCredit) = balancePair opening (closingDebit, closingCredit) = balancePair closing -sideTotals :: HatVal v => Alg v (HatBase AccountTitles) -> (Accum v, Accum v)+sideTotals :: (HatVal v, ExBaseClass (HatBase t))+ => Alg v (HatBase t) -> (Accum v, Accum v) sideTotals alg = (sumSide (decL alg), sumSide (decR alg)) where sumSide = foldEntries (\total value _ -> addAccum value total) emptyAccum
src/ExchangeAlgebra/Accounting/Entries.hs view
@@ -1,9 +1,10 @@+{-# LANGUAGE TypeFamilies #-} {- | Module : ExchangeAlgebra.Accounting.Entries Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license Package for Exchange Algebra defined by Hiroshi Deguchi. @@ -80,7 +81,8 @@ import ExchangeAlgebra.Accounting.Account.Title (AccountTitles(..)) import ExchangeAlgebra.Accounting.Exchange- ( ExBaseClass+ ( StandardBase+ , ExBaseClass , Exchange(decL, decR) , projByAccountTitle )@@ -560,7 +562,7 @@ -- 2038000 -- -- Complexity: O(s) (s = number of scalar entries in the accumulated algebra)-equityMethodBalance :: (HatVal v, ExBaseClass b) => Alg v b -> v+equityMethodBalance :: (HatVal v, StandardBase b) => Alg v b -> v equityMethodBalance = norm . bar . projByAccountTitle InvestmentInAssociate ------------------------------------------------------------------
src/ExchangeAlgebra/Accounting/Exchange.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE ConstraintKinds #-}+{-# LANGUAGE UndecidableSuperClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE FlexibleInstances #-}@@ -42,8 +44,14 @@ -- "ExchangeAlgebra.Journal.Core". Accounting classes and projections are -- exported here, separately from the generic Algebra and Journal APIs. module ExchangeAlgebra.Accounting.Exchange ( ExBaseClass(..)+ , StandardBase , AccountBase(..) , Exchange(..)+ -- * Construction by debit or credit side+ , hatForSide+ , postingForSide+ , journalForSides+ -- * Projections , projCredit , projDebit , projByAccountTitle@@ -52,7 +60,7 @@ , projDeferredAssets , projCurrentLiability , projFixedLiability- , projCapitalStock+ , projNonContraCreditEquity , projContraAssets , projContra ) where@@ -63,13 +71,11 @@ , FixedCurrent(..) , PIMO(..) , AccountSpec(..)- , classifyAccountDivision- , classifyAccountContra+ , AccountVocabulary(..) , defaultSide , switchSide , pimoFromDivision , pimoFlip- , accountSpec ) import ExchangeAlgebra.Algebra.Base.Representation ( HatBaseClass(..) , HatBase(..)@@ -90,7 +96,14 @@ , (.@) , filter )-import qualified ExchangeAlgebra.Algebra.Core.Representation as EA (Alg(..), _hatBase, filter, foldEntries, foldPairs, Pair(..))+import qualified ExchangeAlgebra.Algebra.Core.Representation as EA+ ( Alg(..)+ , _hatBase+ , filter+ , foldEntries+ , foldPairs+ , Pair(..)+ ) import ExchangeAlgebra.Algebra.Value.Class (HatVal(..), Tolerance(..), isErrorValue) import qualified Data.Foldable as Foldable import ExchangeAlgebra.Algebra.Value (MoneyDouble, MoneyDecimal)@@ -103,33 +116,40 @@ -- Extended type class for bases that carry an account title. -- Provides access to and modification of account titles, account divisions, PIMO classification, -- credit/debit determination, and fixed/current classification.-class (HatBaseClass a) => ExBaseClass a where+--+-- * For a concrete title with a 'Not' or v'Hat' label, 'whichSide' must+-- return 'Debit' or 'Credit' (Definitions 7 and 8). Under 'Not' it returns+-- the home side determined by the base's 'whatDiv' and 'isContra'. Under+-- v'Hat' it returns the opposite side.+class (HatBaseClass a, AccountVocabulary (TitleOf a)) => ExBaseClass a where+ -- | Title type carried by this base. Existing instances default to 'AccountTitles'.+ type TitleOf a+ type TitleOf a = AccountTitles+ -- | Retrieve the account title from a base. Complexity: O(1)- getAccountTitle :: a -> AccountTitles+ getAccountTitle :: a -> TitleOf a -- | Change the account title of a base. Complexity: O(1)- setAccountTitle :: a -> AccountTitles -> a+ setAccountTitle :: a -> TitleOf a -> a -- | Account title setter operator. An alias for @setAccountTitle@. Complexity: O(1) {-# INLINE (.~) #-}- (.~) :: a -> AccountTitles -> a+ (.~) :: a -> TitleOf a -> a (.~) = setAccountTitle -- | Retrieve the account division (Assets/Equity/Liability/Cost/Revenue). Complexity: O(1) {-# INLINE whatDiv #-} whatDiv :: a -> AccountDivision- whatDiv = classifyAccountDivision . getAccountTitle+ whatDiv = vocabDivision . getAccountTitle -- | Whether the account is a contra account (評価勘定等): its home side -- and PIMO direction are the reverse of its division's defaults.- -- Delegates to the registry ('classifyAccountContra') exactly like- -- 'whatDiv' delegates to 'classifyAccountDivision' — a constant default- -- would disconnect the registry flag from every built-in instance.+ -- The default reads the contra flag from the account vocabulary. -- Contract: @isContra b == (homeSide of b \/= defaultSide (whatDiv b))@. -- Complexity: O(1) {-# INLINE isContra #-} isContra :: a -> Bool- isContra = classifyAccountContra . getAccountTitle+ isContra = vocabContra . getAccountTitle -- | Retrieve the PIMO direction (PS/IN/MS/OUT; see 'PIMO' for the -- original semantics). Derived from the division via 'pimoFromDivision',@@ -167,9 +187,12 @@ -- Complexity: O(1) {-# INLINE fixedCurrent #-} fixedCurrent :: a -> FixedCurrent- fixedCurrent b = maybe Other asFixedCurrent (accountSpec (getAccountTitle b))+ fixedCurrent b = maybe Other asFixedCurrent (vocabSpec (getAccountTitle b)) +-- | A base whose titles belong to the built-in account registry.+type StandardBase b = (ExBaseClass b, TitleOf b ~ AccountTitles)+ -- | Type class for determining correspondences between account divisions. -- Tests whether two account divisions form a pair in double-entry bookkeeping -- (e.g., Assets <=> Liability).@@ -215,8 +238,6 @@ -- *** Name only (redundant algebra base) -- *** CountUnit only (redundant algebra base)--- *** Day only (redundant algebra base)--- *** TimeOfDay only (redundant algebra base) -- *** @@ -224,10 +245,6 @@ -- | Basic BaseClass with 2 elements -instance ExBaseClass (HatBase (AccountTitles, Day)) where- getAccountTitle (_:< (a, _)) = a- setAccountTitle (h:< (_, d)) b = h:< (b, d)- instance ExBaseClass (HatBase (AccountTitles, Name)) where getAccountTitle (_:< (a, _)) = a setAccountTitle (h:< (_, n)) b = h:< (b, n)@@ -248,25 +265,11 @@ getAccountTitle (_:< (a, _, _, _)) = a setAccountTitle (h:< (_, n, c, s)) b = h:< (b, n, c, s) --- ** 5-element bases--- | Basic BaseClass with 5 elements-instance ExBaseClass (HatBase (AccountTitles, Name, CountUnit, Subject, Day)) where- getAccountTitle (_:< (a, _, _, _, _)) = a- setAccountTitle (h:< (_, n, c, s, d)) b = h:< (b, n, c, s, d)----- ** 6-element bases--- | Basic BaseClass with 6 elements-instance ExBaseClass (HatBase (AccountTitles, Name, CountUnit, Subject, Day, TimeOfDay)) where- getAccountTitle (_:< (a, _, _, _, _, _)) = a- setAccountTitle (h:< (_, n, c, s, d, t)) b = h:< (b, n, c, s, d, t)- -- ** Bases with wildcard-extended dates and times ----- The bases above use the 'Element' instances of 'Day' and t'TimeOfDay', whose--- wildcards are reserved dates and times (1858-11-17 and midnight). The--- following bases use t'Wild' instead, so every date and time of day remains--- an ordinary element.+-- Built-in bases with dates or times use @Wild Day@ and @Wild TimeOfDay@.+-- Wrap a date or time in @Exactly@ to store it+-- as an ordinary element, including 1858-11-17 and midnight. -- -- @since 0.6.1.0 @@ -360,22 +363,90 @@ where credit = sequentialNorm (decR algebra) debit = sequentialNorm (decL algebra)- sequentialNorm = EA.foldPairs (\total _ (EA.Pair hats nots) ->- total + Foldable.foldl' (+) 0 hats + Foldable.foldl' (+) 0 nots) 0+ sequentialNorm = EA.foldPairs collect 0+ collect :: HatVal v => v -> bp -> EA.Pair v -> v+ collect total _ (EA.HatOne value) = total + (0 + value) + 0+ collect total _ (EA.NotOne value) = total + 0 + (0 + value)+ collect total _ (EA.PairSeq hats nots) =+ total + Foldable.foldl' (+) 0 hats + Foldable.foldl' (+) 0 nots -- | Exact credit minus debit, with structural Side contributing nothing. accountState :: forall n b. (HatVal n, ExBaseClass b) => Alg n b -> Accum n {-# INLINE accountState #-} accountState = EA.foldPairs collect emptyAccum where- collect total basePart (EA.Pair hats nots) =- mergeAccum total (mergeAccum (signed Hat hats) (signed Not nots))+ collect :: Accum n -> BasePart b -> EA.Pair n -> Accum n+ collect total basePart pair = mergeAccum total $ case pair of+ EA.HatOne value -> mergeAccum+ (signed Hat (addAccum value emptyAccum)) (signed Not emptyAccum)+ EA.NotOne value -> mergeAccum+ (signed Hat emptyAccum) (signed Not (addAccum value emptyAccum))+ EA.PairSeq hats nots -> mergeAccum+ (signed Hat (Foldable.foldl' (flip addAccum) emptyAccum hats))+ (signed Not (Foldable.foldl' (flip addAccum) emptyAccum nots)) where- signed side values = case whichSide (merge side basePart :: b) of- Credit -> Foldable.foldl' (flip addAccum) emptyAccum values- Debit -> negateAccum (Foldable.foldl' (flip addAccum) emptyAccum values)+ signed :: Hat -> Accum n -> Accum n+ signed side ~state = case whichSide (merge side basePart :: b) of+ Credit -> state+ Debit -> negateAccum state Side -> emptyAccum +-- * Construction by debit or credit side++-- | Choose 'Not' or v'Hat' to put a term on the requested side.+-- The base can include components besides the account title. The result is 'Not' when+-- @whichSide (Not :< key) == side@; otherwise it is v'Hat' (Definitions 7-9).+-- The wildcard v'Side' is compared by equality, just as in the input-conversion+-- helpers: it selects v'Hat' when the base with 'Not' has a concrete side.+-- It does not request a wildcard marker or guarantee a wildcard result.+--+-- >>> hatForSide Debit Cash+-- Not+-- >>> hatForSide Credit Sales+-- Not+hatForSide :: ExBaseClass (HatBase k) => Side -> k -> Hat+hatForSide side key+ | whichSide (Not :< key) == side = Not+ | otherwise = Hat++-- | Construct a term on the requested side while preserving every base component.+-- The amount must satisfy the non-negative, non-error value contract of '(.@)';+-- a violation raises that constructor's error. The marker is chosen by+-- 'hatForSide', including its treatment of the wildcard v'Side'.+--+-- >>> let posting = postingForSide Credit Cash 10 :: Alg Double (HatBase AccountTitles)+-- >>> whichSide (_hatBase posting) == Credit && _val posting == 10+-- True+-- >>> import qualified Data.Text as T+-- >>> import ExchangeAlgebra.Algebra.Element (CountUnit(..))+-- >>> let key = (Cash, T.pack "owner", Yen)+-- >>> type MultiBase = HatBase (AccountTitles, Name, CountUnit)+-- >>> let posting = postingForSide Credit key 10 :: Alg Double MultiBase+-- >>> _hatBase posting == Hat :< key && whichSide (_hatBase posting) == Credit+-- True+postingForSide :: (HatVal v, ExBaseClass (HatBase k))+ => Side+ -> k+ -> v+ -> Alg v (HatBase k)+postingForSide side key amount = amount .@ (hatForSide side key :< key)++-- | Combine triples of side, base without Hat\/Not, and amount with '(.+)'.+-- Every base component is preserved, and repeated terms on the same base+-- remain separate. The empty list gives the empty algebra. Debit/credit balance+-- is not enforced. Each triple has the value contract and wildcard-side behavior+-- of 'postingForSide'.+--+-- >>> import qualified ExchangeAlgebra.Algebra.Core as EA+-- >>> let entries = [(Debit, Cash, 10), (Debit, Cash, 20)]+-- >>> let journal = journalForSides entries :: Alg Double (HatBase AccountTitles)+-- >>> length (EA.toList journal) == 2 && norm journal == 30+-- True+journalForSides :: (HatVal v, ExBaseClass (HatBase k)) => [(Side, k, v)] -> Alg v (HatBase k)+journalForSides = foldr (\(side, key, amount) acc -> postingForSide side key amount .+ acc) mempty++-- * Projections+ ------------------------------------------------------------------ -- | Projects only the credit-side terms. For 'Alg' this coincides with the -- 'Exchange' class method 'decR' (R = Right = Credit, 貸方); the top-level name@@ -405,10 +476,10 @@ -- whose ledger title is the wildcard. -- -- Complexity: O(s) (s is the total number of scalar entries)-projByAccountTitle :: (HatVal n, ExBaseClass b) => AccountTitles -> Alg n b -> Alg n b+projByAccountTitle :: (HatVal n, ExBaseClass b) => TitleOf b -> Alg n b -> Alg n b projByAccountTitle at alg = filter (f at) alg where- f :: (HatVal n,ExBaseClass b) => AccountTitles -> Alg n b -> Bool+ f :: (HatVal n,ExBaseClass b) => TitleOf b -> Alg n b -> Bool f _ Zero = False f t x = matchesQuery t ((getAccountTitle ._hatBase) x) -- | Projects only current assets.@@ -511,9 +582,8 @@ . (filter (not . isContra . _hatBase)) . projCredit --- | Projects the credit-side terms of every non-contra account in the 'Equity'--- division, including 'CapitalStock', 'RetainedEarnings', and other equity--- accounts.+-- | Selects credit-side terms from all non-contra equity accounts, including+-- 'CapitalStock' and 'RetainedEarnings'. -- -- Selection predicate (over every scalar entry @x@ of the input, on the credit side): -- @whatDiv (_hatBase x) == Equity && not (isContra (_hatBase x))@.@@ -529,10 +599,10 @@ -- -- >>> type Test = Alg Double (HatBase AccountTitles) -- >>> x = 100.@Not:<CapitalStock .+ 30.@Not:<Cash .+ 20.@Not:<RetainedEarnings :: Test--- >>> norm (projCapitalStock x)+-- >>> norm (projNonContraCreditEquity x) -- 120.0-projCapitalStock :: (HatVal n, ExBaseClass b) => Alg n b -> Alg n b-projCapitalStock = (filter (\x -> (whatDiv . _hatBase) x == Equity))+projNonContraCreditEquity :: (HatVal n, ExBaseClass b) => Alg n b -> Alg n b+projNonContraCreditEquity = (filter (\x -> (whatDiv . _hatBase) x == Equity)) . (filter (not . isContra . _hatBase)) . projCredit
− src/ExchangeAlgebra/Accounting/PostingPolicy.hs
@@ -1,5 +0,0 @@--- | Policies for admitting postings to bookkeeping accounts.-module ExchangeAlgebra.Accounting.PostingPolicy {-# DEPRECATED "Use ExchangeAlgebra.Accounting.Account instead." #-} - ( ProcessingContext(..), postingAllowedIn, postingCapabilityFor ) where--import ExchangeAlgebra.Accounting.Account.PostingPolicy
src/ExchangeAlgebra/Accounting/Statements.hs view
@@ -16,11 +16,9 @@ +--------------------------------+--------------------------------------------+ 'present' accepts a trial balance over account titles and its stage, and-returns presentation results with their audit events. It does not alter-bookkeeping bases and does not judge whether the trial balance is normal-for accounting purposes; inspect-'ExchangeAlgebra.Accounting.TrialBalance.Validation.trialBalanceFindings' for-that audit.+returns presentation results with their audit events and leaves the+bookkeeping bases intact. Use "ExchangeAlgebra.Accounting.Audit" to+inspect accounting findings separately. Statements receive one reporting scope. A ledger with several components (entity, period, department) is narrowed by the caller and mapped to account titles@@ -30,7 +28,8 @@ -} module ExchangeAlgebra.Accounting.Statements ( PresentationGroup(..)- , PresentationGroupDef(..)+ , PresentationGroupDef+ , PresentationGroupDefOf(..) , defaultPresentationGrouping , presentationGroupOf , lookupGroupDef@@ -39,16 +38,20 @@ , RelativeAmount(..) , relativeTo , addGross- , GroupRowKind(..)- , GroupRow(..)- , GroupedPresentation(..)+ , GroupRowKind+ , GroupRowKindOf(..)+ , GroupRow+ , GroupRowOf(..)+ , GroupedPresentation+ , GroupedPresentationOf(..) , presentGroups , MetricId , mkMetricId , metricIdText , DerivedMetric(..) , PeriodResult(..)- , MetricError(..)+ , MetricError+ , MetricErrorOf(..) , metricForLegacyTitle , legacyTitlesForMetric , periodResultOfAlg@@ -57,21 +60,33 @@ , ReportingScope(..) , PresentationProfile(..) , StatementSection(..)- , StatementLine(..)- , PresentationAllocation(..)- , PresentationRelabel(..)- , MaterialityTreatment(..)- , MaterialityDecision(..)- , ContraPresentationRule(..)+ , StatementLine+ , StatementLineOf(..)+ , PresentationAllocation+ , PresentationAllocationOf(..)+ , PresentationRelabel+ , PresentationRelabelOf(..)+ , MaterialityTreatment+ , MaterialityTreatmentOf(..)+ , MaterialityDecision+ , MaterialityDecisionOf(..)+ , ContraPresentationRule+ , ContraPresentationRuleOf(..) , CustomMetricLabel(..) , SubtotalCoverage(..)- , SubtotalDefinition(..)+ , SubtotalDefinition+ , SubtotalDefinitionOf(..) , StatementSubtotal(..)- , ReportingContext(..)+ , ReportingContext+ , ReportingContextOf(..)+ , reportingContext , jcciSecondGradeContext- , PresentationAuditEvent(..)- , PresentationIssue(..)- , FinancialStatements(..)+ , PresentationAuditEvent+ , PresentationAuditEventOf(..)+ , PresentationIssue+ , PresentationIssueOf(..)+ , FinancialStatements+ , FinancialStatementsOf(..) , presentationLabel , metricLabel , present
src/ExchangeAlgebra/Accounting/Statements/Group.hs view
@@ -44,7 +44,8 @@ module ExchangeAlgebra.Accounting.Statements.Group ( -- * Groups PresentationGroup(..)- , PresentationGroupDef(..)+ , PresentationGroupDef+ , PresentationGroupDefOf(..) , defaultPresentationGrouping , presentationGroupOf , lookupGroupDef@@ -55,9 +56,12 @@ , relativeTo , addGross -- * Grouped rows- , GroupRowKind(..)- , GroupRow(..)- , GroupedPresentation(..)+ , GroupRowKind+ , GroupRowKindOf(..)+ , GroupRow+ , GroupRowOf(..)+ , GroupedPresentation+ , GroupedPresentationOf(..) , presentGroups ) where @@ -98,7 +102,7 @@ -- @pgGross@ member is; the test-suite pins both, together with the disjointness -- of the membership sets and the fact that every registry contra account -- belongs to exactly one group.-data PresentationGroupDef = PresentationGroupDef+data PresentationGroupDefOf t = PresentationGroupDef { pgKey :: PresentationGroup , pgDivision :: AccountDivision -- ^ Statement column the block belongs to. Fixes the group's normal@@ -106,8 +110,8 @@ , pgLabel :: Text -- ^ Label of the net line (and of the carried subtotal when this block -- rolls up into another one).- , pgGross :: [AccountTitles]- , pgDeductions :: [AccountTitles]+ , pgGross :: [t]+ , pgDeductions :: [t] , pgParent :: Maybe PresentationGroup -- ^ When set, this block's net is carried into the named block as a -- 'SubgroupRow' and only the outermost block contributes to the column@@ -116,9 +120,12 @@ } deriving (Show, Eq) +-- | Built-in chart specialization of 'PresentationGroupDefOf'.+type PresentationGroupDef = PresentationGroupDefOf AccountTitles+ -- | Normal (deduction-free) side of a group, i.e. the side its net line is -- stated against.-groupNormalSide :: PresentationGroupDef -> Side+groupNormalSide :: PresentationGroupDefOf t -> Side groupNormalSide = defaultSide . pgDivision -- | Default display groups for callers using 'presentGroups'.@@ -193,13 +200,19 @@ member def = title `elem` pgGross def || title `elem` pgDeductions def -- | Look one block up in the grouping in force.-lookupGroupDef :: [PresentationGroupDef] -> PresentationGroup -> Maybe PresentationGroupDef+lookupGroupDef+ :: [PresentationGroupDefOf t]+ -> PresentationGroup+ -> Maybe (PresentationGroupDefOf t) lookupGroupDef defs key = L.find ((== key) . pgKey) defs -- | Restrict a grouping to the statement columns a writer renders. A balance -- sheet must not net revenue accounts, and a profit and loss statement must -- not net asset accounts.-groupingForDivisions :: [AccountDivision] -> [PresentationGroupDef] -> [PresentationGroupDef]+groupingForDivisions+ :: [AccountDivision]+ -> [PresentationGroupDefOf t]+ -> [PresentationGroupDefOf t] groupingForDivisions divisions = filter ((`elem` divisions) . pgDivision) ------------------------------------------------------------------@@ -238,40 +251,49 @@ ------------------------------------------------------------------ -- | What one row of a block states.-data GroupRowKind- = GrossRow AccountTitles+data GroupRowKindOf t+ = GrossRow t -- ^ A constituent account, before deduction. | SubgroupRow PresentationGroup -- ^ The net of a nested block, carried into this one.- | DeductionRow AccountTitles+ | DeductionRow t -- ^ A contra account. Its amount is already stated relative to the -- group's normal side, so it is normally 'raBelowZero'. | NetRow PresentationGroup -- ^ The block's net, rounded after combining the exact member amounts. deriving (Show, Eq) +-- | Built-in chart specialization of 'GroupRowKindOf'.+type GroupRowKind = GroupRowKindOf AccountTitles+ -- | A group row kind paired with its relative amount.-data GroupRow v = GroupRow- { grKind :: GroupRowKind+data GroupRowOf t v = GroupRow+ { grKind :: GroupRowKindOf t , grAmount :: RelativeAmount v } deriving (Show, Eq) +-- | Built-in chart specialization of 'GroupRowOf'.+type GroupRow = GroupRowOf AccountTitles+ -- | Result of applying a grouping to a set of per-title balances.-data GroupedPresentation v = GroupedPresentation- { gpBlocks :: [(PresentationGroupDef, [GroupRow v])]+data GroupedPresentationOf t v = GroupedPresentation+ { gpBlocks :: [(PresentationGroupDefOf t, [GroupRowOf t v])] -- ^ Blocks in render order: nested blocks precede the block they roll -- up into, roots follow the order of the grouping list. , gpRootTotals :: Map AccountDivision (v, v) -- ^ Per-division @(debit, credit)@ contribution of the __outermost__ -- blocks only. A caller adds this to the ungrouped part of the column; -- adding nested blocks as well would double count.- , gpConsumed :: Set AccountTitles+ , gpConsumed :: Set t -- ^ Titles the blocks have taken over. The caller must not render these -- again through its ordinary per-entry path. } deriving (Show, Eq) +-- | Built-in chart specialization of 'GroupedPresentationOf'.+type GroupedPresentation = GroupedPresentationOf AccountTitles+ -- | Apply a grouping to per-title @(debit gross, credit gross)@ totals. -- -- A block is /active/ when one of its own contra titles carries non-zero gross@@ -286,10 +308,10 @@ -- Complexity: O(g · m + g²) for @g@ blocks of @m@ members (the grouping is a -- fixed, small table). presentGroups- :: HatVal v- => [PresentationGroupDef]- -> Map AccountTitles (v, v)- -> GroupedPresentation v+ :: (Ord t, HatVal v)+ => [PresentationGroupDefOf t]+ -> Map t (v, v)+ -> GroupedPresentationOf t v presentGroups defs balances = GroupedPresentation { gpBlocks = blocks , gpRootTotals = rootTotals
src/ExchangeAlgebra/Accounting/Statements/Metric.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# OPTIONS_GHC -Wincomplete-patterns -Werror=incomplete-patterns #-} @@ -18,7 +19,8 @@ , metricIdText , DerivedMetric(..) , PeriodResult(..)- , MetricError(..)+ , MetricError+ , MetricErrorOf(..) , metricForLegacyTitle , legacyTitlesForMetric , periodResultOfAlg@@ -27,7 +29,6 @@ import qualified ExchangeAlgebra.Accounting.TrialBalance.Accum as Accum -import qualified Data.Map.Strict as M import Data.Text (Text) import qualified Data.Text as T @@ -36,10 +37,11 @@ import ExchangeAlgebra.Accounting.Account.Classification ( AccountDivision(..), DivisionSemantics(..), Side(..) ) import ExchangeAlgebra.Accounting.Account.Registry- ( AccountSemantics(asemDivisionSemantics), accountSemantics )+ ( AccountSemantics(asemDivisionSemantics) )+import ExchangeAlgebra.Accounting.Account.Vocabulary (AccountVocabulary(vocabSemantics)) import ExchangeAlgebra.Accounting.Account.Title (AccountTitles(..)) import ExchangeAlgebra.Accounting.Exchange- ( ExBaseClass(getAccountTitle, whichSide) )+ ( ExBaseClass(TitleOf, getAccountTitle, whichSide) ) import ExchangeAlgebra.Algebra.Base.Representation ( Hat(..), HatBase, HatBaseClass(hat) ) import qualified ExchangeAlgebra.Accounting.TrialBalance.Validation as TB@@ -78,17 +80,20 @@ deriving (Show, Eq) -- | Reasons why a reporting metric cannot be derived.-data MetricError+data MetricErrorOf t = MetricNotAvailableAtStage TB.TrialBalanceStage- | ResidualDerivedCoordinate AccountTitles- | WildcardMetricSide AccountTitles+ | ResidualDerivedCoordinate t+ | WildcardMetricSide t | WildcardMetricAccount -- ^ A posting carries the wildcard account title, so its statement -- division cannot be determined.- | InvalidMetricValue AccountTitles+ | InvalidMetricValue t deriving (Show, Eq) --- | Map an engine-only legacy base to its reporting identity.+-- | A metric error for the built-in chart of accounts.+type MetricError = MetricErrorOf AccountTitles++-- | Map an engine-only legacy account title to its reporting identity. metricForLegacyTitle :: AccountTitles -> Maybe DerivedMetric metricForLegacyTitle title = case title of NetIncome -> Just PeriodResultMetric@@ -107,14 +112,15 @@ CustomMetric _ -> [] -- | Derive period profit or loss without adding a balancing term.--- Only genuine statement-classified Cost and Revenue titles participate;--- direction-encoding legacy bases are therefore excluded structurally.+-- A title contributes only when 'vocabSemantics' gives it a statement+-- division of Cost or Revenue. A custom vocabulary must supply these+-- semantics for each title that contributes to the period result. -- Invalid values and wildcard sides are returned as explicit errors. For -- externally sourced trial balances, prefer 'periodResultOf'. periodResultOfAlg :: (HatVal v, ExBaseClass b) => Alg v b- -> Either MetricError (PeriodResult v)+ -> Either (MetricErrorOf (TitleOf b)) (PeriodResult v) periodResultOfAlg alg | (_, base) : _ <- invalidEntries = Left (InvalidMetricValue (getAccountTitle base))@@ -146,9 +152,8 @@ -- treating an already-derived balancing item as another nominal account. -- Consolidation attribution bases do not participate, so the result is -- the period result before attribution to owners and non-controlling interests.--- No accounting finding is consulted; inspect--- 'ExchangeAlgebra.Accounting.TrialBalance.Validation.trialBalanceFindings'--- separately when the trial balance must also be audited.+-- Use "ExchangeAlgebra.Accounting.Audit" to inspect accounting findings+-- separately. periodResultOf :: HatVal v => TB.TrialBalanceStage@@ -158,12 +163,12 @@ | stage /= TB.BeforeClosing = Left (MetricNotAvailableAtStage stage) | issue : _ <- metricStructureErrors alg = Left issue- | legacy : _ <- nonZeroLegacyTitles alg =+ | legacy : _ <- Accum.nonZeroDerivedTitles alg = Left (ResidualDerivedCoordinate legacy) | otherwise = periodResultOfAlg alg -isStatementNominal :: AccountTitles -> Bool-isStatementNominal title = case accountSemantics title of+isStatementNominal :: AccountVocabulary t => t -> Bool+isStatementNominal title = case vocabSemantics title of Just semantics -> case asemDivisionSemantics semantics of StatementDivision Cost -> True StatementDivision Revenue -> True@@ -182,17 +187,3 @@ ++ map (const WildcardMetricAccount) wildcardAccounts where (invalidValues, wildcardAccounts, wildcardSides) = Accum.structureErrors alg--nonZeroLegacyTitles- :: (HatVal v, ExBaseClass b)- => Alg v b- -> [AccountTitles]-nonZeroLegacyTitles alg =- [ title- | (title, total) <- M.toList totals- , signAccum total /= Just EQ- ]- where- totals = M.filterWithKey (\title _ -> case metricForLegacyTitle title of- Nothing -> False- Just _ -> True) (Accum.accountAccums alg)
src/ExchangeAlgebra/Accounting/Statements/Presentation.hs view
@@ -1,3 +1,6 @@+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -Wincomplete-patterns -Werror=incomplete-patterns #-}@@ -7,12 +10,10 @@ Description : Context-sensitive JGAAP presentation from trial balances. This module is the reporting boundary between a trial balance and presented-statements. 'present' computes statements whenever a correct statement can be-computed; it does not judge whether the trial balance is normal for-accounting purposes. Abnormal-side balances (for example a deficit in-retained earnings), temporary-account residuals, reciprocal-account-mismatches, and unclosed nominal balances are reported separately by-'TB.trialBalanceFindings', and the caller decides how to treat them.+statements. 'present' computes statements when the trial balance and+presentation instructions allow it. Use "ExchangeAlgebra.Accounting.Audit"+to inspect findings such as abnormal-side balances, temporary-account+balances, and residuals after closing. Presentation fails only when no correct statement exists: an invalid value, a wildcard account or side, a trial balance whose debits and credits differ, a conflicting presentation instruction, a balance on a title that no@@ -29,10 +30,10 @@ >>> import ExchangeAlgebra.Algebra.Base.Representation (Hat(..), HatBase(..)) >>> import ExchangeAlgebra.Accounting.Account.Title (AccountTitles(..)) >>> import ExchangeAlgebra.Algebra.Value (MoneyDecimal)->>> type TrialBalance = Algebra.Alg MoneyDecimal (HatBase AccountTitles)->>> let cash = 100 Algebra..@ (Not :< Cash) :: TrialBalance->>> let equity = 100 Algebra..@ (Not :< CapitalStock) :: TrialBalance->>> let capital = cash Algebra..+ equity :: TrialBalance+>>> import ExchangeAlgebra.Accounting.TrialBalance.Balance (TrialBalance)+>>> let cash = 100 Algebra..@ (Not :< Cash) :: TrialBalance MoneyDecimal+>>> let equity = 100 Algebra..@ (Not :< CapitalStock) :: TrialBalance MoneyDecimal+>>> let capital = cash Algebra..+ equity :: TrialBalance MoneyDecimal >>> let context = jcciSecondGradeContext Standalone >>> let statements = present context TB.BeforeClosing capital >>> fmap (length . _statementLines) statements@@ -51,21 +52,33 @@ , ReportingScope(..) , PresentationProfile(..) , StatementSection(..)- , StatementLine(..)- , PresentationAllocation(..)- , PresentationRelabel(..)- , MaterialityTreatment(..)- , MaterialityDecision(..)- , ContraPresentationRule(..)+ , StatementLine+ , StatementLineOf(..)+ , PresentationAllocation+ , PresentationAllocationOf(..)+ , PresentationRelabel+ , PresentationRelabelOf(..)+ , MaterialityTreatment+ , MaterialityTreatmentOf(..)+ , MaterialityDecision+ , MaterialityDecisionOf(..)+ , ContraPresentationRule+ , ContraPresentationRuleOf(..) , CustomMetricLabel(..) , SubtotalCoverage(..)- , SubtotalDefinition(..)+ , SubtotalDefinition+ , SubtotalDefinitionOf(..) , StatementSubtotal(..)- , ReportingContext(..)+ , ReportingContext+ , ReportingContextOf(..)+ , reportingContext , jcciSecondGradeContext- , PresentationAuditEvent(..)- , PresentationIssue(..)- , FinancialStatements(..)+ , PresentationAuditEvent+ , PresentationAuditEventOf(.., ReciprocalAccountsEliminated)+ , PresentationIssue+ , PresentationIssueOf(..)+ , FinancialStatements+ , FinancialStatementsOf(..) , presentationLabel , metricLabel , present@@ -73,6 +86,7 @@ import qualified ExchangeAlgebra.Accounting.TrialBalance.Accum as Accum +import Data.Maybe (isJust) import Data.List.NonEmpty (NonEmpty(..)) import qualified Data.Map.Strict as M import Data.Map.Strict (Map)@@ -82,6 +96,9 @@ import qualified Data.Text as T import ExchangeAlgebra.Algebra.Base.Representation (HatBase)+import ExchangeAlgebra.Algebra.Element.Representation (Element(isWildcard))+import ExchangeAlgebra.Accounting.Account.Vocabulary (AccountVocabulary(..))+import ExchangeAlgebra.Accounting.Exchange (ExBaseClass(TitleOf)) import ExchangeAlgebra.Algebra.Core.Representation (Alg) import ExchangeAlgebra.Algebra.Value.Class (HatVal(..)) import ExchangeAlgebra.Accounting.Account.Classification@@ -99,10 +116,10 @@ import qualified ExchangeAlgebra.Accounting.Account.Registry as Registry import ExchangeAlgebra.Accounting.Statements.Metric ( DerivedMetric(..)- , MetricError+ , MetricErrorOf(..) , MetricId , PeriodResult(..)- , periodResultOf+ , periodResultOfAlg ) import qualified ExchangeAlgebra.Accounting.TrialBalance.Validation as TB import ExchangeAlgebra.Accounting.TrialBalance.Balance@@ -111,7 +128,7 @@ , balanceSide ) --- | Land 4 deliberately supports JGAAP only.+-- | Accounting framework used to prepare statements. data AccountingFramework = JGAAP deriving (Show, Eq) @@ -140,8 +157,8 @@ deriving (Show, Eq) -- | An account line with its label, section, side, amount, and deduction flag.-data StatementLine v = StatementLine- { _lineAccount :: AccountTitles+data StatementLineOf t v = StatementLine+ { _lineAccount :: t , _lineLabel :: Text , _lineSection :: StatementSection , _lineSide :: Side@@ -150,45 +167,63 @@ } deriving (Show, Eq) --- | Evidence-backed split of one title without creating new bookkeeping--- base components. Current and non-current parts must sum exactly to its balance.-data PresentationAllocation v = PresentationAllocation- { _allocationAccount :: AccountTitles+-- | A statement line for the built-in chart of accounts.+type StatementLine = StatementLineOf AccountTitles++-- | Split the balance of one account title for presentation using supporting+-- evidence. The current and non-current parts must sum exactly to that balance.+data PresentationAllocationOf t v = PresentationAllocation+ { _allocationAccount :: t , _allocationCurrent :: v , _allocationNoncurrent :: v , _allocationEvidence :: Text } deriving (Show, Eq) +-- | A maturity allocation for the built-in chart of accounts.+type PresentationAllocation = PresentationAllocationOf AccountTitles+ -- | An account relabeling instruction with its rationale.-data PresentationRelabel = PresentationRelabel- { _relabelSource :: AccountTitles- , _relabelTarget :: AccountTitles+data PresentationRelabelOf t = PresentationRelabel+ { _relabelSource :: t+ , _relabelTarget :: t , _relabelRationale :: Text } deriving (Show, Eq) +-- | A relabeling instruction for the built-in chart of accounts.+type PresentationRelabel = PresentationRelabelOf AccountTitles+ -- | Whether an account is presented gross, separately, or net against another.-data MaterialityTreatment+data MaterialityTreatmentOf t = PresentGross | PresentSeparately- | NetAgainst AccountTitles+ | NetAgainst t deriving (Show, Eq) +-- | A materiality treatment for the built-in chart of accounts.+type MaterialityTreatment = MaterialityTreatmentOf AccountTitles+ -- | An account materiality treatment with its rationale.-data MaterialityDecision = MaterialityDecision- { _materialityAccount :: AccountTitles- , _materialityTreatment :: MaterialityTreatment+data MaterialityDecisionOf t = MaterialityDecision+ { _materialityAccount :: t+ , _materialityTreatment :: MaterialityTreatmentOf t , _materialityRationale :: Text } deriving (Show, Eq) +-- | A materiality decision for the built-in chart of accounts.+type MaterialityDecision = MaterialityDecisionOf AccountTitles+ -- | A separate or net presentation instruction for a contra account.-data ContraPresentationRule- = PresentContraSeparately AccountTitles Text- | NetContraAgainst AccountTitles AccountTitles Text+data ContraPresentationRuleOf t+ = PresentContraSeparately t Text+ | NetContraAgainst t t Text deriving (Show, Eq) +-- | A contra presentation rule for the built-in chart of accounts.+type ContraPresentationRule = ContraPresentationRuleOf AccountTitles+ -- | Profile-specific display labels for a caller-defined metric. The metric -- identity remains separate from these labels. data CustomMetricLabel = CustomMetricLabel@@ -204,16 +239,18 @@ | TreatAbsentAsZero deriving (Show, Eq) --- | A subtotal is a typed reporting definition over account titles, never an--- account title in a base.-data SubtotalDefinition = SubtotalDefinition+-- | A subtotal is a typed reporting definition over account titles.+data SubtotalDefinitionOf t = SubtotalDefinition { _subtotalMetric :: DerivedMetric- , _subtotalCreditTitles :: [AccountTitles]- , _subtotalDebitTitles :: [AccountTitles]+ , _subtotalCreditTitles :: [t]+ , _subtotalDebitTitles :: [t] , _subtotalCoverage :: SubtotalCoverage } deriving (Show, Eq) +-- | A subtotal definition for the built-in chart of accounts.+type SubtotalDefinition = SubtotalDefinitionOf AccountTitles+ -- | A reporting metric with its label and account balance. data StatementSubtotal v = StatementSubtotal { _statementSubtotalMetric :: DerivedMetric@@ -223,20 +260,25 @@ deriving (Show, Eq) -- | Framework, scope, profile, and instructions used to present a trial balance.-data ReportingContext v = ReportingContext+data ReportingContextOf t v = ReportingContext { _reportingFramework :: AccountingFramework , _reportingScope :: ReportingScope , _presentationProfile :: PresentationProfile- , _maturitySensitiveTitles :: Set AccountTitles- , _presentationAllocations :: [PresentationAllocation v]- , _presentationRelabels :: [PresentationRelabel]- , _materialityDecisions :: [MaterialityDecision]- , _contraPresentationRules :: [ContraPresentationRule]- , _subtotalDefinitions :: [SubtotalDefinition]+ , _maturitySensitiveTitles :: Set t+ , _presentationAllocations :: [PresentationAllocationOf t v]+ , _presentationRelabels :: [PresentationRelabelOf t]+ , _materialityDecisions :: [MaterialityDecisionOf t]+ , _contraPresentationRules :: [ContraPresentationRuleOf t]+ , _subtotalDefinitions :: [SubtotalDefinitionOf t] , _customMetricLabels :: [CustomMetricLabel]+ , _labelOverrides :: Map t Text+ -- ^ Japanese labels used by the JCCI grade-2 profile. } deriving (Show, Eq) +-- | A reporting context for the built-in chart of accounts.+type ReportingContext = ReportingContextOf AccountTitles+ -- | Construct a JGAAP context with the JCCI grade-2 presentation profile. -- The caller explicitly chooses the reporting scope; it is not inferred from -- transaction entities or periods. Maturity-sensitive titles start empty, as@@ -245,10 +287,16 @@ -- instructions needed for the report. This starting context does not guarantee -- that 'present' succeeds for every validated trial balance. jcciSecondGradeContext :: ReportingScope -> ReportingContext v-jcciSecondGradeContext scope = ReportingContext- { _reportingFramework = JGAAP+jcciSecondGradeContext scope = (reportingContext JGAAP scope JcciSecondGradeReport)+ { _labelOverrides = jcciSecondGradeLabelOverrides }++-- | Construct a context with empty instruction lists and no label overrides.+reportingContext+ :: AccountingFramework -> ReportingScope -> PresentationProfile -> ReportingContextOf t v+reportingContext framework scope profile = ReportingContext+ { _reportingFramework = framework , _reportingScope = scope- , _presentationProfile = JcciSecondGradeReport+ , _presentationProfile = profile , _maturitySensitiveTitles = S.empty , _presentationAllocations = [] , _presentationRelabels = []@@ -256,28 +304,38 @@ , _contraPresentationRules = [] , _subtotalDefinitions = [] , _customMetricLabels = []+ , _labelOverrides = M.empty } -- | A recorded presentation operation and its supporting values.-data PresentationAuditEvent v- = ReciprocalAccountsEliminated- (TB.AccountBalance v) (TB.AccountBalance v)+data PresentationAuditEventOf t v+ = ReciprocalPairEliminated t (TB.AccountBalance v) t (TB.AccountBalance v)+ -- ^ Left and right endpoints, each followed by its balance before elimination. | AccountRelabeled- AccountTitles AccountTitles (TB.AccountBalance v) Text- | BalanceAllocated AccountTitles v v Text+ t t (TB.AccountBalance v) Text+ | BalanceAllocated t v v Text | MaterialityApplied- AccountTitles MaterialityTreatment (TB.AccountBalance v) Text+ t (MaterialityTreatmentOf t) (TB.AccountBalance v) Text | ContraPresentationApplied- AccountTitles (Maybe AccountTitles) (TB.AccountBalance v) Text+ t (Maybe t) (TB.AccountBalance v) Text | SubtotalCalculated DerivedMetric (TB.AccountBalance v)- | LabelOverridden AccountTitles Text Text+ | LabelOverridden t Text Text deriving (Show, Eq) --- | Reasons why no correct statement can be presented. Accounting--- abnormalities that still allow a statement are not issues; they are--- reported by 'TB.trialBalanceFindings'.-data PresentationIssue v- = InvalidStatementValue AccountTitles+-- | A presentation audit event for the built-in chart of accounts.+type PresentationAuditEvent = PresentationAuditEventOf AccountTitles++-- | Elimination of the built-in branch and head-office current accounts.+pattern ReciprocalAccountsEliminated+ :: TB.AccountBalance v -> TB.AccountBalance v -> PresentationAuditEventOf AccountTitles v+pattern ReciprocalAccountsEliminated branch headOffice =+ ReciprocalPairEliminated BranchCurrentAccount branch HeadOfficeCurrentAccount headOffice++-- | Conditions that prevent presentation. Use+-- "ExchangeAlgebra.Accounting.Audit" to check for accounting findings+-- separately.+data PresentationIssueOf t v+ = InvalidStatementValue t -- ^ A posting value is invalid (for example NaN or infinite). | WildcardStatementBase -- ^ An account title or a Hat/Not side is a wildcard, so the debit or@@ -287,37 +345,43 @@ -- presentation step (the per-title net balances summed on each side, -- as in a balance trial balance). Checked before reciprocal accounts are eliminated, -- so the elimination cannot hide an original imbalance.- | PeriodResultUnavailable MetricError+ | PeriodResultUnavailable (MetricErrorOf t) -- ^ The before-closing period result cannot be derived, so the mandatory -- period-result subtotal cannot be presented.- | MissingPresentationAllocation AccountTitles- | DuplicatePresentationAllocation AccountTitles+ | MissingPresentationAllocation t+ | DuplicatePresentationAllocation t | InvalidPresentationAllocation- AccountTitles (TB.AccountBalance v) v v- | BlankPresentationEvidence AccountTitles- | UnexpectedPresentationAllocation AccountTitles- | ConflictingPresentationInstruction AccountTitles- | MissingPresentationAccount AccountTitles- | BlankPresentationRationale AccountTitles- | UnpresentableBalance AccountTitles (TB.AccountBalance v)+ t (TB.AccountBalance v) v v+ | BlankPresentationEvidence t+ | UnexpectedPresentationAllocation t+ | ConflictingPresentationInstruction t+ | MissingPresentationAccount t+ | BlankPresentationRationale t+ | UnpresentableBalance t (TB.AccountBalance v) | InvalidSubtotalDefinition DerivedMetric | DuplicateMetricIdentity DerivedMetric | UnlabelledCustomMetric MetricId | UnreconciledPresentation v v deriving (Show, Eq) +-- | A presentation issue for the built-in chart of accounts.+type PresentationIssue = PresentationIssueOf AccountTitles+ -- | Presented statement lines, subtotals, and the presentation audit.-data FinancialStatements v = FinancialStatements+data FinancialStatementsOf t v = FinancialStatements { _statementFramework :: AccountingFramework , _statementScope :: ReportingScope , _statementProfile :: PresentationProfile , _statementTrialBalanceStage :: TB.TrialBalanceStage- , _statementLines :: [StatementLine v]+ , _statementLines :: [StatementLineOf t v] , _statementSubtotals :: [StatementSubtotal v]- , _presentationAudit :: [PresentationAuditEvent v]+ , _presentationAudit :: [PresentationAuditEventOf t v] } deriving (Show, Eq) +-- | Financial statements for the built-in chart of accounts.+type FinancialStatements = FinancialStatementsOf AccountTitles+ -- | Profile-specific Japanese display-label overrides. jcciSecondGradeLabelOverrides :: Map AccountTitles Text jcciSecondGradeLabelOverrides = M.fromList@@ -327,18 +391,21 @@ -- | Profile-specific display label. Japanese profiles use the registry's -- cleaned statement label, with the JCCI grade-2 overrides applied first. presentationLabel :: PresentationProfile -> AccountTitles -> Text-presentationLabel profile title = case Registry.accountSpec title of+presentationLabel = labelWith jcciSecondGradeLabelOverrides++labelWith :: AccountVocabulary t => Map t Text -> PresentationProfile -> t -> Text+labelWith overrides profile title = case vocabSpec title of Nothing -> T.pack (show title) Just spec -> case profile of JcciSecondGradeReport -> M.findWithDefault- (Registry.asLabelJa spec) title jcciSecondGradeLabelOverrides+ (Registry.asLabelJa spec) title overrides CanonicalJapanese -> Registry.asLabelJa spec CanonicalEnglish -> Registry.asNameEn spec -- | Resolve a metric's display label independently of its stable identity. -- Profit/loss wording follows the structural balance direction. metricLabel- :: ReportingContext v+ :: ReportingContextOf t v -> DerivedMetric -> TB.AccountBalance v -> Maybe Text@@ -379,7 +446,7 @@ -- an entity, period, or department and map it to account titles before calling -- this function. The stage is stated by the caller. A 'TB.BeforeClosing' trial -- balance always receives a 'PeriodResultMetric' subtotal derived as--- 'periodResultOf' derives it; a caller-supplied 'PeriodResultMetric'+-- @periodResultOf@ derives it; a caller-supplied 'PeriodResultMetric' -- definition is rejected with 'InvalidSubtotalDefinition'. An -- 'TB.AfterClosing' trial balance receives no period-result subtotal. -- Presentation instructions that move a balance between a profit-and-loss@@ -389,21 +456,26 @@ -- equals the exact sum of the revenue and expense balances. A maturity -- allocation or a maturity-sensitive title must be an asset or a liability. --+-- Combined reports eliminate each pair in 'vocabReciprocalPairs'. Each+-- endpoint must be concrete, carry the reciprocal role, and have a+-- non-nominal division. A conflicting instruction or an invalid endpoint+-- yields 'ConflictingPresentationInstruction' for that title.+-- -- Titles whose balance must be split between current and noncurrent are the -- union of '_maturitySensitiveTitles' and the implicitly maturity-sensitive -- titles. '_maturitySensitiveTitles' lists titles whose balances require a -- maturity split. ----- Success does not mean that the trial balance is normal for accounting--- purposes. A balance on the side opposite to its home side is presented in--- its own section on the side it actually has; inspect--- 'TB.trialBalanceFindings' to audit it.+-- A balance on the side opposite to its home side is presented in its own+-- section on the side it actually has. Inspect such balances with+-- 'ExchangeAlgebra.Accounting.Audit.impossibleBalances' and+-- 'ExchangeAlgebra.Accounting.Audit.abnormalBalances'. present- :: HatVal v- => ReportingContext v+ :: (HatVal v, ExBaseClass (HatBase t), TitleOf (HatBase t) ~ t)+ => ReportingContextOf t v -> TB.TrialBalanceStage- -> Alg v (HatBase AccountTitles)- -> Either (NonEmpty (PresentationIssue v)) (FinancialStatements v)+ -> Alg v (HatBase t)+ -> Either (NonEmpty (PresentationIssueOf t v)) (FinancialStatementsOf t v) present context stage alg = case issues of issue : rest -> Left (issue :| rest) [] -> Right FinancialStatements@@ -464,35 +536,36 @@ labelAudit = [ LabelOverridden title canonical displayed | _presentationProfile context == JcciSecondGradeReport- , (title, _) <- M.toList jcciSecondGradeLabelOverrides+ , title <- M.keys (_labelOverrides context) , title `elem` map _lineAccount statementLines- , let canonical = presentationLabel CanonicalJapanese title- , let displayed = presentationLabel JcciSecondGradeReport title+ , let canonical = labelWith (_labelOverrides context) CanonicalJapanese title+ , let displayed = labelWith (_labelOverrides context) JcciSecondGradeReport title , canonical /= displayed ] eliminateReciprocals- :: HatVal v => ReportingContext v- -> Map AccountTitles (Accum v)- -> (Map AccountTitles (Accum v), [PresentationAuditEvent v])+ :: (HatVal v, AccountVocabulary t) => ReportingContextOf t v+ -> Map t (Accum v)+ -> (Map t (Accum v), [PresentationAuditEventOf t v]) eliminateReciprocals context balances = case _reportingScope context of Standalone -> (balances, []) Combined ->- ( M.delete BranchCurrentAccount- (M.delete HeadOfficeCurrentAccount balances)- , [ ReciprocalAccountsEliminated branch headOffice- | branch /= TB.NoBalance || headOffice /= TB.NoBalance+ ( foldr (\(left, right) -> M.delete left . M.delete right) balances vocabReciprocalPairs+ , [ ReciprocalPairEliminated left leftBalance right rightBalance+ | (left, right) <- vocabReciprocalPairs+ , let leftBalance = balance left+ rightBalance = balance right+ , leftBalance /= TB.NoBalance || rightBalance /= TB.NoBalance ] ) where- branch = accumulatedBalance (accumulatedFor BranchCurrentAccount balances)- headOffice = accumulatedBalance (accumulatedFor HeadOfficeCurrentAccount balances)+ balance title = accumulatedBalance (accumulatedFor title balances) applyRelabels- :: HatVal v- => ReportingContext v- -> Map AccountTitles (Accum v)- -> (Map AccountTitles (Accum v), [PresentationAuditEvent v])+ :: (Ord t, HatVal v)+ => ReportingContextOf t v+ -> Map t (Accum v)+ -> (Map t (Accum v), [PresentationAuditEventOf t v]) applyRelabels context balances0 = Prelude.foldl applyOne (balances0, []) (_presentationRelabels context) where@@ -505,10 +578,10 @@ [AccountRelabeled source target sourceBalance rationale]) applyMateriality- :: HatVal v- => ReportingContext v- -> Map AccountTitles (Accum v)- -> (Map AccountTitles (Accum v), [PresentationAuditEvent v])+ :: (Ord t, HatVal v)+ => ReportingContextOf t v+ -> Map t (Accum v)+ -> (Map t (Accum v), [PresentationAuditEventOf t v]) applyMateriality context balances0 = Prelude.foldl applyOne (balances0, []) (_materialityDecisions context) where@@ -525,10 +598,10 @@ in (next, events ++ [event]) applyContraRules- :: HatVal v- => ReportingContext v- -> Map AccountTitles (Accum v)- -> (Map AccountTitles (Accum v), [PresentationAuditEvent v])+ :: (Ord t, HatVal v)+ => ReportingContextOf t v+ -> Map t (Accum v)+ -> (Map t (Accum v), [PresentationAuditEventOf t v]) applyContraRules context balances0 = Prelude.foldl applyOne (balances0, []) (_contraPresentationRules context)@@ -544,10 +617,10 @@ ) moveBalance- :: HatVal v- => AccountTitles -> AccountTitles- -> Map AccountTitles (Accum v)- -> Map AccountTitles (Accum v)+ :: (Ord t, HatVal v)+ => t -> t+ -> Map t (Accum v)+ -> Map t (Accum v) moveBalance source target balances = if source == target then balances@@ -557,12 +630,12 @@ (M.delete source balances) allocationIssues- :: HatVal v- => Set AccountTitles- -> ReportingContext v- -> Map AccountTitles (TB.AccountBalance v)- -> Map AccountTitles (Accum v)- -> [PresentationIssue v]+ :: (HatVal v, AccountVocabulary t)+ => Set t+ -> ReportingContextOf t v+ -> Map t (TB.AccountBalance v)+ -> Map t (Accum v)+ -> [PresentationIssueOf t v] allocationIssues required context balances states = concatMap checkTitle checkedTitles ++ [ DuplicatePresentationAllocation title | title <- duplicateTitles (map _allocationAccount allocations)@@ -574,7 +647,7 @@ allocationTitles = S.fromList (map _allocationAccount allocations) checkedTitles = S.toList (required `S.union` allocationTitles) checkTitle title- | Just semantics <- Registry.accountSemantics title+ | Just semantics <- vocabSemantics title , StatementDivision division <- asemDivisionSemantics semantics , division `elem` [Assets, Liability] = checkBalance title | otherwise = [ConflictingPresentationInstruction title]@@ -596,7 +669,7 @@ allocationMatches :: HatVal v- => Accum v -> PresentationAllocation v -> Bool+ => Accum v -> PresentationAllocationOf t v -> Bool allocationMatches total allocation = _allocationCurrent allocation >= 0 && _allocationNoncurrent allocation >= 0@@ -609,25 +682,27 @@ (addAccum (_allocationNoncurrent allocation) emptyAccum) instructionIssues- :: HatVal v- => Set AccountTitles- -> ReportingContext v- -> Map AccountTitles (TB.AccountBalance v)- -> [PresentationIssue v]+ :: (HatVal v, AccountVocabulary t)+ => Set t+ -> ReportingContextOf t v+ -> Map t (TB.AccountBalance v)+ -> [PresentationIssueOf t v] instructionIssues explicitRequired context balances =- duplicateInstructionIssues+ map ConflictingPresentationInstruction (duplicateTitles instructionSources)+ ++ reciprocalIssues ++ concatMap relabelIssue (_presentationRelabels context) ++ concatMap materialityIssue (_materialityDecisions context) ++ concatMap contraIssue (_contraPresentationRules context) where- duplicateInstructionIssues =- map ConflictingPresentationInstruction- (duplicateTitles instructionSources)- ++ [ ConflictingPresentationInstruction title- | _reportingScope context == Combined- , title <- [BranchCurrentAccount, HeadOfficeCurrentAccount]- , title `elem` instructionSources- ]+ reciprocalIssues =+ [ ConflictingPresentationInstruction title+ | _reportingScope context == Combined+ , (left, right) <- vocabReciprocalPairs+ , title <- [left, right]+ , title `elem` instructionSources || isWildcard title || isNominal title+ || not (hasReciprocalRole title)+ ]+ hasReciprocalRole = maybe False (elem ReciprocalAccount . asemRoles) . vocabSemantics instructionSources = concatMap relabelTitles (_presentationRelabels context) ++ concatMap materialityTitles (_materialityDecisions context) ++ concatMap contraTitles (_contraPresentationRules context)@@ -640,7 +715,7 @@ [ConflictingPresentationInstruction (_relabelSource rule)] | isNominal (_relabelSource rule) /= isNominal (_relabelTarget rule) = [ConflictingPresentationInstruction (_relabelSource rule)]- | not (presentableTarget (_relabelTarget rule)) =+ | not (presentable (_relabelTarget rule)) = [ConflictingPresentationInstruction (_relabelTarget rule)] | otherwise = [] materialityIssue decision@@ -657,7 +732,7 @@ [ConflictingPresentationInstruction target] | isNominal (_materialityAccount decision) /= isNominal target -> [ConflictingPresentationInstruction (_materialityAccount decision)]- | not (presentableTarget target) ->+ | not (presentable target) -> [ConflictingPresentationInstruction target] | M.notMember target balances -> [MissingPresentationAccount target]@@ -680,12 +755,12 @@ [ConflictingPresentationInstruction source] | isNominal source /= isNominal target -> [ConflictingPresentationInstruction source]- | not (presentableTarget target) ->+ | not (presentable target) -> [ConflictingPresentationInstruction target] | M.notMember target balances -> [MissingPresentationAccount target] | otherwise -> []- isNominal title = case Registry.accountSemantics title of+ isNominal title = case vocabSemantics title of Just semantics -> asemDivisionSemantics semantics `elem` [StatementDivision Revenue, StatementDivision Cost] Nothing -> False@@ -698,26 +773,25 @@ contraTitles (PresentContraSeparately source _) = [source] contraTitles (NetContraAgainst source target _) = [source, target] -duplicateTitles :: [AccountTitles] -> [AccountTitles]+duplicateTitles :: Ord t => [t] -> [t] duplicateTitles titles = S.toList (S.fromList [title | title <- titles, count title titles > 1]) where count needle = length . filter (== needle) -presentableTarget :: AccountTitles -> Bool-presentableTarget title = case Registry.accountSemantics title of- Just semantics -> asemReportingEligibility semantics `elem`- [StatementEligible, ContextualPresentation]- Nothing -> False+-- | A contextual title has a section on either side. Its balance only selects+-- which section to use, so an empty balance suffices to test coverage.+presentable :: AccountVocabulary t => t -> Bool+presentable title = isJust (reportingSection title TB.NoBalance) implicitMaturityTitles- :: Map AccountTitles (TB.AccountBalance v) -> Set AccountTitles+ :: AccountVocabulary t => Map t (TB.AccountBalance v) -> Set t implicitMaturityTitles balances = S.fromList [ title | (title, balance) <- M.toList balances , balanceSide balance /= Side , fixedCurrent title == Other- , Just semantics <- [Registry.accountSemantics title]+ , Just semantics <- [vocabSemantics title] , StatementDivision division <- [asemDivisionSemantics semantics] , division `elem` [Assets, Liability] ]@@ -726,9 +800,9 @@ -- undetermined. When this list is non-empty, no other check is evaluated, -- because the account accumulation relies on a determined side. statementStructureIssues- :: HatVal v- => Alg v (HatBase AccountTitles)- -> [PresentationIssue v]+ :: (HatVal v, ExBaseClass (HatBase t), TitleOf (HatBase t) ~ t)+ => Alg v (HatBase t)+ -> [PresentationIssueOf t v] statementStructureIssues alg = map (InvalidStatementValue . fst) invalidValues ++ map (const WildcardStatementBase) (wildcardAccounts ++ wildcardSides)@@ -739,8 +813,8 @@ -- relabeling, netting, or allocation; empty when they are equal. inputBalanceIssues :: HatVal v- => Map AccountTitles (Accum v)- -> [PresentationIssue v]+ => Map t (Accum v)+ -> [PresentationIssueOf t v] inputBalanceIssues states = [ UnbalancedStatementInput (roundAccum debit) (roundAccum credit) | signAccum (mergeAccum debit (negateAccum credit)) /= Just EQ ]@@ -752,16 +826,19 @@ _ -> (debits, credits) -- | The mandatory period-result subtotal of a before-closing trial balance,--- derived as 'periodResultOf' derives it, or the issue that prevents it. An+-- derived as @periodResultOf@ derives it, or the issue that prevents it. An -- after-closing trial balance yields neither. periodResultSubtotal- :: HatVal v- => ReportingContext v+ :: (HatVal v, ExBaseClass (HatBase t), TitleOf (HatBase t) ~ t)+ => ReportingContextOf t v -> TB.TrialBalanceStage- -> Alg v (HatBase AccountTitles)- -> ([PresentationIssue v], [StatementSubtotal v])+ -> Alg v (HatBase t)+ -> ([PresentationIssueOf t v], [StatementSubtotal v]) periodResultSubtotal _ TB.AfterClosing _ = ([], [])-periodResultSubtotal context TB.BeforeClosing alg = case periodResultOf TB.BeforeClosing alg of+periodResultSubtotal _ TB.BeforeClosing alg+ | title : _ <- Accum.nonZeroDerivedTitles alg =+ ([PeriodResultUnavailable (ResidualDerivedCoordinate title)], [])+periodResultSubtotal context TB.BeforeClosing alg = case periodResultOfAlg alg of Left issue -> ([PeriodResultUnavailable issue], []) Right result -> let balance = case result of@@ -772,17 +849,17 @@ | Just label <- [metricLabel context PeriodResultMetric balance]]) coverageIssues- :: Map AccountTitles (TB.AccountBalance v) -> [PresentationIssue v]+ :: AccountVocabulary t => Map t (TB.AccountBalance v) -> [PresentationIssueOf t v] coverageIssues balances = [ UnpresentableBalance title balance | (title, balance) <- M.toList balances , balanceSide balance /= Side- , not (presentableTarget title)+ , not (presentable title) ] reconciliationIssues- :: HatVal v- => ReportingContext v -> Map AccountTitles (Accum v) -> [PresentationIssue v]+ :: (HatVal v, AccountVocabulary t)+ => ReportingContextOf t v -> Map t (Accum v) -> [PresentationIssueOf t v] reconciliationIssues context balances = [ UnreconciledPresentation (roundAccum debit) (roundAccum credit) | signAccum (mergeAccum debit (negateAccum credit)) /= Just EQ ]@@ -804,11 +881,11 @@ [] -> total subtotalIssues- :: HatVal v- => ReportingContext v- -> Map AccountTitles (TB.AccountBalance v)- -> Map AccountTitles (TB.AccountBalance v)- -> [PresentationIssue v]+ :: (Ord t, HatVal v)+ => ReportingContextOf t v+ -> Map t (TB.AccountBalance v)+ -> Map t (TB.AccountBalance v)+ -> [PresentationIssueOf t v] subtotalIssues context initial balances = duplicateDefinitionIssues ++ duplicateCustomLabelIssues ++ concatMap check definitions@@ -872,10 +949,10 @@ count needle = length . filter (== needle) renderLines- :: (Eq v, Num v)- => ReportingContext v- -> Map AccountTitles (TB.AccountBalance v)- -> [StatementLine v]+ :: (AccountVocabulary t, Eq v, Num v)+ => ReportingContextOf t v+ -> Map t (TB.AccountBalance v)+ -> [StatementLineOf t v] renderLines context balances = concatMap renderOne (M.toList balances) where renderOne (_, TB.NoBalance) = []@@ -890,11 +967,11 @@ [] -> Nothing allocatedLines- :: (Eq v, Num v)- => ReportingContext v -> AccountTitles -> TB.AccountBalance v- -> PresentationAllocation v -> [StatementLine v]+ :: (AccountVocabulary t, Eq v, Num v)+ => ReportingContextOf t v -> t -> TB.AccountBalance v+ -> PresentationAllocationOf t v -> [StatementLineOf t v] allocatedLines context title balance allocation =- [ StatementLine title (presentationLabel (_presentationProfile context) title)+ [ StatementLine title (labelWith (_labelOverrides context) (_presentationProfile context) title) section side amount (isContraTitle title) | (section, amount) <- [ (currentSection title balance, _allocationCurrent allocation)@@ -906,21 +983,21 @@ side = balanceSide balance lineFor- :: Num v => ReportingContext v -> AccountTitles -> StatementSection- -> TB.AccountBalance v -> StatementLine v+ :: (AccountVocabulary t, Num v) => ReportingContextOf t v -> t -> StatementSection+ -> TB.AccountBalance v -> StatementLineOf t v lineFor context title section balance = StatementLine- title (presentationLabel (_presentationProfile context) title)+ title (labelWith (_labelOverrides context) (_presentationProfile context) title) section (balanceSide balance) (balanceAmount balance) (isContraTitle title) -isContraTitle :: AccountTitles -> Bool-isContraTitle title = case Registry.accountSemantics title of+isContraTitle :: AccountVocabulary t => t -> Bool+isContraTitle title = case vocabSemantics title of Just semantics -> ContraAccount `elem` asemRoles semantics Nothing -> False reportingSection- :: AccountTitles -> TB.AccountBalance v -> Maybe StatementSection+ :: AccountVocabulary t => t -> TB.AccountBalance v -> Maybe StatementSection reportingSection title balance = do- semantics <- Registry.accountSemantics title+ semantics <- vocabSemantics title case asemReportingEligibility semantics of DerivedPresentation -> Nothing NotPresented -> Nothing@@ -929,7 +1006,7 @@ StatementDivision division -> Just (divisionSection title division) _ -> Nothing -divisionSection :: AccountTitles -> AccountDivision -> StatementSection+divisionSection :: AccountVocabulary t => t -> AccountDivision -> StatementSection divisionSection title division = case division of Assets -> case fixedCurrent title of Fixed -> NoncurrentAssetsSection@@ -941,8 +1018,8 @@ Revenue -> RevenueSection Cost -> ExpenseSection -fixedCurrent :: AccountTitles -> FixedCurrent-fixedCurrent title = case Registry.accountSpec title of+fixedCurrent :: AccountVocabulary t => t -> FixedCurrent+fixedCurrent title = case vocabSpec title of Just spec -> Registry.asFixedCurrent spec Nothing -> Other @@ -951,16 +1028,16 @@ contextualSection (TB.CreditBalance _) = ContextualCreditSection contextualSection TB.NoBalance = ContextualDebitSection -currentSection :: AccountTitles -> TB.AccountBalance v -> StatementSection-currentSection title balance = case Registry.accountSemantics title of+currentSection :: AccountVocabulary t => t -> TB.AccountBalance v -> StatementSection+currentSection title balance = case vocabSemantics title of Just semantics -> case asemDivisionSemantics semantics of StatementDivision Liability -> CurrentLiabilitiesSection StatementDivision Assets -> CurrentAssetsSection _ -> contextualSection balance Nothing -> contextualSection balance -noncurrentSection :: AccountTitles -> TB.AccountBalance v -> StatementSection-noncurrentSection title balance = case Registry.accountSemantics title of+noncurrentSection :: AccountVocabulary t => t -> TB.AccountBalance v -> StatementSection+noncurrentSection title balance = case vocabSemantics title of Just semantics -> case asemDivisionSemantics semantics of StatementDivision Liability -> NoncurrentLiabilitiesSection StatementDivision Assets -> NoncurrentAssetsSection@@ -975,13 +1052,13 @@ (Credit, value) -> TB.CreditBalance value -- | An absent title contributes the empty exact sum.-accumulatedFor :: HatVal v => AccountTitles -> Map AccountTitles (Accum v) -> Accum v+accumulatedFor :: (Ord t, HatVal v) => t -> Map t (Accum v) -> Accum v accumulatedFor = M.findWithDefault emptyAccum subtotalBalance- :: HatVal v- => Map AccountTitles (Accum v)- -> [AccountTitles] -> [AccountTitles] -> TB.AccountBalance v+ :: (Ord t, HatVal v)+ => Map t (Accum v)+ -> [t] -> [t] -> TB.AccountBalance v subtotalBalance balances creditTitles debitTitles = accumulatedBalance (foldr (mergeAccum . (`accumulatedFor` balances)) emptyAccum (debitTitles ++ creditTitles))
src/ExchangeAlgebra/Accounting/Transfer.hs view
@@ -194,7 +194,7 @@ , Rounding(..) , roundScaled )-import ExchangeAlgebra.Accounting.Account (accountSpec)+import ExchangeAlgebra.Accounting.Account (AccountVocabulary(vocabSpec)) import ExchangeAlgebra.Accounting.Exchange (ExBaseClass(..)) import ExchangeAlgebra.Journal.Core (Journal, Note) import qualified ExchangeAlgebra.Journal.Core as Journal@@ -434,7 +434,7 @@ target = merge Not (ignoreWildcard (base source) targetPattern) unknown :: [b] unknown = [postingBase | postingBase <- [source, target]- , isNothing (accountSpec (getAccountTitle postingBase))]+ , isNothing (vocabSpec (getAccountTitle postingBase))] net :: Accum v net = mergeAccum notTotal (negateAccum hatTotal)
src/ExchangeAlgebra/Accounting/TrialBalance.hs view
@@ -1,18 +1,8 @@ {- | Module : ExchangeAlgebra.Accounting.TrialBalance-Description : Compute debit and credit account balances and audit findings.--Import this module for the complete trial-balance API. Import-"ExchangeAlgebra.Accounting.TrialBalance.Balance" for balance calculations or-"ExchangeAlgebra.Accounting.TrialBalance.Validation" for findings alone.+Description : Compute debit and credit account balances. -+--------------------------------------+-------------------------------------------+-| Task | Entry point |-+======================================+===========================================+-| Aggregate account balances | 'accountBalances' |-+--------------------------------------+-------------------------------------------+-| Report accounting findings | 'trialBalanceFindings' |-+--------------------------------------+-------------------------------------------++Use "ExchangeAlgebra.Accounting.Audit" to audit the trial balance. 'accountBalances' returns account balances directed by 'DebitBalance' or 'CreditBalance'. 'ExchangeAlgebra.Algebra.Core.netPairMapBy' instead returns@@ -30,11 +20,7 @@ , balanceAmount , accountBalances , TrialBalanceStage(..)- , ReclassificationRule(..)- , TrialBalanceInput(..)- , TBFinding(..)- , trialBalanceFindings ) where import ExchangeAlgebra.Accounting.TrialBalance.Balance-import ExchangeAlgebra.Accounting.TrialBalance.Validation+import ExchangeAlgebra.Accounting.TrialBalance.Validation (TrialBalanceStage(..))
src/ExchangeAlgebra/Accounting/TrialBalance/Accum.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE FlexibleContexts #-} @@ -6,6 +8,7 @@ -- the public balance representation remains in TrialBalance.Balance. module ExchangeAlgebra.Accounting.TrialBalance.Accum ( structureErrors+ , nonZeroDerivedTitles , accountAccums , insertAccountAccum , readAccountAccum@@ -16,35 +19,56 @@ import ExchangeAlgebra.Algebra.Core.Representation (Alg, pattern (:@), foldEntries) import ExchangeAlgebra.Algebra.Value.Class (HatVal(..), isErrorValue)-import ExchangeAlgebra.Accounting.Account.Classification (Side(..))-import ExchangeAlgebra.Accounting.Account.Title (AccountTitles(..))+import ExchangeAlgebra.Accounting.Account.Classification+ ( ReportingEligibility(..), Side(..) )+import ExchangeAlgebra.Accounting.Account.Registry+ ( AccountSemantics(asemReportingEligibility) )+import ExchangeAlgebra.Accounting.Account.Vocabulary+ ( AccountVocabulary(vocabSemantics) ) import ExchangeAlgebra.Accounting.Exchange- ( ExBaseClass(getAccountTitle, whichSide) )+ ( ExBaseClass(TitleOf, getAccountTitle, whichSide) ) import ExchangeAlgebra.Algebra.Base.Representation (Hat(..), HatBase(..))+import ExchangeAlgebra.Algebra.Element.Representation (Element(isWildcard)) -- | Inspect structure without determining posting sides. Lists retain the -- validation fold's reverse traversal order, including a standalone zero term. -- The result contains invalid values with titles, wildcard accounts, and -- wildcard sides, respectively. structureErrors- :: HatVal v- => Alg v (HatBase AccountTitles)- -> ([(AccountTitles, v)], [AccountTitles], [AccountTitles])+ :: (HatVal v, ExBaseClass (HatBase t), TitleOf (HatBase t) ~ t)+ => Alg v (HatBase t)+ -> ([(t, v)], [t], [t]) structureErrors alg = case alg of value :@ base -> collect ([], [], []) value base _ -> foldEntries collect ([], [], []) alg where collect (invalids, accounts, sides) value (side :< title) = ( [(title, value) | isErrorValue value] ++ invalids- , [title | title == AccountTitle] ++ accounts+ , [title | isWildcard title] ++ accounts , [title | side == HatNot] ++ sides ) +-- | List derived-presentation titles whose exact account sum is non-zero.+-- Titles are returned in ascending order, without rounding the sums.+nonZeroDerivedTitles+ :: (HatVal v, ExBaseClass b)+ => Alg v b -> [TitleOf b]+nonZeroDerivedTitles alg =+ [ title+ | (title, total) <- M.toAscList (accountAccums alg)+ , isDerived title+ , signAccum total /= Just EQ+ ]+ where+ isDerived title = case vocabSemantics title of+ Just semantics -> asemReportingEligibility semantics == DerivedPresentation+ Nothing -> False+ -- | Add one posting to its account's exact debit-minus-credit sum. insertAccountAccum :: (HatVal v, ExBaseClass b)- => Map AccountTitles (Accum v) -> v -> b -> Map AccountTitles (Accum v)+ => Map (TitleOf b) (Accum v) -> v -> b -> Map (TitleOf b) (Accum v) insertAccountAccum totals value base = M.insertWith mergeAccum (getAccountTitle base) (case whichSide base of Debit -> addAccum value emptyAccum@@ -54,7 +78,7 @@ -- | Retain each account's exact signed sum until its consumer reads it. accountAccums :: (HatVal v, ExBaseClass b)- => Alg v b -> Map AccountTitles (Accum v)+ => Alg v b -> Map (TitleOf b) (Accum v) accountAccums = foldEntries insertAccountAccum M.empty -- | Determine direction before rounding a non-negative magnitude once.
src/ExchangeAlgebra/Accounting/TrialBalance/Balance.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {- |@@ -10,7 +11,8 @@ and credit second. -} module ExchangeAlgebra.Accounting.TrialBalance.Balance- ( AccountBalance(..)+ ( TrialBalance+ , AccountBalance(..) , balancePair , addPair , netPair@@ -26,13 +28,20 @@ import qualified Data.Map.Strict as M import Data.Map.Strict (Map) +import ExchangeAlgebra.Algebra.Base.Representation (HatBase) import ExchangeAlgebra.Algebra.Core.Representation (Alg) import ExchangeAlgebra.Algebra.Value.Class (HatVal(..)) import ExchangeAlgebra.Accounting.Account.Classification (Side(..)) import ExchangeAlgebra.Accounting.Account.Title (AccountTitles) import ExchangeAlgebra.Accounting.Exchange- ( ExBaseClass )+ ( ExBaseClass(TitleOf) ) +-- | A trial balance: postings of one scope whose bases are reduced to account+-- titles. The caller chooses the scope and the unit before reducing a ledger+-- to this form. The type does not record whether the postings are adjusted or+-- closed; functions that need a processing point state it as a precondition.+type TrialBalance v = Alg v (HatBase AccountTitles)+ -- | Net balance direction remains structural; values stay non-negative. data AccountBalance v = NoBalance@@ -66,8 +75,7 @@ (addPair (balancePair left) (balancePair right)) -- | Look up an account balance, treating an absent account as balanced.-balanceFor :: AccountTitles -> Map AccountTitles (AccountBalance v)- -> AccountBalance v+balanceFor :: Ord t => t -> Map t (AccountBalance v) -> AccountBalance v balanceFor title = M.findWithDefault NoBalance title -- | Recover the structural side of a balance.@@ -87,7 +95,7 @@ accountBalances :: (HatVal v, ExBaseClass b) => Alg v b- -> Map AccountTitles (AccountBalance v)+ -> Map (TitleOf b) (AccountBalance v) accountBalances = M.map finish . Accum.accountAccums where finish total = case Accum.readAccountAccum Credit total of
src/ExchangeAlgebra/Accounting/TrialBalance/Validation.hs view
@@ -1,343 +1,17 @@-{-# LANGUAGE PatternSynonyms #-}-{-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE BangPatterns #-}-{-# OPTIONS_GHC -Wincomplete-patterns -Werror=incomplete-patterns #-}- {- | Module : ExchangeAlgebra.Accounting.TrialBalance.Validation-Description : Accounting findings on trial balances, reported without blocking.--An exactly balanced trial balance can still be abnormal for accounting-purposes. 'trialBalanceFindings' reports reciprocal-account mismatches,-temporary-account residuals, closing-device residuals, abnormal-side balances,-and missing classification evidence independently of the double-entry balance-check. It is an audit function: it never blocks a computation, and the caller-(a person or a language model) decides how to treat each finding.--Computation and audit are separate. Financial statements are prepared by-'ExchangeAlgebra.Accounting.Statements.Presentation.present' directly from a-trial balance, without consulting these findings. The policy gate was removed-in 0.6.0.0; inspect findings with 'trialBalanceFindings'. No finding performs-a reclassification automatically. A caller must record and apply a transfer,-then inspect the resulting trial balance again.--Findings use exact equality. Prefer an exact value type such as-@MoneyDecimal@ for deterministic accounting checks.--Inspect a cash contribution. The findings do not close or reclassify the-supplied postings.+Description : Trial-balance stages and account balance types. ->>> import qualified Data.Map.Strict as Map->>> import qualified Data.Set as Set->>> import qualified ExchangeAlgebra.Algebra.Core as Algebra->>> import ExchangeAlgebra.Algebra.Base.Representation (Hat(..), HatBase(..))->>> import ExchangeAlgebra.Accounting.Account.Title (AccountTitles(..))->>> import ExchangeAlgebra.Algebra.Value (MoneyDecimal)->>> type TrialBalance = Algebra.Alg MoneyDecimal (HatBase AccountTitles)->>> let cash = 100 Algebra..@ (Not :< Cash) :: TrialBalance->>> let equity = 100 Algebra..@ (Not :< CapitalStock) :: TrialBalance->>> let capital = cash Algebra..+ equity :: TrialBalance->>> let input = TrialBalanceInput capital BeforeClosing Map.empty [] Set.empty->>> trialBalanceFindings input-[]+'TrialBalanceStage' identifies whether the supplied trial balance precedes+or follows closing. Use "ExchangeAlgebra.Accounting.Audit" to audit balances. -} module ExchangeAlgebra.Accounting.TrialBalance.Validation- ( TrialBalanceStage(..)- , AccountBalance(..)- , ReclassificationRule(..)- , TrialBalanceInput(..)- , TBFinding(..)- , trialBalanceFindings- ) where--import qualified ExchangeAlgebra.Accounting.TrialBalance.Accum as Accum--import Data.List.NonEmpty (NonEmpty(..))-import qualified Data.List.NonEmpty as NE-import qualified Data.Map.Strict as M-import Data.Map.Strict (Map)-import qualified Data.Set as S-import Data.Set (Set)-import Data.Text (Text)-import qualified Data.Text as T+ ( TrialBalanceStage(..), AccountBalance(..) ) where -import ExchangeAlgebra.Accounting.Exchange (ExBaseClass(whichSide))-import ExchangeAlgebra.Algebra.Core.Representation- ( Alg, pattern (:@)- , foldEntries- )-import ExchangeAlgebra.Algebra.Value.Class (HatVal(..))-import ExchangeAlgebra.Accounting.Account.Classification- ( AccountRole(..)- , DivisionSemantics(..)- , HomeSideSemantics(..)- , Side(..)- , AccountDivision(..)- )-import ExchangeAlgebra.Accounting.Account.Registry- ( AccountSemantics(asemDivisionSemantics,- asemHomeSideSemantics, asemRoles)- , accountSemantics, concreteAccountTitles )-import ExchangeAlgebra.Accounting.Account.Title (AccountTitles(..))-import ExchangeAlgebra.Algebra.Base.Representation (Hat(..), HatBase((:<)))-import ExchangeAlgebra.Accounting.TrialBalance.Balance- ( AccountBalance(..)- , balanceFor- , balanceSide- )+import ExchangeAlgebra.Accounting.TrialBalance.Balance (AccountBalance(..)) -- | Processing point of the supplied trial balance. data TrialBalanceStage = BeforeClosing | AfterClosing deriving (Show, Eq)---- | A rule identifies a condition and possible target titles. It supplies an--- instruction, not an automatic mutation.-data ReclassificationRule- = SideReclassificationRule- AccountTitles- Side- (NonEmpty AccountTitles)- | MaturityEvidenceRequired AccountTitles- deriving (Show, Eq)---- | Unvalidated trial-balance input and its external evidence.-data TrialBalanceInput v = TrialBalanceInput- { _trialBalanceElement :: Alg v (HatBase AccountTitles)- , _trialBalanceStage :: TrialBalanceStage- , _temporaryBalanceExplanations :: Map AccountTitles Text- , _reclassificationRules :: [ReclassificationRule]- , _maturityEvidenceTitles :: Set AccountTitles- }- deriving (Show)---- | Facts detected before financial-statement presentation.-data TBFinding v- = InvalidTrialBalanceValue v- | WildcardTrialBalanceAccount- | WildcardTrialBalanceSide- | UnbalancedTrialBalance v v- | ReciprocalMismatch- (AccountBalance v)- (AccountBalance v)- | StandaloneReciprocalBalance AccountTitles (AccountBalance v)- | UnresolvedTemporaryBalance AccountTitles (AccountBalance v)- | ExplainedTemporaryBalance AccountTitles (AccountBalance v) Text- | BlankTemporaryExplanation AccountTitles (AccountBalance v)- | ClosingDeviceResidual AccountTitles (AccountBalance v)- | DerivedCoordinateResidual AccountTitles (AccountBalance v)- | UnclosedNominalBalance AccountTitles (AccountBalance v)- | UnexplainedAbnormalBalance- AccountTitles Side (AccountBalance v)- | AbnormalBalanceWithReclassificationRule- AccountTitles (AccountBalance v) AccountTitles- | AmbiguousReclassification- AccountTitles (AccountBalance v) (NonEmpty AccountTitles)- | MissingMaturityEvidence AccountTitles- | InapplicableReclassificationRule ReclassificationRule- deriving (Show, Eq)---- | Detect every applicable finding. Structural errors suppress any operation--- that would call the partial legacy @whichSide@ function on wildcard bases.-trialBalanceFindings :: HatVal v => TrialBalanceInput v -> [TBFinding v]-trialBalanceFindings input- | not (null structuralFindings) = structuralFindings- | otherwise = balanceFindings- ++ reciprocalFindings totals balances- ++ temporaryFindings input balances- ++ closingFindings input balances- ++ abnormalFindings input balances- ++ maturityFindings input balances- ++ ruleConfigurationFindings input- where- alg = _trialBalanceElement input- (invalidValues, wildcardAccounts, wildcardSides) = Accum.structureErrors alg- structuralFindings = map (InvalidTrialBalanceValue . snd) invalidValues- ++ map (const WildcardTrialBalanceAccount) wildcardAccounts- ++ map (const WildcardTrialBalanceSide) wildcardSides- (debitState, creditState, totals) = case alg of- value :@ base -> collect initial value base- _ -> foldEntries collect initial alg- initial = (emptyAccum, emptyAccum, M.empty)- collect (!debits, !credits, !accounts) value base = case base of- HatNot :< _ -> (debits, credits, accounts)- _ :< AccountTitle -> (debits, credits, accounts)- _ | value == zeroValue -> (debits, credits, accounts)- | otherwise ->- let !accounts' = Accum.insertAccountAccum accounts value base- !debits' = case whichSide base of- Debit -> addAccum value debits- _ -> debits- !credits' = case whichSide base of- Credit -> addAccum value credits- _ -> credits- in (debits', credits', accounts')- debit = roundAccum debitState- credit = roundAccum creditState- balanceFindings =- [ UnbalancedTrialBalance debit credit- | signAccum (mergeAccum debitState (negateAccum creditState)) /= Just EQ ]- balances = M.map finish totals- finish total = case Accum.readAccountAccum Credit total of- (Side, _) -> NoBalance- (Debit, value) -> DebitBalance value- (Credit, value) -> CreditBalance value--reciprocalFindings- :: HatVal v- => Map AccountTitles (Accum v)- -> Map AccountTitles (AccountBalance v)- -> [TBFinding v]-reciprocalFindings totals balances =- case (branch, headOffice) of- (NoBalance, NoBalance) -> []- (NoBalance, balance) ->- [StandaloneReciprocalBalance HeadOfficeCurrentAccount balance]- (balance, NoBalance) ->- [StandaloneReciprocalBalance BranchCurrentAccount balance]- _ | signAccum (mergeAccum- (M.findWithDefault emptyAccum BranchCurrentAccount totals)- (M.findWithDefault emptyAccum HeadOfficeCurrentAccount totals))- == Just EQ -> []- | otherwise -> [ReciprocalMismatch branch headOffice]- where- branch = balanceFor BranchCurrentAccount balances- headOffice = balanceFor HeadOfficeCurrentAccount balances--temporaryFindings- :: TrialBalanceInput v- -> Map AccountTitles (AccountBalance v)- -> [TBFinding v]-temporaryFindings input balances = concatMap finding temporaryTitles- where- temporaryTitles = case _trialBalanceStage input of- BeforeClosing -> titlesWithRole SuspenseOrClearingAccount- AfterClosing -> filter (/= CashOverShort)- (titlesWithRole SuspenseOrClearingAccount)- finding title = case balanceFor title balances of- NoBalance -> []- balance -> case M.lookup title (_temporaryBalanceExplanations input) of- Nothing -> [UnresolvedTemporaryBalance title balance]- Just explanation- | T.null (T.strip explanation) ->- [BlankTemporaryExplanation title balance]- | otherwise ->- [ExplainedTemporaryBalance title balance explanation]--closingFindings- :: TrialBalanceInput v- -> Map AccountTitles (AccountBalance v)- -> [TBFinding v]-closingFindings input balances = case _trialBalanceStage input of- BeforeClosing -> []- AfterClosing ->- concatMap residual (CashOverShort : titlesWithRole ClosingDevice)- ++ concatMap derivedResidual- (titlesWithRole PeriodResult ++ titlesWithRole ReportingSubtotal)- ++ [ UnclosedNominalBalance title balance- | (title, balance) <- M.toList balances- , hasBalance balance- , isNominal title- ]- where- residual title = case balanceFor title balances of- NoBalance -> []- balance -> [ClosingDeviceResidual title balance]- derivedResidual title = case balanceFor title balances of- NoBalance -> []- balance -> [DerivedCoordinateResidual title balance]- isNominal title = case accountSemantics title of- Just semantics -> case asemDivisionSemantics semantics of- StatementDivision Cost -> True- StatementDivision Revenue -> True- _ -> False- Nothing -> False- hasBalance NoBalance = False- hasBalance _ = True--abnormalFindings- :: TrialBalanceInput v- -> Map AccountTitles (AccountBalance v)- -> [TBFinding v]-abnormalFindings input balances = concatMap finding (M.toList balances)- where- finding (_, NoBalance) = []- finding (title, balance) = case expectedSide title of- Nothing -> []- Just expected- | balanceSide balance == expected -> []- | otherwise -> classifyRule title expected balance- classifyRule title expected balance = case ruleTargets title (balanceSide balance)- (_reclassificationRules input) of- [] -> [UnexplainedAbnormalBalance- title expected balance]- [target] -> [AbnormalBalanceWithReclassificationRule- title balance target]- target : targets -> [AmbiguousReclassification- title balance (target :| targets)]--maturityFindings- :: Eq v- => TrialBalanceInput v- -> Map AccountTitles (AccountBalance v)- -> [TBFinding v]-maturityFindings input balances =- [ MissingMaturityEvidence title- | MaturityEvidenceRequired title <- _reclassificationRules input- , balanceFor title balances /= NoBalance- , S.notMember title (_maturityEvidenceTitles input)- ]--expectedSide :: AccountTitles -> Maybe Side-expectedSide title = do- semantics <- accountSemantics title- if OrdinaryAccount `elem` asemRoles semantics- then case asemHomeSideSemantics semantics of- FixedHomeSide side -> Just side- ContextDependentHomeSide -> Nothing- NoFixedHomeSide -> Nothing- NoPostingSide -> Nothing- else Nothing--ruleTargets- :: AccountTitles- -> Side- -> [ReclassificationRule]- -> [AccountTitles]-ruleTargets title side = deduplicate S.empty . concatMap targets- where- deduplicate _ [] = []- deduplicate seen (candidate : candidates)- | candidate `S.member` seen = deduplicate seen candidates- | otherwise = candidate- : deduplicate (S.insert candidate seen) candidates- targets (SideReclassificationRule source trigger candidates)- | source == title && trigger == side = NE.toList candidates- | otherwise = []- targets (MaturityEvidenceRequired _) = []--ruleConfigurationFindings :: TrialBalanceInput v -> [TBFinding v]-ruleConfigurationFindings input =- [ InapplicableReclassificationRule rule- | rule <- _reclassificationRules input- , not (applicable rule)- ]- where- applicable (MaturityEvidenceRequired title) = title /= AccountTitle- applicable (SideReclassificationRule source trigger candidates) =- source /= AccountTitle- && trigger /= Side- && expectedSide source /= Nothing- && expectedSide source /= Just trigger- && all (targetAccepts trigger) (NE.toList candidates)- targetAccepts trigger target =- target /= AccountTitle && expectedSide target == Just trigger--titlesWithRole :: AccountRole -> [AccountTitles]-titlesWithRole role =- [ title- | title <- concreteAccountTitles- , Just semantics <- [accountSemantics title]- , role `elem` asemRoles semantics- ]
src/ExchangeAlgebra/Algebra.hs view
@@ -5,7 +5,7 @@ Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license Package for Exchange Algebra defined by Hiroshi Deguchi. @@ -32,9 +32,9 @@ , BaseForSingleHat(..) , HatBase(..) , Element(..)- , AxisKey(..)- , axisIsWildcard- , AxisDecompose(..)+ , ElementKey(..)+ , elementKeyIsWildcard+ , HasElementKeys(..) , (.#) , Name , Subject
src/ExchangeAlgebra/Algebra/Base.hs view
@@ -3,7 +3,7 @@ Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license Package for Exchange Algebra defined by Hiroshi Deguchi. @@ -34,9 +34,9 @@ , BaseForSingleHat(..) , HatBase(..) , Element(..)- , AxisKey(..)- , axisIsWildcard- , AxisDecompose(..)+ , ElementKey(..)+ , elementKeyIsWildcard+ , HasElementKeys(..) , (.#) , Name , Subject@@ -56,9 +56,9 @@ ) import ExchangeAlgebra.Algebra.Element ( Element(..)- , AxisKey(..)- , axisIsWildcard- , AxisDecompose(..)+ , ElementKey(..)+ , elementKeyIsWildcard+ , HasElementKeys(..) , (.#) , Name , Subject
− src/ExchangeAlgebra/Algebra/Base/Account/JcciAliases.hs
@@ -1,4 +0,0 @@--- | Compatibility export for JCCI account-name aliases.-module ExchangeAlgebra.Algebra.Base.Account.JcciAliases {-# DEPRECATED "Use ExchangeAlgebra.Accounting.Account instead." #-} (jcciAliases) where --import ExchangeAlgebra.Accounting.Account.Aliases (jcciAliases)
− src/ExchangeAlgebra/Algebra/Base/Account/Registry.hs
@@ -1,8 +0,0 @@--- | Compatibility exports for the account registry.-module ExchangeAlgebra.Algebra.Base.Account.Registry {-# DEPRECATED "Use ExchangeAlgebra.Accounting.Account instead." #-} - ( AccountSpec(..), AccountSemantics(..), accountAliases, accountSpec- , accountSemantics, accountSpecMap, concreteAccountTitles- , classifyAccountContra, accountDescriptions- ) where--import ExchangeAlgebra.Accounting.Account.Registry
− src/ExchangeAlgebra/Algebra/Base/Account/Types.hs
@@ -1,8 +0,0 @@--- | Compatibility exports for account classification types.-module ExchangeAlgebra.Algebra.Base.Account.Types {-# DEPRECATED "Use ExchangeAlgebra.Accounting.Account instead." #-} - ( AccountDivision(..), Side(..), ClosingRule(..), FixedCurrent(..)- , AccountRole(..), PostingCapability(..), DivisionSemantics(..)- , HomeSideSemantics(..), ReportingEligibility(..)- ) where--import ExchangeAlgebra.Accounting.Account.Classification
− src/ExchangeAlgebra/Algebra/Base/Element.hs
@@ -1,10 +0,0 @@--- | Import "ExchangeAlgebra.Algebra.Element" instead.-module ExchangeAlgebra.Algebra.Base.Element {-# DEPRECATED "Use ExchangeAlgebra.Algebra.Element instead." #-}- ( Element(..), AxisKey(..), axisIsWildcard, AxisDecompose(..), (.#)- , AccountTitles(..), Name, Subject, CountUnit(..), Hashable(..), Generic- ) where--import ExchangeAlgebra.Algebra.Element.Representation- ( Element(..), AxisKey(..), axisIsWildcard, AxisDecompose(..), (.#)- , Name, Subject, CountUnit(..), Hashable(..), Generic )-import ExchangeAlgebra.Accounting.Account (AccountTitles(..))
src/ExchangeAlgebra/Algebra/Base/Representation.hs view
@@ -12,7 +12,6 @@ module ExchangeAlgebra.Algebra.Base.Representation where import ExchangeAlgebra.Algebra.Element.Representation-import Data.Time (Day, TimeOfDay) import GHC.Stack (HasCallStack, callStack, prettyCallStack) import qualified Data.Binary as Binary import Control.DeepSeq (NFData(..))@@ -51,7 +50,7 @@ instance (Element e1, Element e2, Element e3, Element e4, Element e5, Element e6) => BaseClass (e1, e2, e3, e4, e5, e6) where --- 7-tuple: 'Element'/'AxisDecompose' already provide 7-tuple instances; this+-- 7-tuple: 'Element'/'HasElementKeys' already provide 7-tuple instances; this -- closes the gap so every Element tuple arity is also usable as a base. instance (Element e1, Element e2, Element e3, Element e4, Element e5, Element e6, Element e7) => BaseClass (e1, e2, e3, e4, e5, e6, e7) where@@ -68,7 +67,7 @@ -- by the account division /together with/ this label (see -- 'ExchangeAlgebra.Accounting.Exchange.whichSide' — an -- account sits on its home side when 'Not' and on the opposite side when v'Hat').-class (BaseClass a, BaseClass (BasePart a), AxisDecompose (BasePart a)) => HatBaseClass a where+class (BaseClass a, BaseClass (BasePart a), HasElementKeys (BasePart a)) => HatBaseClass a where -- | The type of the base part excluding the Hat. type BasePart a -- | Extract the base part excluding the Hat. Complexity: O(1)@@ -250,7 +249,7 @@ instance (BaseClass a) => BaseClass (HatBase a) where -instance (BaseClass a, AxisDecompose a) => HatBaseClass (HatBase a) where+instance (BaseClass a, HasElementKeys a) => HatBaseClass (HatBase a) where type BasePart (HatBase a) = a hat = _hat@@ -282,12 +281,6 @@ -- *** CountUnit only (redundant algebra base) instance BaseClass CountUnit where---- *** Day only (redundant algebra base)-instance BaseClass Day where---- *** TimeOfDay only (redundant algebra base)-instance BaseClass TimeOfDay where -- *** An element extended with a wildcard (redundant algebra base) --
src/ExchangeAlgebra/Algebra/Core/Representation.hs view
@@ -20,10 +20,88 @@ {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE OverloadedStrings #-} -- | Generic exchange algebra representation and operations.-module ExchangeAlgebra.Algebra.Core.Representation where+module ExchangeAlgebra.Algebra.Core.Representation+ ( Redundant(..)+ , Pair( HatOne+ , NotOne+ , PairSeq+ , Pair+ , _hatSide+ , _notSide+ )+ , Alg(..)+ , pattern (:@)+ , _val+ , _hatBase+ , AxisPosting+ , DMap+ , mkPair+ , pairView+ , pairNull+ , foldPair+ , mapPair+ , hatPair+ , filterPair+ , pairSums+ , pairStates+ , comparePairSides+ , nullPair+ , pairAppend+ , pairUnion+ , emptyAxisPosting+ , insertAxisPosting+ , queryAxisPosting+ , linerFromMap+ , isZero+ , singleton+ , (.@)+ , (<@)+ , union+ , insert+ , unions+ , mergeAlgMap+ , mergeAlgMapIfNonZero+ , unionsMerge+ , foldPairs+ , netPairState+ , hasNonfiniteState+ , postNetStates+ , vals+ , bases+ , fromList+ , sigma+ , sigma2When+ , sigmaFromMap+ , toList+ , foldEntries+ , toASCList+ , map+ , mapPosting+ , mapMaybePosting+ , filter+ , mapBasePart+ , extendBy+ , proj+ , choosePairByHat+ , projExactMap+ , projWildMap+ , mkAlgFromMap+ , singlePairToAlg+ , projNetNorm+ , projectedNetState+ , foldProjectedNorm+ , foldProjectedState+ , barNormPair+ , balanceBy+ , balanceMapBy+ , netPairMapBy+ , foldEntriesToMap+ , decBy+ , postFromNetBy+ ) where import ExchangeAlgebra.Algebra.Base.Representation-import ExchangeAlgebra.Algebra.Element.Representation (Element(..), AxisDecompose(..), AxisKey(..), CountUnit(..), ( .# ), matchesQuery)+import ExchangeAlgebra.Algebra.Element.Representation (Element(..), HasElementKeys(..), ElementKey(..), CountUnit(..), ( .# ), matchesQuery) import ExchangeAlgebra.Algebra.Value (MoneyDouble, MoneyDecimal) import ExchangeAlgebra.Algebra.Value.Class @@ -95,16 +173,11 @@ -- -- Derived lemmas (also property-tested): @'bar'@ idempotence -- (@'bar' ('bar' x) = 'bar' x@), 'Zero' identity, and associativity of @('.+')@.--- Note @('.+')@ accumulates same-base postings as an ordered sequence (the--- /redundancy/), so 'Show' \/ 'Eq' \/ @Binary@ observe that order, as do the--- sequential sums in 'barWithin'. For finite postings, 'norm', 'bar', and--- balance are order-independent for every value type.--- The order itself is furthermore /construction-path dependent/: the--- pairwise-union path ('fromList'\/'mconcat') and the bulk-merge path--- ('sigma'\/'unionsMerge') arrange the same multiset of postings differently.--- Do not rely on @('==')@ to compare algebras built by different routes —--- compare after 'compress'\/'bar', or use an exact value type and compare--- the netted content.+-- For each base and each side, @('.+')@ retains the terms in left-to-right+-- order. 'fromList', 'sigma', and 'unionsMerge' follow the input order.+-- 'Eq', @Binary@, and the sequential sums in 'barWithin' can observe that+-- order. 'Show' displays sorted terms. For finite terms, 'norm', 'bar', and+-- balance are order-independent. class (HatVal n, HatBaseClass b, Monoid (a n b)) => Redundant a n b where -- | Hat operation. Flips Hat/Not on all terms.@@ -146,6 +219,10 @@ (.+) :: a n b -> a n b -> a n b -- | Scalar multiplication. Multiplies the value of every term by a scalar.+ -- Fixity @infixr 7@: it binds more tightly than the sums '(.+)' and '(<>)',+ -- so @2 .* x .+ y@ and @2 .* x <> y@ scale only @x@, and @2 .* 3 .* x@ is+ -- @2 .* (3 .* x)@. It also binds more tightly than '(.@)', so write+ -- @2 .* (10 .@ b)@. -- Complexity: O(1) for singleton, O(n) for Liner (.*) :: n -> a n b -> a n b @@ -180,31 +257,132 @@ infixr 7 .^+infixr 7 .* infixr 2 .- infixr 3 .+ infixr 3 <+ ------------------------------------------------------------ -- | Sequences of values on the Hat and Not sides of one base.-data Pair v where- Pair :: {_hatSide :: !(Seq v)- ,_notSide :: !(Seq v)} -> Pair v- deriving (Eq)+data Pair v+ = HatOne ~v+ | NotOne ~v+ | PairSeq !(Seq v) !(Seq v)+ deriving (Eq) +-- | Normalize the representation without evaluating the values.+-- Invariant: 'PairSeq' never holds exactly one posting in total.+mkPair :: Seq v -> Seq v -> Pair v+{-# INLINE mkPair #-}+mkPair hs ns = case (Seq.length hs, Seq.length ns) of+ (1, 0) -> case Seq.viewl hs of+ h Seq.:< _ -> HatOne h+ _ -> PairSeq hs ns+ (0, 1) -> case Seq.viewl ns of+ n Seq.:< _ -> NotOne n+ _ -> PairSeq hs ns+ _ -> PairSeq hs ns++-- | Compatibility view. Singleton sides allocate a sequence only on this path.+pairView :: Pair v -> (Seq v, Seq v)+{-# INLINE pairView #-}+pairView (HatOne v) = (Seq.singleton v, Seq.empty)+pairView (NotOne v) = (Seq.empty, Seq.singleton v)+pairView (PairSeq hs ns) = (hs, ns)++-- | Construct, match, select, or update the two ordered sides of a pair.+pattern Pair :: Seq v -> Seq v -> Pair v+pattern Pair {_hatSide, _notSide} <- (pairView -> (_hatSide, _notSide))+ where Pair hs ns = mkPair hs ns+{-# COMPLETE Pair #-}++-- | Test for an empty pair without allocating singleton sequences.+pairNull :: Pair v -> Bool+{-# INLINE pairNull #-}+pairNull (HatOne _) = False+pairNull (NotOne _) = False+pairNull (PairSeq hs ns) = Seq.null hs && Seq.null ns++-- | Fold Hat entries followed by Not entries, preserving each side's order.+foldPair :: (a -> v -> a)+ -> (a -> v -> a)+ -> a+ -> Pair v+ -> a+{-# INLINE foldPair #-}+foldPair fh _ z (HatOne v) = fh z v+foldPair _ fn z (NotOne v) = fn z v+foldPair fh fn z (PairSeq hs ns) = Foldable.foldl' fn (Foldable.foldl' fh z hs) ns++-- | Map values without evaluating singleton payloads or changing their order.+mapPair :: (v -> w) -> Pair v -> Pair w+{-# INLINE mapPair #-}+mapPair f (HatOne v) = HatOne (f v)+mapPair f (NotOne v) = NotOne (f v)+mapPair f (PairSeq hs ns) = mkPair (fmap f hs) (fmap f ns)++-- | Exchange the two sides without changing the order within either side.+hatPair :: Pair v -> Pair v+{-# INLINE hatPair #-}+hatPair (HatOne v) = NotOne v+hatPair (NotOne v) = HatOne v+hatPair (PairSeq hs ns) = mkPair ns hs++-- | Keep selected entries, preserving side order and normalizing the shape.+filterPair :: (v -> Bool) -> (v -> Bool) -> Pair v -> Pair v+{-# INLINE filterPair #-}+filterPair fh _ p@(HatOne v) = if fh v then p else nullPair+filterPair _ fn p@(NotOne v) = if fn v then p else nullPair+filterPair fh fn (PairSeq hs ns) = mkPair (Seq.filter fh hs) (Seq.filter fn ns)++-- | Sequential side totals, including the initial addition to zero.+pairSums :: Num v => Pair v -> (v, v)+{-# INLINE pairSums #-}+pairSums (HatOne v) = (0 + v, 0)+pairSums (NotOne v) = (0, 0 + v)+pairSums (PairSeq hs ns) = (Foldable.foldl' (+) 0 hs, Foldable.foldl' (+) 0 ns)++-- | Exact side totals, kept separate until the caller chooses a readout.+pairStates :: HatVal v => Pair v -> (Accum v, Accum v)+{-# INLINE pairStates #-}+pairStates (HatOne v) = (addAccum v emptyAccum, emptyAccum)+pairStates (NotOne v) = (emptyAccum, addAccum v emptyAccum)+pairStates (PairSeq hs ns) =+ ( Foldable.foldl' (flip addAccum) emptyAccum hs+ , Foldable.foldl' (flip addAccum) emptyAccum ns+ )+ instance (Binary.Binary v) => Binary.Binary (Pair v) where {-# INLINABLE put #-} {-# INLINABLE get #-}- put (Pair hs ns) = do+ put (HatOne v) = Binary.put (1 :: Int) >> Binary.put v >> Binary.put (0 :: Int)+ put (NotOne v) = Binary.put (0 :: Int) >> Binary.put (1 :: Int) >> Binary.put v+ put (PairSeq hs ns) = do Binary.put (Seq.length hs :: Int) Foldable.foldr (\x k -> Binary.put x >> k) (pure ()) hs Binary.put (Seq.length ns :: Int) Foldable.foldr (\x k -> Binary.put x >> k) (pure ()) ns get = do hsLen <- Binary.get :: Binary.Get Int- hs <- go hsLen Seq.empty- nsLen <- Binary.get :: Binary.Get Int- ns <- go nsLen Seq.empty- pure (Pair hs ns)+ case hsLen of+ 1 -> do+ h <- Binary.get+ nsLen <- Binary.get :: Binary.Get Int+ if nsLen <= 0+ then pure (HatOne h)+ else mkPair (Seq.singleton h) <$> go nsLen Seq.empty+ _ | hsLen <= 0 -> do+ nsLen <- Binary.get :: Binary.Get Int+ if nsLen == 1+ then do+ n <- Binary.get+ pure (NotOne n)+ else mkPair Seq.empty <$> go nsLen Seq.empty+ | otherwise -> do+ hs <- go hsLen Seq.empty+ nsLen <- Binary.get :: Binary.Get Int+ ns <- go nsLen Seq.empty+ pure (mkPair hs ns) where go :: Binary.Binary a => Int -> Seq a -> Binary.Get (Seq a) go n !acc@@ -216,8 +394,8 @@ instance (HatVal v) => Ord (Pair v) where {-# INLINE compare #-}- compare first@(Pair hs1 ns1) second@(Pair hs2 ns2) =- compare (key first) (key second) <> compare (hs1, ns1) (hs2, ns2)+ compare first second =+ compare (key first) (key second) <> comparePairSides first second where -- Hat minus Not; classification uses the state, never rounded overflow. key pair = case exactAccum state of@@ -249,19 +427,58 @@ min x y | x <= y = x | otherwise = y +-- | Compare Hat sequences first and Not sequences second, as in the old record.+comparePairSides :: forall v. Ord v => Pair v -> Pair v -> Ordering+{-# INLINE comparePairSides #-}+comparePairSides x y = compareHat x y <> compareNot x y+ where+ compareHat :: Pair v -> Pair v -> Ordering+ compareHat (HatOne a) (HatOne b) = compare a b+ compareHat (HatOne _) (NotOne _) = GT+ compareHat (NotOne _) (HatOne _) = LT+ compareHat (NotOne _) (NotOne _) = EQ+ compareHat (HatOne a) (PairSeq hs _) = oneSeq a hs+ compareHat (PairSeq hs _) (HatOne b) = seqOne hs b+ compareHat (NotOne _) (PairSeq hs _) = if Seq.null hs then EQ else LT+ compareHat (PairSeq hs _) (NotOne _) = if Seq.null hs then EQ else GT+ compareHat (PairSeq hs _) (PairSeq ks _) = compare hs ks+ compareNot :: Pair v -> Pair v -> Ordering+ compareNot (NotOne a) (NotOne b) = compare a b+ compareNot (NotOne _) (HatOne _) = GT+ compareNot (HatOne _) (NotOne _) = LT+ compareNot (HatOne _) (HatOne _) = EQ+ compareNot (NotOne a) (PairSeq _ ns) = oneSeq a ns+ compareNot (PairSeq _ ns) (NotOne b) = seqOne ns b+ compareNot (HatOne _) (PairSeq _ ns) = if Seq.null ns then EQ else LT+ compareNot (PairSeq _ ns) (HatOne _) = if Seq.null ns then EQ else GT+ compareNot (PairSeq _ ns) (PairSeq _ ms) = compare ns ms+ oneSeq :: v -> Seq v -> Ordering+ oneSeq a xs = case Seq.viewl xs of+ Seq.EmptyL -> GT+ b Seq.:< rest -> compare a b <> if Seq.null rest then EQ else LT+ seqOne :: Seq v -> v -> Ordering+ seqOne xs b = case Seq.viewl xs of+ Seq.EmptyL -> LT+ a Seq.:< rest -> compare a b <> if Seq.null rest then EQ else GT+ {-# INLINE nullPair #-} -- | Complexity: O(1) nullPair :: Pair v-nullPair = Pair Seq.empty Seq.empty+nullPair = mkPair Seq.empty Seq.empty {-# INLINE pairAppend #-} -- | Complexity: O(log(min(h1,h2)) + log(min(n1,n2))) -- where h1/h2 and n1/n2 are the lengths of the appended 'Seq's on each side. pairAppend :: Pair v -> Pair v -> Pair v-pairAppend (Pair x1 y1) (Pair x2 y2) =- let !hs = x1 Seq.>< x2- !ns = y1 Seq.>< y2- in Pair hs ns+pairAppend (HatOne a) (HatOne b) = mkPair (Seq.fromList [a, b]) Seq.empty+pairAppend (NotOne a) (NotOne b) = mkPair Seq.empty (Seq.fromList [a, b])+pairAppend (HatOne a) (NotOne b) = mkPair (Seq.singleton a) (Seq.singleton b)+pairAppend (NotOne a) (HatOne b) = mkPair (Seq.singleton b) (Seq.singleton a)+pairAppend (HatOne a) (PairSeq hs ns) = mkPair (a Seq.<| hs) ns+pairAppend (NotOne a) (PairSeq hs ns) = mkPair hs (a Seq.<| ns)+pairAppend (PairSeq hs ns) (HatOne a) = mkPair (hs Seq.|> a) ns+pairAppend (PairSeq hs ns) (NotOne a) = mkPair hs (ns Seq.|> a)+pairAppend (PairSeq hs ns) (PairSeq ks ms) = mkPair (hs Seq.>< ks) (ns Seq.>< ms) {-# INLINE pairUnion #-} -- | Set-style merge of two single-base projection results.@@ -280,10 +497,24 @@ -- -- Complexity: O(1). pairUnion :: Pair v -> Pair v -> Pair v-pairUnion (Pair x1 y1) (Pair x2 y2) =- let !hs = if Seq.null x1 then x2 else x1- !ns = if Seq.null y1 then y2 else y1- in Pair hs ns+pairUnion p@(HatOne _) (HatOne _) = p+pairUnion p@(NotOne _) (NotOne _) = p+pairUnion (HatOne a) (NotOne b) = mkPair (Seq.singleton a) (Seq.singleton b)+pairUnion (NotOne a) (HatOne b) = mkPair (Seq.singleton b) (Seq.singleton a)+pairUnion p@(HatOne a) (PairSeq _ ns)+ | Seq.null ns = p+ | otherwise = mkPair (Seq.singleton a) ns+pairUnion p@(NotOne a) (PairSeq hs _)+ | Seq.null hs = p+ | otherwise = mkPair hs (Seq.singleton a)+pairUnion p@(PairSeq hs ns) (HatOne a)+ | Seq.null hs = mkPair (Seq.singleton a) ns+ | otherwise = p+pairUnion p@(PairSeq hs ns) (NotOne a)+ | Seq.null ns = mkPair hs (Seq.singleton a)+ | otherwise = p+pairUnion (PairSeq hs ns) (PairSeq ks ms) =+ mkPair (if Seq.null hs then ks else hs) (if Seq.null ns then ms else ns) -- | A member of the redundant algebra. 'Zero' represents zero, @(:@)@ -- represents one term with a value and hat base, and 'Liner' stores multiple@@ -295,7 +526,7 @@ -- /derived from/ @_realg@ and must stay consistent with it: @_axisPosting@, -- @_idToBp@ and @_allBpIds@ must be exactly the component index, id↔base map and id set -- built from the keys of @_realg@ (as the internal @linerFromMap@ does). The--- wildcard projection path (@projWildMap@, @filterByAxis@) reads those indices and+-- wildcard projection path (@projWildMap@, @filterByNoteField@) reads those indices and -- will return wrong answers (silently, not an exception) if they disagree with -- @_realg@. The fields @_bpToId@ and @_nextBpId@ are currently unmaintained -- /poison/ (reserved for a dormant scheme) — forcing them throws. Always build@@ -311,7 +542,7 @@ Zero :: Alg v b Single :: !v -> !b -> Alg v b Liner :: { _realg :: !(Map.HashMap (BasePart b) (Pair v))- , _axisPosting :: ~(IntMap.IntMap (Map.HashMap AxisKey IntSet.IntSet))+ , _axisPosting :: ~AxisPosting , _bpToId :: ~(Map.HashMap (BasePart b) Int) , _idToBp :: ~(IntMap.IntMap (BasePart b)) , _nextBpId :: ~Int@@ -320,6 +551,9 @@ -- | Serialize an algebra in the 0.5 wire layout (tag 0 = 'Zero', tag 1 = -- one posting, tag 2 = the per-base map with each t'Pair' in sequence order).+-- Tag 2 writes blocks in the base 'Map.HashMap' traversal order, so equal+-- algebras can have different byte sequences across versions of @hashable@.+-- Compare decoded values to check equality. -- -- Decoding is a construction boundary, like '.@': it fails on a value for -- which 'valueError' is 'Just' (negative or non-finite), on a tag-1 posting@@ -371,7 +605,7 @@ count <- Binary.get :: Binary.Get Int pairs <- go count Map.empty let nonempty = Map.filter- (\(Pair hs ns) -> not (Seq.null hs && Seq.null ns)) pairs+ (not . pairNull) pairs pure $ if Map.null nonempty then Zero else linerFromMap nonempty _ -> fail ("Alg: unknown tag " ++ show tag) where@@ -381,56 +615,71 @@ go remaining !acc | remaining <= 0 = pure acc | otherwise = do- basis <- Binary.get- Pair hs ns <- Binary.get+ basis <- Binary.get+ decoded <- Binary.get if Map.member basis acc then fail "Alg: repeated base key" else do- mapM_ (\value -> case valueError value of- Just message -> fail ("Alg: " ++ show message)- Nothing -> pure ()) (hs Seq.>< ns)- let pair = Pair (Seq.filter (not . isZeroValue) hs)- (Seq.filter (not . isZeroValue) ns)+ let check :: v -> Binary.Get ()+ check value = case valueError value of+ Just message -> fail ("Alg: " ++ show message)+ Nothing -> pure ()+ case decoded of+ HatOne value -> check value+ NotOne value -> check value+ PairSeq hs ns -> mapM_ check hs >> mapM_ check ns+ let pair = filterPair (not . isZeroValue) (not . isZeroValue) decoded go (remaining - 1) (Map.insert basis pair acc) -type AxisPosting = IntMap.IntMap (Map.HashMap AxisKey IntSet.IntSet)+-- | An index from component positions and element keys to sets of base IDs.+type AxisPosting = IntMap.IntMap (Map.HashMap ElementKey SizedIds) +-- | A set of base IDs and its cardinality in the first field.+-- Invariant: insertion evaluates the cardinality before storing the pair.+type SizedIds = (Int, IntSet.IntSet)+ {-# INLINE emptyAxisPosting #-} -- | Complexity: O(1) emptyAxisPosting :: AxisPosting emptyAxisPosting = IntMap.empty {-# INLINE insertAxisPosting #-}--- | Complexity: O(d * (hash-insert + intset-insert))--- In practice this is near O(d), where d is the number of components in the base part.-insertAxisPosting :: [AxisKey] -> Int -> AxisPosting -> AxisPosting+-- | Insert a base ID once for each component position and element key.+-- For d components, this performs O(d) map updates and up to d set membership+-- checks and insertions.+insertAxisPosting :: [ElementKey] -> Int -> AxisPosting -> AxisPosting insertAxisPosting !keys !bpId !idx = snd $ L.foldl' step (0 :: Int, idx) keys where step (!axis, !acc) !k =- let !axisMap = IntMap.findWithDefault Map.empty axis acc- !ids0 = Map.lookupDefault IntSet.empty k axisMap- !ids1 = IntSet.insert bpId ids0- !axisMap' = Map.insert k ids1 axisMap- !acc' = IntMap.insert axis axisMap' acc+ let !axisMap = IntMap.findWithDefault Map.empty axis acc+ !axisMap' = Map.alter addId k axisMap+ !acc' = IntMap.insert axis axisMap' acc in (axis + 1, acc') + addId Nothing = Just (1, IntSet.singleton bpId)+ addId (Just sized@(count, ids))+ | IntSet.member bpId ids = Just sized+ | otherwise =+ let !count' = count + 1+ !ids' = IntSet.insert bpId ids+ in Just (count', ids')+ {-# INLINE queryAxisPosting #-}--- | Complexity: O(d + intersection cost)--- d is the number of components; intersections are performed in ascending set-size order.-queryAxisPosting :: [AxisKey] -> AxisPosting -> IntSet.IntSet -> IntSet.IntSet+-- | Find candidate base IDs for the concrete components of a query.+-- With d components and k matched sets, this performs up to d index lookups,+-- O(k log k) comparisons of cached cardinalities, and k - 1 intersections+-- (zero intersections when k is zero).+queryAxisPosting :: [ElementKey] -> AxisPosting -> IntSet.IntSet -> IntSet.IntSet queryAxisPosting !keys !idx !allIds = case matchedSets of- Left () -> IntSet.empty- Right [] -> allIds- -- 'L.sortOn' preserves length, so a non-empty 'xs' sorts to a non-empty- -- list; matching @(x:rest)@ here (rather than on a lazy let-binding) makes- -- exhaustiveness explicit and avoids the partial pattern warning.- Right xs@(_:_) ->- case L.sortOn IntSet.size xs of- (x:rest) -> L.foldl' IntSet.intersection x rest- [] -> allIds -- unreachable: xs is non-empty+ Left () -> IntSet.empty+ Right sets -> case L.sortOn fst sets of+ [] -> allIds+ ((_, ids) : rest) -> L.foldl' intersectIds ids rest where+ intersectIds acc (_, ids) = IntSet.intersection acc ids+ matchedSets = L.foldl' collect (Right []) (zip [0 :: Int ..] keys) @@ -446,12 +695,12 @@ -- A component with a wildcard inside it (e.g. @("a", wildcard)@) must -- not be looked up as an exact key; the final 'matchesQuery' check selects.- axisHasWildcard (AxisKey coordinate) = haveWildcard coordinate+ axisHasWildcard (ElementKey coordinate) = haveWildcard coordinate {-# INLINE axisHasWildcard #-} {-# INLINE linerFromMap #-}--- | Complexity: O(n * d * (hash-insert + intset-insert))--- n is the number of distinct base keys in the map.+-- | Build a 'Liner' with a lazy index. For n distinct bases with d components,+-- forcing the index performs O(n * d) map and set operations. linerFromMap :: (HatBaseClass b) => Map.HashMap (BasePart b) (Pair v) -> Alg v b@@ -473,15 +722,15 @@ (error "Liner internal: _nextBpId is not maintained (reserved for P1a); do not force") allIds where- ~(idx, idToBp, allIds) =+ ~(_, idx, idToBp, allIds) = Map.foldlWithKey'- (\(!idxAcc, !idToBpAcc, !allIdsAcc) bp _ ->- let !bpId = IntMap.size idToBpAcc- !idx' = insertAxisPosting (toAxisKeys bp) bpId idxAcc+ (\(!bpId, !idxAcc, !idToBpAcc, !allIdsAcc) bp _ ->+ let !nextId = bpId + 1+ !idx' = insertAxisPosting (toElementKeys bp) bpId idxAcc !idToBp' = IntMap.insert bpId bp idToBpAcc !allIds' = IntSet.insert bpId allIdsAcc- in (idx', idToBp', allIds'))- (emptyAxisPosting, IntMap.empty, IntSet.empty)+ in (nextId, idx', idToBp', allIds'))+ (0, emptyAxisPosting, IntMap.empty, IntSet.empty) m -- | Tests whether the member of the redundant algebra is zero (empty).@@ -551,29 +800,48 @@ -- of 'Alg' below now calls 'showValue'. The @Double@/@MoneyDouble@ 'showValue' -- implementations reproduce the old formatting byte-for-byte. -instance (HatVal v, HatBaseClass b) => Eq (Alg v b) where+-- | Compare the members of the redundant algebra. A 'Single' and a one-term+-- 'Liner' are equal when their hat bases and values match. Equality also+-- compares the order of values on each Hat and Not side of a base.+instance (HatVal v, HatBaseClass b) => Eq (Alg v b) where (==) Zero Zero = True (==) Zero _ = False (==) _ Zero = False (==) (v1:@b1) (v2:@b2) = (v1 == v2) && (b1 == b2) (==) (Liner m1 _ _ _ _ _) (Liner m2 _ _ _ _ _) = m1 == m2- (==) _ _ = False+ (==) single@(_ :@ _) (Liner entries _ _ _ _ _) =+ maybe False (single ==) (singleFromMap entries)+ (==) (Liner entries _ _ _ _ _) single@(_ :@ _) =+ maybe False (== single) (singleFromMap entries) (/=) x y = not (x == y) -instance (HatVal v, HatBaseClass b) => Ord (Alg v b) where+-- | Order 'Zero' first, one-term members next, and members with multiple+-- terms last. Compare one-term members by hat base and then by value.+-- Compare the remaining members by their maps, including the per-side+-- order of values. For lawful bases and values, @compare x y == EQ@+-- exactly when @x == y@.+instance forall v b. (HatVal v, HatBaseClass b) => Ord (Alg v b) where {-# INLINE compare #-} compare Zero Zero = EQ compare Zero _ = LT compare _ Zero = GT - compare (_:@_) (Liner _ _ _ _ _ _) = LT- compare (Liner _ _ _ _ _ _) (_:@_) = GT- compare (v1:@b1) (v2:@b2)- | b1 == b2 = compare v1 v2- | b1 > b2 = GT- | otherwise = LT -- b1 < b2 (Ord is total; otherwise keeps it exhaustive)-- compare (Liner m1 _ _ _ _ _) (Liner m2 _ _ _ _ _) = compare m1 m2+ compare left right = case (asSingle left, asSingle right) of+ (v1 :@ b1, v2 :@ b2)+ | b1 == b2 -> compare v1 v2+ | b1 > b2 -> GT+ | otherwise -> LT+ (_ :@ _, Liner {}) -> LT+ (Liner {}, _ :@ _) -> GT+ (Liner m1 _ _ _ _ _, Liner m2 _ _ _ _ _) -> compare m1 m2+ (Zero, Zero) -> EQ+ (Zero, _) -> LT+ (_, Zero) -> GT+ where+ asSingle :: Alg v b -> Alg v b+ asSingle algebra@(Liner entries _ _ _ _ _) =+ Maybe.fromMaybe algebra (singleFromMap entries)+ asSingle algebra = algebra (<) x y | compare x y == LT = True | otherwise = False@@ -595,6 +863,15 @@ min x y | x <= y = x | otherwise = y +-- | Read a one-term map as a singleton by inspecting at most two map entries.+{-# INLINE singleFromMap #-}+singleFromMap :: (HatVal v, HatBaseClass b)+ => Map.HashMap (BasePart b) (Pair v)+ -> Maybe (Alg v b)+singleFromMap entries = case Map.toList entries of+ [(basePart, pair)] -> singlePairToAlg basePart pair+ _ -> Nothing+ instance (HatVal v, HatBaseClass b) => Show (Alg v b) where show Zero = "0" show (v:@b) = (showValue v) ++ ":@" ++ show b@@ -621,7 +898,7 @@ --- | union two trees+-- | Combine two algebras, appending the right-hand values on each base and side. -- -- >>> type Test = Alg Double (HatBase CountUnit) -- >>> x = 1.@Hat:<Yen .+ 1.@Not:<Amount :: Test@@ -650,7 +927,9 @@ | isZeroValue v2 = v1`Single`b1 | otherwise = insert b2 v2 (v1`Single`b1) -- If one side is a singleton-union x (v:@b) = insert b v x+union x@(Liner m _ _ _ _ _) (v:@b)+ | isZeroValue v = x+ | otherwise = insertLiner (flip pairAppend) b v m union (v:@b) x = insert b v x -- In the case of multiple terms@@ -658,7 +937,11 @@ {-# INLINE insert #-}--- | Complexity:+-- | Insert one term. Into a 'Liner', the term goes before the existing terms+-- for its base and side. Into a single term @w :\@ c@, the existing term+-- stays first, as in @(w :\@ c) .+ (v :\@ b)@.+--+-- Complexity: -- - into Zero or singleton: O(1) to O(d * index-build) -- - into Liner: O(n * d * index-build) due to rebuilding 'linerFromMap' -- where n is the number of distinct base keys after insertion.@@ -669,19 +952,21 @@ True -> insert b2 v2 $ linerFromMap $ Map.singleton (base b1)- $ nullPair {_hatSide = Seq.singleton v1}+ $ HatOne v1 False -> insert b2 v2 $ linerFromMap $ Map.singleton (base b1)- $ nullPair {_notSide = Seq.singleton v1}-insert !b !v (Liner m _ _ _ _ _) = case isHat b of- True -> insertLiner (nullPair {_hatSide = Seq.singleton v})- False -> insertLiner (nullPair {_notSide = Seq.singleton v})+ $ NotOne v1+insert !b !v (Liner m _ _ _ _ _) = insertLiner pairAppend b v m++{-# INLINE insertLiner #-}+insertLiner :: HatBaseClass b+ => (Pair v -> Pair v -> Pair v)+ -> b -> v -> Map.HashMap (BasePart b) (Pair v) -> Alg v b+insertLiner combine b v m =+ linerFromMap (Map.insertWith combine (base b) pairToInsert m) where- !bp = base b- insertLiner !pairToInsert =- let !m' = Map.insertWith pairAppend bp pairToInsert m- in linerFromMap m'+ pairToInsert = if isHat b then HatOne v else NotOne v ------------------------------------------------------------------ -- Monoid@@ -709,9 +994,9 @@ | isZeroValue v = acc | otherwise = let !p = if isHat b- then nullPair {_hatSide = Seq.singleton v}- else nullPair {_notSide = Seq.singleton v}- in Map.insertWith pairAppend (base b) p acc+ then HatOne v+ else NotOne v+ in Map.insertWith (flip pairAppend) (base b) p acc mergeAlgMap !acc (Liner m _ _ _ _ _) | Map.null m = acc | otherwise = Map.unionWith pairAppend acc m@@ -731,12 +1016,8 @@ -- | Merge multiple Algs by directly combining their internal HashMaps, -- building the AxisPosting index only once at the end. ----- Produces the same /multiset/ of postings as @unions@\/'mconcat', but the--- same-base sequence order differs (the bulk-merge accumulates a new same-base--- singleton in front of the previously merged values, whereas the pairwise--- union path interleaves differently). 'Eq'\/@Binary@ observe that order, and--- 'Double' can observe it through the sequential sums in 'barWithin'; see the--- characterization test @testSameBaseSeqOrderPathDependence@.+-- The result preserves the input traversal order on each base and side,+-- as 'fromList' does for a list. unionsMerge :: (HatVal n, Foldable f, HatBaseClass b) => f (Alg n b) -> Alg n b unionsMerge ts = let !m = Foldable.foldl' mergeAlgMap Map.empty ts@@ -753,7 +1034,7 @@ (.^) Zero = Zero (.^) (n:@ b) = n `Single` (revHat b) (.^) (Liner ms idx bpToId idToBp nextBpId allIds) = Liner- (Map.map (\ (Pair hs ns) -> Pair ns hs) ms)+ (Map.map hatPair ms) idx bpToId idToBp@@ -779,15 +1060,13 @@ | otherwise = scaled where scaled = Liner- (Map.map (\(Pair hs ns) -> Pair (fmap (x *) hs) (fmap (x *) ns)) ms)+ (Map.map (mapPair (x *)) ms) idx bpToId idToBp nextBpId allIds norm Zero = 0 norm (v:@_) = roundAccum (addAccum v emptyAccum) norm (Liner ms _ _ _ _ _) = roundAccum $- Map.foldl' (\total (Pair hs ns) ->- Foldable.foldl' (flip addAccum)- (Foldable.foldl' (flip addAccum) total hs) ns) emptyAccum ms+ Map.foldl' (foldPair (flip addAccum) (flip addAccum)) emptyAccum ms {-# INLINE (.-) #-} (.-) Zero = Zero@@ -814,8 +1093,8 @@ else finish side value finish side value | isZeroValue value = Nothing- | side == Hat = Just (Pair (Seq.singleton value) Seq.empty)- | otherwise = Just (Pair Seq.empty (Seq.singleton value))+ | side == Hat = Just (HatOne value)+ | otherwise = Just (NotOne value) {-# INLINE barWithin #-} barWithin _ Zero = Zero@@ -826,20 +1105,18 @@ False -> linerFromMap res where {-# INLINE f #-}- f p@(Pair hs ns) =- let !h = Foldable.foldl' (+) 0 hs- !n = Foldable.foldl' (+) 0 ns+ f p =+ let (!h, !n) = pairSums p in case (not (isErrorValue h || isErrorValue n) && abs (h - n) <= absTol tolerance + relTol tolerance * max (abs h) (abs n)) of -- scale-aware tolerance (WI-11) True -> Nothing- False -> case (Seq.length hs, Seq.length ns) of- -- Already in canonical form: singleton on winning side, empty on other- (1, 0) | h > n -> Just p- (0, 1) | n > h -> Just p+ False -> case p of+ HatOne _ | h > n -> Just p+ NotOne _ | n > h -> Just p _ -> case compare h n of- GT -> Just (Pair (Seq.singleton (h - n)) Seq.empty)- _ -> Just (Pair Seq.empty (Seq.singleton (n - h)))+ GT -> Just (HatOne (h - n))+ _ -> Just (NotOne (n - h)) {-# INLINE compress #-} compress Zero = Zero@@ -853,13 +1130,15 @@ | otherwise = linerFromMap reduced where reduced = Map.mapMaybe compressPair pairs- compressPair (Pair hs ns) =- let h = roundAccum (Foldable.foldl' (flip addAccum) emptyAccum hs)- n = roundAccum (Foldable.foldl' (flip addAccum) emptyAccum ns)- hats = if isZeroValue h then Seq.empty else Seq.singleton h- nots = if isZeroValue n then Seq.empty else Seq.singleton n- in if Seq.null hats && Seq.null nots then Nothing- else Just (Pair hats nots)+ compressPair pair =+ let (hatState, notState) = pairStates pair+ h = roundAccum hatState+ n = roundAccum notState+ in case (isZeroValue h, isZeroValue n) of+ (True, True) -> Nothing+ (False, True) -> Just (HatOne h)+ (True, False) -> Just (NotOne n)+ (False, False) -> Just (mkPair (Seq.singleton h) (Seq.singleton n)) -- | Visit full-base pairs without rebuilding every posting's base.@@ -870,17 +1149,17 @@ foldPairs collect initial (value :@ postingBase) | isZeroValue value = initial | isHat postingBase = collect initial (base postingBase)- (Pair (Seq.singleton value) Seq.empty)+ (HatOne value) | otherwise = collect initial (base postingBase)- (Pair Seq.empty (Seq.singleton value))+ (NotOne value) foldPairs collect initial (Liner pairs _ _ _ _ _) = Map.foldlWithKey' collect initial pairs -- | Exact Not-minus-Hat residual for one complete base. netPairState :: HatVal n => Pair n -> Accum n {-# INLINE netPairState #-}-netPairState (Pair hats nots) = mergeAccum- (Foldable.foldl' (flip addAccum) emptyAccum nots)- (negateAccum (Foldable.foldl' (flip addAccum) emptyAccum hats))+netPairState pair = mergeAccum nots (negateAccum hats)+ where+ (hats, nots) = pairStates pair -- | Distinguish nonfinite inputs from finite overflow of the rounded output. hasNonfiniteState :: HatVal n => Accum n -> Bool@@ -920,11 +1199,7 @@ vals (Liner m _ _ _ _ _) = reverse $ Map.foldl'- (\acc (Pair hs ns) ->- Foldable.foldl' (flip (:))- (Foldable.foldl' (flip (:)) acc hs)- ns- )+ (foldPair (flip (:)) (flip (:))) [] m @@ -938,8 +1213,7 @@ bases (Liner m _ _ _ _ _) = Map.foldlWithKey' f [] m where f :: (HatVal v, HatBaseClass b) => [b] -> BasePart b -> Pair v -> [b]- f xs b (Pair {_hatSide = hs, _notSide = ns})- = Foldable.foldl' (g Not b) (Foldable.foldl' (g Hat b) xs hs) ns+ f xs b = foldPair (g Hat b) (g Not b) xs g :: (HatVal v, HatBaseClass b) => Hat -> BasePart b -> [b] -> v -> [b] g h b ys _ = (merge h b):ys@@ -967,12 +1241,11 @@ -- | Summation function that applies a function to each element of a list and sums the results. -- Complexity: O(sum of HashMap union costs over produced members of the redundant algebra). ----- Uses the bulk-merge path ('unionsMerge'); see there for the same-base--- sequence-order caveat relative to 'fromList'\/'mconcat'.+-- Each base and side retains terms in list order, as in 'unionsMerge'. -- -- >>> type Test = Alg Double (HatBase CountUnit)--- >>> sigma [1,2] (\x -> x.@Hat:<Yen)--- 1.00:@Hat:<Yen .+ 2.00:@Hat:<Yen+-- >>> vals (sigma [1,2,3] (\x -> x .@ Hat :< Yen) :: Test)+-- [1.0,2.0,3.0] {-# INLINE sigma #-} sigma :: (HatVal v, HatBaseClass b) => [a] -> (a -> Alg v b) -> Alg v b@@ -1029,8 +1302,10 @@ toList (Liner m _ _ _ _ _) = Map.foldlWithKey' f [] m where f :: (HatVal v, HatBaseClass b) => [Alg v b] -> BasePart b -> Pair v -> [Alg v b]- f xs b Pair {_hatSide = hs, _notSide = ns}- = Foldable.foldl' (g Hat b) (Foldable.foldl' (g Not b) xs ns) hs+ f xs b (HatOne v) = g Hat b xs v+ f xs b (NotOne v) = g Not b xs v+ f xs b (PairSeq hs ns) =+ Foldable.foldl' (g Hat b) (Foldable.foldl' (g Not b) xs ns) hs g :: (HatVal v, HatBaseClass b) => Hat -> BasePart b -> [Alg v b] -> v -> [Alg v b] g h b ys v@@ -1048,7 +1323,7 @@ -- accumulator, such as list append, this is only an ordinary left fold: its -- result records the actual traversal order and can distinguish different -- sequence orders of the same entry multiset.-foldEntries :: (HatVal v, HatBaseClass b)+foldEntries :: forall v b acc. (HatVal v, HatBaseClass b) => (acc -> v -> b -> acc) -> acc -> Alg v b@@ -1060,11 +1335,13 @@ foldEntries f !acc (Liner m _ _ _ _ _) = Map.foldlWithKey' step acc m where- step !acc0 !bp (Pair hs ns) =+ step :: acc -> BasePart b -> Pair v -> acc+ step !acc0 !bp pair = let !hatBase = merge Hat bp !notBase = merge Not bp- !acc1 = Foldable.foldl' (\a v -> if isZeroValue v then a else f a v hatBase) acc0 hs- in Foldable.foldl' (\a v -> if isZeroValue v then a else f a v notBase) acc1 ns+ in foldPair (entry hatBase) (entry notBase) acc0 pair+ entry :: b -> acc -> v -> acc+ entry b a v = if isZeroValue v then a else f a v b {-# INLINE toASCList #-} -- | Complexity: O(s log s), dominated by sorting the list representation.@@ -1117,21 +1394,39 @@ -> Pair v -> DMap (BasePart b) (Pair v) -> DMap (BasePart b) (Pair v)- p fn b Pair {_hatSide=hs, _notSide=ns} accDList =+ p fn b (HatOne v) accDList = pOne fn Hat b v accDList+ p fn b (NotOne v) accDList = pOne fn Not b v accDList+ p fn b (PairSeq hs ns) accDList = let (dl1, hs2) = q fn Hat b hs (dl2, ns2) = q fn Not b ns prefix = dappendMap dl1 dl2 in case (Seq.null hs2, Seq.null ns2) of (True,True) -> dappendMap prefix accDList (True,False) -> dappendMap prefix- . dappendMap (dsingleMap (b, nullPair{_notSide = ns2}))+ . dappendMap (dsingleMap (b, mkPair Seq.empty ns2)) $ accDList (False,True) -> dappendMap prefix- . dappendMap (dsingleMap (b, nullPair{_hatSide = hs2}))+ . dappendMap (dsingleMap (b, mkPair hs2 Seq.empty)) $ accDList (False,False) -> dappendMap prefix- . dappendMap (dsingleMap (b, Pair hs2 ns2))+ . dappendMap (dsingleMap (b, mkPair hs2 ns2)) $ accDList+ pOne :: (HatVal v, HatBaseClass b)+ => (Alg v b -> Alg v b)+ -> Hat+ -> BasePart b+ -> v+ -> DMap (BasePart b) (Pair v)+ -> DMap (BasePart b) (Pair v)+ pOne fn h bp v rest = case fn (v `Single` merge h bp) of+ Zero -> rest+ v2 :@ b2+ | isZeroValue v2 -> rest+ | b2 == (merge h bp) -> Map.insertWith pairAppend bp+ (if isHat h then HatOne v2 else NotOne v2) . rest+ | isHat (hat b2) -> Map.insertWith pairAppend (base b2) (HatOne v2) . rest+ | otherwise -> Map.insertWith pairAppend (base b2) (NotOne v2) . rest+ {-# INLINE q #-} q :: (HatVal v, HatBaseClass b) => (Alg v b -> Alg v b)@@ -1159,10 +1454,10 @@ -- element changes the base. | b2 == (merge h b) -> (dlAcc, v2 Seq.<| vsAcc) | isHat (hat b2) -> (dappendMap dlAcc (dsingleMap ( base b2- ,nullPair{_hatSide = Seq.singleton v2}))+ ,HatOne v2)) ,vsAcc ) | otherwise -> (dappendMap dlAcc (dsingleMap ( base b2- ,nullPair{_notSide = Seq.singleton v2} ))+ ,NotOne v2 )) ,vsAcc ) -- | Map every posting to exactly one posting. The typed form of 'map'.@@ -1182,7 +1477,9 @@ mkAlgFromMap $ Map.foldrWithKey addPair id m Map.empty where {-# INLINE addPair #-}- addPair bp (Pair hs ns) accDMap =+ addPair bp (HatOne v) accDMap = mapOne (merge Hat bp) id v . accDMap+ addPair bp (NotOne v) accDMap = mapOne (merge Not bp) id v . accDMap+ addPair bp (PairSeq hs ns) accDMap = mapSide Hat bp hs . mapSide Not bp ns . accDMap {-# INLINE mapSide #-}@@ -1198,8 +1495,8 @@ {-# INLINE postingPair #-} postingPair v b- | isHat (hat b) = nullPair {_hatSide = Seq.singleton v}- | otherwise = nullPair {_notSide = Seq.singleton v}+ | isHat (hat b) = HatOne v+ | otherwise = NotOne v -- Difference-map (endo) used by 'map' to accumulate Liner rebuilds in O(1). -- NB. The plain difference-list helpers (dnil/dappend/dsingle/dToList/dFromList)@@ -1224,35 +1521,21 @@ -- 2.00:@Not:<Yen .+ 2.00:@Hat:<Amount -filter :: (HatVal v, HatBaseClass b) => (Alg v b -> Bool) -> Alg v b -> Alg v b+filter :: forall v b. (HatVal v, HatBaseClass b) => (Alg v b -> Bool) -> Alg v b -> Alg v b filter _ Zero = Zero filter f (v:@b) | f (v`Single`b) = v`Single`b | otherwise = Zero filter f (Liner m _ _ _ _ _) =- -- Build a new Map using mapMaybeWithKey- let m' = Map.mapMaybeWithKey- (\basePart (Pair hs ns) ->- -- Filter each of hs and ns- let hs' = filterSide basePart Hat hs- ns' = filterSide basePart Not ns- in- -- Remove the entry (Nothing) if both become empty- if Seq.null hs' && Seq.null ns'- then Nothing- else Just (Pair hs' ns'))- m- in- -- If the resulting Map is empty, return Zero; otherwise Liner m'- if Map.null m' then Zero else linerFromMap m'+ let selected = Map.mapMaybeWithKey select m+ in if Map.null selected then Zero else linerFromMap selected where- ----------------------------------------------------------------- -- Filter function that constructs "v:@(merge h basePart)" from- -- basePart and Hat/Not, and tests whether it satisfies predicate f- ----------------------------------------------------------------- -- filterSide :: BasePart b -> Hat -> Seq v -> Seq v- {-# INLINE filterSide #-}- filterSide bp h = Seq.filter (\val -> f (val `Single` merge h bp))+ select :: BasePart b -> Pair v -> Maybe (Pair v)+ select bp pair =+ let kept = filterPair (accept Hat bp) (accept Not bp) pair+ in if pairNull kept then Nothing else Just kept+ accept :: Hat -> BasePart b -> v -> Bool+ accept h bp val = f (val `Single` merge h bp) ------------------------------------------------------------ -- | Relabel the /base part/ of every term, preserving the Hat\/Not structure@@ -1269,10 +1552,8 @@ -- order but retains, for every full Hat\/Not base, the multiset of values. -- The functor and additive laws at this layer are: ----- * @mapBasePart id x@ and @x@ are equal through ℘. Raw equality can fail when--- @x@ is a one-key, one-value @Liner@ produced by 'bar' or filtering:--- rebuilding it chooses the singleton @(:@)@ representation, and 'Eq'--- distinguishes those constructors.+-- * For valid algebras, @mapBasePart id x == x@. When rebuilding a one-term+-- 'Liner' as a 'Single', 'Eq' compares the same value and hat base. -- * @mapBasePart (g . f) x@ and -- @mapBasePart g (mapBasePart f x)@ are equal through ℘, but need not be raw -- equal.@@ -1286,8 +1567,7 @@ -- * Algebraically, @bar (mapBasePart f (bar x))@ and -- @bar (mapBasePart f x)@ are equal through ℘ whenever the implementation's -- rounding of a source-base residual does not change the cancellation after--- relabelling (always on exact values). Raw equality can additionally--- distinguish singleton from one-key @Liner@.+-- relabelling (always on exact values). -- -- In particular, @mapBasePart f (bar x) == bar (mapBasePart f x)@ is false in -- general: distinct source bases may collide only after relabelling. When@@ -1332,9 +1612,9 @@ -- the per-side sequence order. Through ℘: -- -- * @extendBy h (x .+ y)@ equals @extendBy h x .+ extendBy h y@.--- * @extendBy (:\@)@ is the identity. Raw equality can fail because the--- result is rebuilt by a fold: the per-side order and the--- singleton-versus-@Liner@ representation may differ from @x@.+-- * For valid algebras, @extendBy (.\@) x == x@. The substitution rebuilds+-- each @v :\@ b@ term and the fold preserves the order of values on each+-- Hat and Not side of a base. -- * @mapBasePart f x@ equals -- @extendBy (\\v b -> v :\@ merge (hat b) (f (base b))) x@. -- * @norm (extendBy h x)@ equals the sum of @norm (h v b)@ over the entries of@@ -1391,10 +1671,10 @@ -- -- Complexity: -- exact single-key path: expected O(1)--- wildcard single-key path: O(queryAxisPosting + c * verify)+-- wildcard single-key path: index lookup, sorting by cached cardinality, set+-- intersections, and one lookup and verification step per candidate base.+-- The first wildcard query also builds the index. -- multi-pattern path: O(sum pattern costs + union costs)------ where c is candidate count returned by the posting index. -- >>> type Test = Alg Double (HatBase CountUnit) -- >>> x = 1.@Hat:<Yen .+ 1.@Not:<Amount :: Test -- >>> y = 2.@Not:<Yen .+ 2.@Hat:<Amount :: Test@@ -1459,11 +1739,13 @@ {-# INLINE choosePairByHat #-} -- | Complexity: O(1) choosePairByHat :: Hat -> Pair v -> Pair v-choosePairByHat h Pair {_hatSide = hs, _notSide = ns} =- case h of- Hat -> nullPair {_hatSide = hs}- Not -> nullPair {_notSide = ns}- HatNot -> Pair {_hatSide = hs, _notSide = ns}+choosePairByHat HatNot p = p+choosePairByHat Hat p@(HatOne _) = p+choosePairByHat Not p@(NotOne _) = p+choosePairByHat Hat (NotOne _) = nullPair+choosePairByHat Not (HatOne _) = nullPair+choosePairByHat Hat (PairSeq hs _) = mkPair hs Seq.empty+choosePairByHat Not (PairSeq _ ns) = mkPair Seq.empty ns {-# INLINE projExactMap #-} -- | Exact (non-wildcard) single-base projection: a direct 'Map.lookup' on the@@ -1486,9 +1768,8 @@ projExactMap b m = case Map.lookup bp m of Nothing -> Map.empty Just p -> case choosePairByHat h p of- selected@(Pair hs ns) -> case (Seq.null hs, Seq.null ns) of- (True, True) -> Map.empty- _ -> Map.singleton bp selected+ selected | pairNull selected -> Map.empty+ | otherwise -> Map.singleton bp selected where !bp = base b !h = hat b@@ -1498,7 +1779,8 @@ -- ('queryAxisPosting'), so it necessarily forces the index. Only invoked when -- 'haveWildcard' holds. ----- Complexity: O(queryAxisPosting + c * verify).+-- The query uses cached set cardinalities to order intersections, then looks up+-- and verifies each candidate base. The index is built on first use. projWildMap :: (HatBaseClass b) => b@@ -1508,7 +1790,7 @@ -> IntSet.IntSet -> Map.HashMap (BasePart b) (Pair v) projWildMap b m idx idToBp allIds =- let !ids = queryAxisPosting (toAxisKeys bp) idx allIds+ let !ids = queryAxisPosting (toElementKeys bp) idx allIds in IntSet.foldl' (\acc bpId -> case IntMap.lookup bpId idToBp of Nothing -> acc@@ -1516,9 +1798,8 @@ Nothing -> acc Just p | matchesQuery bp bp0 -> case choosePairByHat h p of- selected@(Pair hs ns) -> case (Seq.null hs, Seq.null ns) of- (True, True) -> acc- _ -> Map.insert bp0 selected acc+ selected | pairNull selected -> acc+ | otherwise -> Map.insert bp0 selected acc | otherwise -> acc) Map.empty ids@@ -1538,10 +1819,9 @@ {-# INLINE singlePairToAlg #-} -- | Complexity: O(1) singlePairToAlg :: (HatVal v, HatBaseClass b) => BasePart b -> Pair v -> Maybe (Alg v b)-singlePairToAlg b (Pair hs ns) = case (Seq.viewl hs, Seq.viewl ns) of- (Seq.EmptyL, n Seq.:< nsRest) | Seq.null nsRest -> Just (n `Single` merge Not b)- (h Seq.:< hsRest, Seq.EmptyL) | Seq.null hsRest -> Just (h `Single` merge Hat b)- _ -> Nothing+singlePairToAlg b (HatOne v) = Just (v `Single` merge Hat b)+singlePairToAlg b (NotOne v) = Just (v `Single` merge Not b)+singlePairToAlg _ (PairSeq _ _) = Nothing ------------------------------------------------------------------ @@ -1852,13 +2132,15 @@ decBy kf (Liner m _ _ _ _ _) = M.map mkAlgFromMap (Map.foldlWithKey' step M.empty m) where- step !acc !bp (Pair hs ns) =+ step !acc !bp p@(HatOne _) = insertSide (merge Hat bp) bp p acc+ step !acc !bp p@(NotOne _) = insertSide (merge Not bp) bp p acc+ step !acc !bp (PairSeq hs ns) = let !acc1 = if Seq.null hs then acc- else insertSide (merge Hat bp) bp (nullPair {_hatSide = hs}) acc+ else insertSide (merge Hat bp) bp (mkPair hs Seq.empty) acc in if Seq.null ns then acc1- else insertSide (merge Not bp) bp (nullPair {_notSide = ns}) acc1+ else insertSide (merge Not bp) bp (mkPair Seq.empty ns) acc1 {-# INLINE insertSide #-} insertSide hb bp p acc = case kf hb of Nothing -> acc
src/ExchangeAlgebra/Algebra/Element.hs view
@@ -19,10 +19,10 @@ wildcard = CompanyWildcard @ -Use t'Wild' for an element type whose values all have meaning, such as-@Day@, @TimeOfDay@, or a custom identifier. Wrap ordinary elements in-'Exactly' and use the v'Wild' constructor as the wildcard. The underlying type-can be used without defining its own 'Element' instance.+Use @Wild Day@ and @Wild TimeOfDay@ for date and time elements in a base.+Wrap a concrete date or time in 'Exactly' and use the v'Wild' constructor+as the wildcard. You can also wrap a custom identifier whose type has+no 'Element' instance. >>> import Data.Time (TimeOfDay, midnight) >>> matchesQuery (Exactly midnight) (Wild :: Wild TimeOfDay)@@ -33,11 +33,10 @@ == Import guidance Import 'Element' and its associated symbols from-"ExchangeAlgebra.Algebra.Element". The old-"ExchangeAlgebra.Algebra.Base.Element" module is deprecated.+"ExchangeAlgebra.Algebra.Element". -} module ExchangeAlgebra.Algebra.Element- ( Element(..), AxisKey(..), axisIsWildcard, AxisDecompose(..), (.#)+ ( Element(..), ElementKey(..), elementKeyIsWildcard, HasElementKeys(..), (.#) , Name, Subject, CountUnit(..), Wild(..), matchesQuery, Hashable(..), Generic ) where
src/ExchangeAlgebra/Algebra/Element/Representation.hs view
@@ -7,9 +7,9 @@ module ExchangeAlgebra.Algebra.Element.Representation ( Element(..)- , AxisKey(..)- , axisIsWildcard- , AxisDecompose(..)+ , ElementKey(..)+ , elementKeyIsWildcard+ , HasElementKeys(..) , (.#) , Name , Subject@@ -22,8 +22,7 @@ import qualified Data.Text as T import Data.Text (Text)-import qualified Data.Time as Time-import Data.Time+import Data.Time (Day, TimeOfDay(..), toModifiedJulianDay) import GHC.Generics (Generic) import Data.Hashable import Data.Typeable (Typeable, cast, typeOf)@@ -164,37 +163,37 @@ -- | An existential type that holds one element of a base with its type erased. -- Used to decompose multi-dimensional bases (tuples) into one key per component position.-data AxisKey = forall a. Element a => AxisKey !a+data ElementKey = forall a. Element a => ElementKey !a -- | Force the stored element to weak head normal form without requiring 'NFData' -- from every user-defined 'Element'.-instance NFData AxisKey where- rnf (AxisKey axis) = axis `seq` ()+instance NFData ElementKey where+ rnf (ElementKey axis) = axis `seq` () -instance Eq AxisKey where- AxisKey x == AxisKey y = case cast y of+instance Eq ElementKey where+ ElementKey x == ElementKey y = case cast y of Nothing -> False Just y' -> x == y' -instance Hashable AxisKey where- hashWithSalt salt (AxisKey x) = salt `hashWithSalt` (typeOf x) `hashWithSalt` x+instance Hashable ElementKey where+ hashWithSalt salt (ElementKey x) = salt `hashWithSalt` (typeOf x) `hashWithSalt` x -- | Test whether the stored element is its wildcard.-{-# INLINE axisIsWildcard #-}-axisIsWildcard :: AxisKey -> Bool-axisIsWildcard (AxisKey x) = isWildcard x+{-# INLINE elementKeyIsWildcard #-}+elementKeyIsWildcard :: ElementKey -> Bool+elementKeyIsWildcard (ElementKey x) = isWildcard x --- | A type class for decomposing a base into one t'AxisKey' per component position.+-- | A type class for decomposing a base into one t'ElementKey' per component position. -- Overlapping instances are defined for tuple types so that each component--- is decomposed into a separate t'AxisKey'.+-- is decomposed into a separate t'ElementKey'. -- -- Complexity: O(k) (k is the number of tuple components)-class (Element a) => AxisDecompose a where- toAxisKeys :: a -> [AxisKey]+class (Element a) => HasElementKeys a where+ toElementKeys :: a -> [ElementKey] -instance {-# OVERLAPPABLE #-} Element a => AxisDecompose a where- {-# INLINE toAxisKeys #-}- toAxisKeys a = [AxisKey a]+instance {-# OVERLAPPABLE #-} Element a => HasElementKeys a where+ {-# INLINE toElementKeys #-}+ toElementKeys a = [ElementKey a] -- | Shorthand notation for the wildcard. An alias for @wildcard@. -- Write @(.#)@ when specifying patterns in projections and transfer transformations.@@ -253,25 +252,12 @@ instance Hashable Day where hashWithSalt salt day = hashWithSalt salt (toModifiedJulianDay day) --- | The wildcard is 'Time.midnight', so an element recorded at 00:00 is--- indistinguishable from "no time of day". Use @Wild TimeOfDay@ to include midnight--- as an ordinary element.-instance Element TimeOfDay where- wildcard = Time.midnight---- | The wildcard is @'ModifiedJulianDay' 0@ (1858-11-17), so that date is--- indistinguishable from "no date". Use @Wild Day@ to include every date--- as an ordinary element.-instance Element Day where- wildcard = ModifiedJulianDay 0- ------------------------------------------------------------------ -- | An element type extended with a wildcard from outside the type. -- -- Use it when the underlying element type has no value to spare for the--- wildcard, such as 'Day' or t'TimeOfDay': every date and every time of day is--- a meaningful element, so @'Exactly' 'Time.midnight'@ remains an ordinary--- time and only v'Wild' is the wildcard.+-- wildcard, such as 'Day' or t'TimeOfDay'. For example, @'Exactly' midnight@+-- represents the ordinary time 00:00. The v'Wild' constructor is the wildcard. -- -- * In a ledger entry, v'Wild' records that the component does not apply -- (for example, a transaction recorded without a time of day).@@ -336,9 +322,9 @@ x -> x instance {-# OVERLAPPING #-} (Element a, Element b)- => AxisDecompose (a, b) where- {-# INLINE toAxisKeys #-}- toAxisKeys (a, b) = [AxisKey a, AxisKey b]+ => HasElementKeys (a, b) where+ {-# INLINE toElementKeys #-}+ toElementKeys (a, b) = [ElementKey a, ElementKey b] instance (Element a, Element b, Element c) => Element (a, b, c) where@@ -373,9 +359,9 @@ ((b1, b2), b3) instance {-# OVERLAPPING #-} (Element a, Element b, Element c)- => AxisDecompose (a, b, c) where- {-# INLINE toAxisKeys #-}- toAxisKeys (a, b, c) = [AxisKey a, AxisKey b, AxisKey c]+ => HasElementKeys (a, b, c) where+ {-# INLINE toElementKeys #-}+ toElementKeys (a, b, c) = [ElementKey a, ElementKey b, ElementKey c] instance (Element a, Element b, Element c, Element d)@@ -415,9 +401,9 @@ ((b1, b2, b3), b4) instance {-# OVERLAPPING #-} (Element a, Element b, Element c, Element d)- => AxisDecompose (a, b, c, d) where- {-# INLINE toAxisKeys #-}- toAxisKeys (a, b, c, d) = [AxisKey a, AxisKey b, AxisKey c, AxisKey d]+ => HasElementKeys (a, b, c, d) where+ {-# INLINE toElementKeys #-}+ toElementKeys (a, b, c, d) = [ElementKey a, ElementKey b, ElementKey c, ElementKey d] instance (Element a, Element b, Element c, Element d, Element e)@@ -461,9 +447,15 @@ ((b1, b2, b3, b4), b5) instance {-# OVERLAPPING #-} (Element a, Element b, Element c, Element d, Element e)- => AxisDecompose (a, b, c, d, e) where- {-# INLINE toAxisKeys #-}- toAxisKeys (a, b, c, d, e) = [AxisKey a, AxisKey b, AxisKey c, AxisKey d, AxisKey e]+ => HasElementKeys (a, b, c, d, e) where+ {-# INLINE toElementKeys #-}+ toElementKeys (a, b, c, d, e) =+ [ ElementKey a+ , ElementKey b+ , ElementKey c+ , ElementKey d+ , ElementKey e+ ] instance (Element a, Element b, Element c, Element d, Element e, Element f)@@ -510,9 +502,9 @@ ((b1, b2, b3, b4, b5), b6) instance {-# OVERLAPPING #-} (Element a, Element b, Element c, Element d, Element e, Element f)- => AxisDecompose (a, b, c, d, e, f) where- {-# INLINE toAxisKeys #-}- toAxisKeys (a, b, c, d, e, f) = [AxisKey a, AxisKey b, AxisKey c, AxisKey d, AxisKey e, AxisKey f]+ => HasElementKeys (a, b, c, d, e, f) where+ {-# INLINE toElementKeys #-}+ toElementKeys (a, b, c, d, e, f) = [ElementKey a, ElementKey b, ElementKey c, ElementKey d, ElementKey e, ElementKey f] instance (Element a, Element b, Element c, Element d, Element e, Element f, Element g)@@ -562,9 +554,9 @@ ((b1, b2, b3, b4, b5, b6), b7) instance {-# OVERLAPPING #-} (Element a, Element b, Element c, Element d, Element e, Element f, Element g)- => AxisDecompose (a, b, c, d, e, f, g) where- {-# INLINE toAxisKeys #-}- toAxisKeys (a, b, c, d, e, f, g) = [AxisKey a, AxisKey b, AxisKey c, AxisKey d, AxisKey e, AxisKey f, AxisKey g]+ => HasElementKeys (a, b, c, d, e, f, g) where+ {-# INLINE toElementKeys #-}+ toElementKeys (a, b, c, d, e, f, g) = [ElementKey a, ElementKey b, ElementKey c, ElementKey d, ElementKey e, ElementKey f, ElementKey g] -- | One-way wildcard query matching. The query is the pattern. -- Complexity: O(k) (k is the number of tuple components).
src/ExchangeAlgebra/Algebra/Internal.hs view
@@ -28,7 +28,7 @@ import "ExchangeAlgebra.Algebra" instead unless you are writing a test or an engine that must see 'Liner'. - Released under the OWL license+ Released under the MIT license Package for Exchange Algebra defined by Hiroshi Deguchi. @@ -50,9 +50,9 @@ , BaseForSingleHat(..) , HatBase(..) , Element(..)- , AxisKey(..)- , axisIsWildcard- , AxisDecompose(..)+ , ElementKey(..)+ , elementKeyIsWildcard+ , HasElementKeys(..) , (.#) , Name , Subject@@ -64,7 +64,13 @@ , isNearlyNum , Redundant(..) , HatVal(..)- , Pair(..)+ , Pair( HatOne+ , NotOne+ , PairSeq+ , Pair+ , _hatSide+ , _notSide+ ) , Alg(.., (:@), _val, _hatBase) , linerFromMap , isZero
src/ExchangeAlgebra/Algebra/Posting.hs view
@@ -29,8 +29,7 @@ -- @ -- -- Import "ExchangeAlgebra.Accounting.Account" alongside this module when--- the posting base uses account titles. The old "ExchangeAlgebra.Posting"--- path re-exports the same types and functions during the transition.+-- the base uses account titles. module ExchangeAlgebra.Algebra.Posting ( -- * Posting values Posted@@ -152,8 +151,8 @@ -- | Postings built through 'entry' and 'Monoid', without implicit cancellation -- or compression. Equality and display delegate to the underlying 'Alg'.--- Equality is structural and depends on construction order. To compare--- multisets of postings instead, compare the results of @toASCList . postingAlg@.+-- Equality compares the order of values on each Hat and Not side of a base.+-- To compare multisets of postings, compare the results of @toASCList . postingAlg@. -- (0.6.0.0: polymorphic in the value type @v@; 0.5.x fixed @v = Double@.) -- The value type is nominal for the same reason as in t'Posted'. type role Posting nominal nominal@@ -173,11 +172,11 @@ -- > postingAlg (a <> b) == (postingAlg a .+ postingAlg b) -- -- This law uses 'Alg' equality without a tolerance for every 'HatBaseClass'--- instance, so it also preserves the multiset of postings. Associativity--- holds as equality of posting multisets, using--- @sameMultiset x y = toASCList x == toASCList y@:+-- instance. Associativity holds under the same equality, because '(.+)'+-- keeps the terms on each base and side in left-to-right order for either+-- grouping: ----- > sameMultiset (postingAlg ((a <> b) <> c)) (postingAlg (a <> (b <> c)))+-- > postingAlg ((a <> b) <> c) == postingAlg (a <> (b <> c)) -- -- Complexity: the same as '(.+)' on the underlying algebras. instance (HatVal v, HatBaseClass b) => Semigroup (Posting v b) where
src/ExchangeAlgebra/Algebra/Transfer/Representation.hs view
@@ -31,11 +31,10 @@ a successful application returning @Right entries@. A source wildcard matches any stored element; a concrete source matches only itself. * Relation: @obs (a .+ entries)@ equals the observation of independently- rewriting each matched posting to its rule's target and scaled value;+ moving each matched term to its rule's target with its original value; unmatched postings remain unchanged. * Observation: @obs@ as defined above, including every target base.-* Tolerance: relative @1e-9@; tested values are integers in @1..1000000@,- and coefficients are @2@, @3@, @0.5@ and @4@.+* Tolerance: relative @1e-9@; tested values are integers in @1..1000000@. * Instances: 'Double' and @MoneyDecimal@ with flat @HatBase@ tuples. === L4: canonical form@@ -66,9 +65,6 @@ , TransferApplyError(..) , mkTransferRules , rulesToList- , relabel- , scaleBy- , divideBy , transferEntries , collapseEntries , collapseNetEntries@@ -78,7 +74,9 @@ ) where import Data.Binary (Binary(..))-import Data.Hashable (Hashable)+import Data.Binary.Get (getWord8)+import Data.Binary.Put (putWord8)+import Data.Hashable (Hashable(..)) import Data.List (find, sortOn, tails) import GHC.Generics (Generic) import ExchangeAlgebra.Algebra.Core.Representation (Alg(Single))@@ -98,15 +96,20 @@ -- | How a rule changes the value it moves. data TransferScale v = Relabel -- ^ Keep the value.- | MulBy v -- ^ Multiply by a positive finite coefficient.- | DivBy v -- ^ Divide by a positive finite coefficient. deriving (Eq, Ord, Show, Generic) -{-# DEPRECATED MulBy, DivBy "A factor on the destination only does not balance. Use mapPosting to convert units, or Portion of ExchangeAlgebra.Accounting.Transfer to move a share." #-}--instance Binary v => Binary (TransferScale v)+-- Keep the original wire tag for the supported operation.+instance Binary v => Binary (TransferScale v) where+ put Relabel = putWord8 0+ get = do+ tag <- getWord8+ case tag of+ 0 -> pure Relabel+ _ -> fail "TransferScale: unknown or removed operation" -instance Hashable v => Hashable (TransferScale v)+-- Preserve the hash inputs for the retained operation in the old sum type.+instance Hashable v => Hashable (TransferScale v) where+ hashWithSalt salt Relabel = hashWithSalt (hashWithSalt salt (0 :: Int)) (0 :: Int) -- | A source pattern, target template and value operation. data TransferRule v b = TransferRule@@ -136,11 +139,9 @@ instance (Hashable v, Hashable b) => Hashable (TransferRules v b) --- | A construction failure. The first invalid coefficient in input order--- precedes overlap checks; overlaps report the first pair @(i,j)@, @i < j@.+-- | A construction failure. Overlaps report the first pair @(i,j)@, @i < j@. data TransferRuleError v b = OverlappingRules (TransferRule v b) (TransferRule v b) -- ^ Including duplicates.- | InvalidCoefficient (TransferRule v b) -- ^ Zero, negative or non-finite. deriving (Eq, Show) -- | A value operation produced a non-finite (or otherwise invalid) value.@@ -149,24 +150,17 @@ | NonFiniteBalance b -- ^ Closing base, normalized to Not. deriving (Show) --- | Validate coefficients, reject all overlapping source patterns, and sort.+-- | Reject all overlapping source patterns and sort. -- Matching is one-way: a wildcard in the ledger is a value, not a pattern. -- Overlap uses wildcard substitution recursively, including nested tuples; -- symmetric wildcard equality is insufficient. Complexity: O(r^2). mkTransferRules :: (HatVal v, HatBaseClass b) => [TransferRule v b] -> Either (TransferRuleError v b) (TransferRules v b)-mkTransferRules rules = case find invalidCoefficient rules of- Just rule -> Left (InvalidCoefficient rule)- Nothing -> case find overlaps pairs of- Just (first, second) -> Left (OverlappingRules first second)- Nothing -> Right (TransferRules (sortOn ruleFrom rules))+mkTransferRules rules = case find overlaps pairs of+ Just (first, second) -> Left (OverlappingRules first second)+ Nothing -> Right (TransferRules (sortOn ruleFrom rules)) where- invalidCoefficient rule = case ruleScale rule of- Relabel -> False- MulBy coefficient -> invalid coefficient- DivBy coefficient -> invalid coefficient- invalid coefficient = coefficient <= zeroValue || isErrorValue coefficient pairs = [(first, second) | first : rest <- tails rules, second <- rest] overlaps (first, second) = patternsOverlap (ruleFrom first) (ruleFrom second)@@ -175,22 +169,6 @@ rulesToList :: TransferRules v b -> [TransferRule v b] rulesToList (TransferRules rules) = rules -{-# DEPRECATED relabel "Use from .-> to |% Relabel of ExchangeAlgebra.Accounting.Transfer for an accounting transfer, or TransferRule from to Relabel to move coordinates." #-}-{-# DEPRECATED scaleBy, divideBy "A factor on the destination only does not balance. Use mapPosting to convert units, or Portion of ExchangeAlgebra.Accounting.Transfer to move a share." #-}---- | Construct a value-preserving rule; validate with 'mkTransferRules'.-relabel :: b -> b -> TransferRule v b-relabel source target = TransferRule source target Relabel---- | Construct a multiplication rule; the coefficient must be positive and finite.-scaleBy :: b -> b -> v -> TransferRule v b-scaleBy source target coefficient = TransferRule source target (MulBy coefficient)---- | Construct a division rule. Division is not reciprocal multiplication:--- the latter need not round the same way for floating-point values.-divideBy :: b -> b -> v -> TransferRule v b-divideBy source target coefficient = TransferRule source target (DivBy coefficient)- -- | Match only the pattern's wildcards, preserving literal ledger wildcards. -- Also used by "ExchangeAlgebra.Accounting.Transfer" on 'BasePart'. matches :: Element b => b -> b -> Bool@@ -204,11 +182,9 @@ -- | Generate cancellation and destination entries, without the input ledger. -- Input values must satisfy the ordinary non-negative, finite posting contract.--- 'Relabel'-only rules cannot fail. Scaled overflow returns 'NonFiniteResult',--- and no partial result is returned. Source HatNot postings are unmatched.--- A relabel to the identical base generates nothing; a zero scaled value--- generates only the cancellation. No implicit @bar@ or legacy one-to-one--- map is used. Complexity: O(s*r), with linear rule lookup per posting.+-- Source 'HatNot' terms are unmatched. A rule with an identical+-- source and destination generates no entries. The result retains all+-- generated terms. Complexity: O(s*r), with linear rule lookup per term. transferEntries :: (HatVal v, HatBaseClass b) => TransferRules v b -> Alg v b@@ -225,16 +201,12 @@ Nothing -> Right Zero Just rule -> generate rule value source generate rule value source- | ruleScale rule == Relabel && target == source = Right Zero- | isErrorValue moved = Left (NonFiniteResult rule value source)- | isZeroValue moved = Right cancellation- | otherwise = Right (cancellation .+ (moved `Single` target))+ | target == source = Right Zero+ | isErrorValue value = Left (NonFiniteResult rule value source)+ | isZeroValue value = Right cancellation+ | otherwise = Right (cancellation .+ (value `Single` target)) where target = ignoreWildcard source (ruleTo rule)- moved = case ruleScale rule of- Relabel -> value- MulBy coefficient -> value * coefficient- DivBy coefficient -> value / coefficient cancellation = value `Single` revHat source -- | Move selected entries to new bases while retaining every posting.
− src/ExchangeAlgebra/Algebra/Transfer/Rule.hs
@@ -1,119 +0,0 @@-{- |-Module : ExchangeAlgebra.Algebra.Transfer.Rule-Description : Transfer rules and closing entries.--This compatibility module re-exports generic transfer rules and base rewriting.-Use "ExchangeAlgebra.Algebra.Transfer" for generic transfers.-Start with 'mkTransferRules', then 'transferEntries' or the collapse functions.-Closing and settlement names re-export the same entities as-"ExchangeAlgebra.Accounting.Closing". Use that module for closing operations-and their compatibility, accounting balance, and non-negativity laws.--Definition 9 describes a transfer by adding source cancellations and target-postings to the original algebra. For @Right entries = transferEntries rules a@,-@a .+ entries@ is precisely that expression. This module returns only the-additional entries, preserving the original audit trail. Only-'collapseNetEntries' applies @bar@ to rewritten entries.--== Laws--The observation @obs@ is the map from complete bases (including Hat\/Not) to-summed values after @bar@; it does not observe the singleton versus composite-constructor or sequence order. Relative tolerance means a per-base difference-of at most @1e-9 * max (abs x) (abs y)@, treating absent bases as zero.--=== L1: base rewriting--* Subject: 'transferEntries'.-* Preconditions: disjoint source patterns, valid non-negative postings and- a successful application returning @Right entries@. A source wildcard- matches any stored element; a concrete source matches only itself.-* Relation: @obs (a .+ entries)@ equals the observation of independently- rewriting each matched posting to its rule's target and scaled value;- unmatched postings remain unchanged.-* Observation: @obs@ as defined above, including every target base.-* Tolerance: relative @1e-9@; tested values are integers in @1..1000000@,- and coefficients are @2@, @3@, @0.5@ and @4@.-* Instances: 'Double' and @MoneyDecimal@ with flat @HatBase@ tuples.--=== L4: canonical form--* Subject: 'mkTransferRules'.-* Preconditions: construction succeeds; the second input permutes the first.-* Relation: both constructions return equal rule sets.-* Observation: 'Eq' of t'TransferRules', or 'rulesToList'.-* Tolerance: exact equality. Errors (including NaN) are outside this law.-* Instances: all lawful 'HatVal' and 'HatBaseClass' instances.--=== L6: base collapse--* Subject: 'collapseEntries' and 'collapseNetEntries'.-* Preconditions: non-negative valid postings and an exact additive value type.-* Relation: @bar (x .+ collapseEntries p f x) ==- bar (x .+ collapseNetEntries p f x)@. The raw form has twice as many- postings as @proj p x@ and twice its norm; the net form calls 'ExchangeAlgebra.Algebra.Core.bar'- after- rewriting the base parts.-* Observation: net ledger and raw posting count and norm.-* Tolerance: exact.-* Instances: @MoneyDecimal@ with 'HatBaseClass' bases.--}-module ExchangeAlgebra.Algebra.Transfer.Rule- {-# DEPRECATED "Use ExchangeAlgebra.Algebra.Transfer for generic transfers and \- \ExchangeAlgebra.Accounting.Closing for closing entries." #-}- ( TransferScale(..)- , TransferRule(..)- , TransferRules- , TransferRuleError(..)- , TransferApplyError(..)- , mkTransferRules- , rulesToList- , relabel- , scaleBy- , divideBy- -- * Additional entries- , transferEntries- , collapseEntries- , collapseNetEntries- -- * Closing entries- , ClosingSide(..)- , closingSide- , closingEntries- , SettleRule- , retainedEarningsRule- , SettlementBatch- , SignedNet- , SettleError(..)- , settleEntries- , settlementSteps- ) where--import ExchangeAlgebra.Algebra.Transfer.Representation ( TransferScale(..)- , TransferRule(..)- , TransferRules- , TransferRuleError(..)- , TransferApplyError(..)- , mkTransferRules- , rulesToList- , relabel- , scaleBy- , divideBy- , transferEntries- , collapseEntries- , collapseNetEntries- )--import ExchangeAlgebra.Accounting.Closing ( ClosingSide(..)- , closingSide- , closingEntries- , SettleRule- , retainedEarningsRule- , SettlementBatch- , SignedNet- , SettleError(..)- , settleEntries- , settlementSteps- )--import ExchangeAlgebra.Algebra.Value.Class (HatVal)-import ExchangeAlgebra.Algebra.Base.Representation (HatBaseClass)
src/ExchangeAlgebra/Algebra/Value.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE BangPatterns #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DerivingStrategies #-} @@ -7,28 +8,29 @@ Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license Exact, non-negative decimal value type t'MoneyDecimal' for use as the @v@ parameter of @Alg v b@ / @Journal n v b@. - == Why this exists (DESIGN, 2026-06-06)+ == Why this exists The accounting value type is selectable: - * @Double@ — fast IEEE-754; the default. Addition is /non-associative/,- so the order in which same-base postings are summed (which depends on how a- value was /constructed/) can change @norm@ / @bar@ results. In the- agent-based simulations this manifested as a ~3% swing in a stock value when- the construction order changed (see plans/in-progress/LAZY_EVAL_AUDIT.md and- FP_SUMMATION_SURVEY.md). This is acceptable for relative-price ABM work where- speed matters, but it is not deterministic/auditable.+ * @Double@ — fast IEEE-754; the default. Floating-point addition is+ /non-associative/, but @norm@ and @bar@ sum the supplied values exactly and+ round once, and @balance@ compares the exact sums, so for finite terms they+ do not depend on the order in which same-base terms were added. The sequential sums of @barWithin@,+ @balanceWithin@, and @diffRLWithin@ follow that order and can change in the+ last digit. Decimal amounts such as @0.1@ are approximated, and products and+ quotients such as tax ratios round at each step. This is acceptable for+ relative-price ABM work where speed matters. * @MoneyDecimal@ — exact base-10 fixed-point (a non-negative 'Data.Decimal').- Addition is /exact and associative/, so results are independent of- construction order: the fromList fold direction, parallel merges, etc. no- longer change the answer. This is the right choice for audited ledgers and- for making the construction-order optimizations (fromList O(N)) safe.+ Addition is /exact and associative/, so every readout, including the+ sequential sums, is independent of construction order, and decimal amounts+ such as @0.1@ are represented exactly. This is the right choice for audited+ ledgers whose totals must match decimal arithmetic. @Integer@ (minimal-currency-unit) is intentionally NOT offered: ABM simulations use relative prices with base unit 1 and sub-unit fractional prices, which an@@ -97,7 +99,9 @@ ) import Data.Decimal (Decimal, DecimalRaw (Decimal), normalizeDecimal, roundTo') import Data.Ratio (numerator, denominator)-import Data.Word (Word8)+import Data.Word (Word8, Word64)+import Data.Int (Int64)+import Data.Bits (countLeadingZeros, shiftR) import Data.Scientific (Scientific, coefficient, base10Exponent) import qualified Data.Scientific as Scientific import Data.Text (Text)@@ -105,6 +109,8 @@ import Data.Hashable (Hashable (..)) import Control.DeepSeq (NFData (..)) import qualified Data.Binary as Binary+import qualified Data.Binary.Put as BinPut+import qualified Data.ByteString.Builder as BB -- | A non-negative exact decimal value (wraps 'Data.Decimal.Decimal'). --@@ -377,12 +383,13 @@ -- This is the @newtype@ counterpart of the bare-@Double@ instance: a dedicated, -- domain-specific money type so a ledger value cannot be silently confused with -- an ABM coefficient, a random draw, or any other raw 'Double'. Every instance--- it needs is owned here (via @deriving newtype@), so — exactly like+-- it needs is owned here, so — exactly like -- t'MoneyDecimal' — there are no orphan instances. Use t'MoneyDouble' for the same -- speed as bare 'Double' while keeping the value type distinct in signatures. ----- Trade-off vs t'MoneyDecimal': addition is /non-associative/ (FP), so @norm@ \/--- @bar@ can differ in the last ULP depending on construction order. It is fast+-- Trade-off vs t'MoneyDecimal': decimal amounts are approximated, and the+-- sequential sums of @barWithin@ can differ in the last digit depending on+-- construction order (@norm@ and @bar@ sum exactly and round once). It is fast -- and runs everywhere bare 'Double' does (subtraction is signed, so the -- intermediate negatives that arise inside @bar@\/@(.-)@ are fine — unlike -- @Number.NonNegative.Double@, whose @(-)@ /errors/ on a negative result).@@ -392,13 +399,54 @@ -- @isNaN x || isInfinite x || x < 0@, so the @(.\@)@ smart constructor and -- @(.*)@ reject negative\/non-finite values. newtype MoneyDouble = MoneyDouble Double- -- All instances are coerced from the existing bare-'Double' instances- -- ('Nearly'/'HatVal' live in "ExchangeAlgebra.Algebra"; 'Binary'/'Hashable'/- -- 'NFData' come from the binary/hashable/deepseq packages), so t'MoneyDouble'- -- is a zero-cost wrapper with identical numeric behavior and 2-decimal- -- 'showValue' formatting.+ -- Derived instances delegate to bare 'Double'. 'HatVal' delegates by hand+ -- with 2-decimal 'showValue' formatting; 'Binary.Binary' uses a compatible+ -- encoder below and the binary package's 'Double' decoder. deriving newtype ( Eq, Ord, Show, Num, Fractional, Real, RealFrac- , Nearly, Hashable, NFData, Binary.Binary )+ , Nearly, Hashable, NFData )++-- | Encode exactly the same bytes as the binary package's 'Double' instance.+-- Its encoder expands the mantissa into an Integer byte list; writing the+-- mantissa directly with a builder avoids that intermediate allocation.+-- Decoding retains the 'Double' instance's behavior, including non-finite values.+instance Binary.Binary MoneyDouble where+ {-# INLINE put #-}+ put (MoneyDouble d) = putDoubleCompat d+ get = MoneyDouble <$> Binary.get++-- | Write the binary package's mantissa/exponent representation of a 'Double'.+-- Invariant: decodeFloat returns a mantissa that fits in Int64, including+-- zero, subnormal, infinite, and NaN inputs on the supported Double runtime.+putDoubleCompat :: Double -> Binary.Put+putDoubleCompat d = case decodeFloat d of+ (mi, e) ->+ let !m = fromInteger mi :: Int64+ in BinPut.putBuilder (mant m <> BB.int64BE (fromIntegral e))+ where+ mant :: Int64 -> BB.Builder+ mant m+ | m >= -2147483648 && m <= 2147483647 =+ BB.word8 0 <> BB.int32BE (fromIntegral m)+ | otherwise =+ let !a = fromIntegral (abs m) :: Word64+ !n = byteLen a+ in BB.word8 1 <> BB.word8 (signByte m)+ <> BB.int64BE (fromIntegral n) <> bytesLE n a++ signByte :: Int64 -> Word8+ signByte m+ | m < 0 = 255+ | otherwise = 1++ byteLen :: Word64 -> Int+ byteLen a = (64 - countLeadingZeros a + 7) `quot` 8++ bytesLE :: Int -> Word64 -> BB.Builder+ bytesLE 7 a = BB.word32LE (fromIntegral a)+ <> BB.word16LE (fromIntegral (a `shiftR` 32))+ <> BB.word8 (fromIntegral (a `shiftR` 48))+ bytesLE 0 _ = mempty+ bytesLE k a = BB.word8 (fromIntegral a) <> bytesLE (k - 1) (a `shiftR` 8) -- | Delegates to the 'Prelude.Double' accumulator. Written by hand because the -- associated data family 'Accum' cannot be derived through a newtype.
src/ExchangeAlgebra/Algebra/Value/Class.hs view
@@ -109,8 +109,8 @@ -- -- * 'Prelude.Double' — fast IEEE-754 (this module); the low-friction default. -- * @MoneyDouble@ ("ExchangeAlgebra.Algebra.Value") — same speed, dedicated money newtype.--- * @MoneyDecimal@ ("ExchangeAlgebra.Algebra.Value") — exact decimal, construction-order--- independent totals; use for audited\/deterministic ledgers.+-- * @MoneyDecimal@ ("ExchangeAlgebra.Algebra.Value") — exact decimal arithmetic, so+-- totals match decimal bookkeeping; use for audited ledgers. -- -- DESIGN NOTE (2026-06-06, selectable value type — Double vs exact Decimal): -- The @RealFloat@ superclass was intentionally *removed* so that exact,
− src/ExchangeAlgebra/Assist.hs
@@ -1,14 +0,0 @@-{-# LANGUAGE OverloadedStrings #-}-{- |Compatibility import for "ExchangeAlgebra.IO.Input.Assist".--}-module ExchangeAlgebra.Assist {-# DEPRECATED "Import ExchangeAlgebra.IO.Input.Assist instead." #-}- ( AccountInfo(..)- , describeAccount- , allAccountInfos- , suggestAccounts- , explainEntryError- , explainJournalErrors- , explainSourceErrors- ) where--import ExchangeAlgebra.IO.Input.Assist
− src/ExchangeAlgebra/Assist/Descriptions.hs
@@ -1,9 +0,0 @@-{- |-Module : ExchangeAlgebra.Assist.Descriptions-Description : Compatibility projection of the canonical account registry.--}-module ExchangeAlgebra.Assist.Descriptions {-# DEPRECATED "Use ExchangeAlgebra.Accounting.Account instead." #-}- ( accountDescriptions- ) where--import ExchangeAlgebra.Accounting.Account (accountDescriptions)
− src/ExchangeAlgebra/Bookkeeping.hs
@@ -1,33 +0,0 @@--- | Compatibility exports for bookkeeping operations.-module ExchangeAlgebra.Bookkeeping-{-# DEPRECATED "Import ExchangeAlgebra.Accounting.Entries instead." #-}- ( -- * Base injection- MkBase- -- * Cost of goods sold (売上原価, 3 分法)- , cogsAdjustmentEntries- -- * Depreciation (減価償却)- , depreciationIndirectEntry- , depreciationDirectEntry- -- * Allowance for doubtful accounts (貸倒引当金)- , allowanceReplenishmentEntry- , allowanceResetEntries- -- * Deferral / accrual (経過勘定)- , prepaidExpenseEntry- , unearnedRevenueEntry- , accruedRevenueEntry- , accruedExpenseEntry- , reversingEntry- -- * Tax settlement (消費税・法人税等)- , consumptionTaxSettlementEntry- , corporateTaxInterimEntry- , corporateTaxSettlementEntries- -- * Equity method (持分法)- , equityMethodEarningsEntry- , equityMethodDividendEntry- , equityMethodEntries- , equityMethodBalance- -- * Prior-period error correction (前期修正)- , priorPeriodErrorCorrection- ) where--import ExchangeAlgebra.Accounting.Entries
− src/ExchangeAlgebra/Consolidation/Worksheet.hs
@@ -1,22 +0,0 @@--- | Compatibility exports for consolidation worksheets.-module ExchangeAlgebra.Consolidation.Worksheet-{-# DEPRECATED "Import ExchangeAlgebra.Accounting.Consolidation instead." #-}- ( PeriodResult(..)- , AccountBalance(..)- , LinkField(..)- , TrialBalanceSource(..)- , WorksheetAdjustment(..)- , WorksheetLinkage(..)- , WorksheetInput(..)- , WorksheetError(..)- , ValidatedWorksheet- , validateConsolidationWorksheet- , validatedSources- , validatedAdjustments- , validatedLinkage- , combinedWorksheet- ) where--import ExchangeAlgebra.Accounting.Consolidation-import ExchangeAlgebra.Accounting.Statements.Metric (PeriodResult(..))-import ExchangeAlgebra.Accounting.TrialBalance.Balance (AccountBalance(..))
− src/ExchangeAlgebra/Convert.hs
@@ -1,24 +0,0 @@-{-# LANGUAGE GADTs #-}-{-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE OverloadedStrings #-}-{-# OPTIONS_GHC -Wno-deprecations #-}-{- |Compatibility import for "ExchangeAlgebra.IO.Input" and-"ExchangeAlgebra.Accounting.Account".--}-module ExchangeAlgebra.Convert {-# DEPRECATED "Import ExchangeAlgebra.IO.Input or ExchangeAlgebra.Accounting.Account for concreteAccountTitles instead." #-}- ( ConvError(..)- -- $concreteAccountTitles- , concreteAccountTitles- , normalizeTitle- , parseAccountTitle- , parseSide- , markerForSide- , postingFromSide- , journalFromSides- ) where--import ExchangeAlgebra.IO.Input-import ExchangeAlgebra.Accounting.Account (concreteAccountTitles)---- $concreteAccountTitles--- Concrete account titles are listed by @concreteAccountTitles@.
− src/ExchangeAlgebra/Convert/Checked.hs
@@ -1,31 +0,0 @@-{-# LANGUAGE FlexibleContexts #-}-{-# OPTIONS_GHC -Wincomplete-patterns -Werror=incomplete-patterns #-}-{- |Compatibility import for "ExchangeAlgebra.IO.Input" and-"ExchangeAlgebra.Accounting.Account".--}-module ExchangeAlgebra.Convert.Checked {-# DEPRECATED "Import ExchangeAlgebra.IO.Input or ExchangeAlgebra.Accounting.Account for posting policy instead." #-}- ( -- $postingPolicy- ProcessingContext(..)- , EntryError(..)- , JournalError(..)- , JournalCert(..)- , SourceError(..)- , postingAllowedIn- , checkedEntryIn- , checkedEntry- , checkedEntryTextIn- , checkedEntryText- , checkedJournalIn- , checkedJournal- , certifyJournalTextIn- , certifyJournalText- , reconcileSources- ) where--import ExchangeAlgebra.IO.Input.Checked hiding (ProcessingContext, postingAllowedIn)-import ExchangeAlgebra.Accounting.Account (ProcessingContext(..), postingAllowedIn)---- $postingPolicy--- 'checkedEntryIn' takes a t'ProcessingContext' as its first argument.--- 'postingAllowedIn' checks whether each account's posting capability is allowed--- in that context.
− src/ExchangeAlgebra/Convert/Csv.hs
@@ -1,17 +0,0 @@-{-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE OverloadedStrings #-}-{- |Compatibility import for "ExchangeAlgebra.IO.Input.Csv".--}-module ExchangeAlgebra.Convert.Csv {-# DEPRECATED "Import ExchangeAlgebra.IO.Input.Csv instead." #-}- ( -- * Parsing journal CSV- parseJournalCsv- , parseJournalCsvWith- -- * Note-keyed journal (when the optional @note@ column is present)- , parseNotedJournalCsv- -- * Amount parsers- , scientificAmount- -- * Field splitting- , splitTrim- ) where--import ExchangeAlgebra.IO.Input.Csv
src/ExchangeAlgebra/IO/Input.hs view
@@ -11,33 +11,51 @@ -- | Parse CSV | "ExchangeAlgebra.IO.Input.Csv" | -- | Explain validation feedback | "ExchangeAlgebra.IO.Input.Assist" | module ExchangeAlgebra.IO.Input- ( ConvError(..)+ ( ConvErrorOf(..)+ , ConvError+ -- * Account-name tables+ , AccountResolver+ , AccountNameTable+ , accountNameTable+ , extendAccountNames+ , resolveWith+ , defaultAccountNames+ , vocabularyNames , normalizeTitle , parseAccountTitle , parseSide , markerForSide , postingFromSide , journalFromSides- , EntryError(..)- , JournalError(..)- , JournalCert(..)+ , EntryErrorOf(..)+ , EntryError+ , JournalErrorOf(..)+ , JournalError+ , JournalCertOf(..)+ , JournalCert , SourceError(..) , checkedEntryIn , checkedEntry , checkedEntryTextIn , checkedEntryText+ , checkedEntryTextBy , checkedJournalIn , checkedJournal , certifyJournalTextIn , certifyJournalText+ , certifyJournalTextBy , reconcileSources ) where import ExchangeAlgebra.IO.Input.Conversion- ( ConvError(..), normalizeTitle, parseAccountTitle, parseSide+ ( ConvErrorOf(..), ConvError+ , AccountResolver, AccountNameTable, accountNameTable, extendAccountNames+ , resolveWith, defaultAccountNames, vocabularyNames+ , normalizeTitle, parseAccountTitle, parseSide , markerForSide, postingFromSide, journalFromSides ) import ExchangeAlgebra.IO.Input.Checked- ( EntryError(..), JournalError(..), JournalCert(..), SourceError(..)+ ( EntryErrorOf(..), EntryError, JournalErrorOf(..), JournalError+ , JournalCertOf(..), JournalCert, SourceError(..) , checkedEntryIn, checkedEntry, checkedEntryTextIn, checkedEntryText- , checkedJournalIn, checkedJournal, certifyJournalTextIn- , certifyJournalText, reconcileSources )+ , checkedEntryTextBy, checkedJournalIn, checkedJournal, certifyJournalTextIn+ , certifyJournalText, certifyJournalTextBy, reconcileSources )
src/ExchangeAlgebra/IO/Input/Admission.hs view
@@ -31,8 +31,8 @@ -- After admission, derive reports from 'admittedJournal' with the existing -- functions: pass the trial balance and its stage to -- @ExchangeAlgebra.Accounting.Statements.Presentation.present@, read the--- trial-balance findings separately with--- @ExchangeAlgebra.Accounting.TrialBalance.trialBalanceFindings@, and write+-- trial-balance findings separately with the audits of+-- "ExchangeAlgebra.Accounting.Audit", and write -- rows with the CSV writers in "ExchangeAlgebra.IO.Output.Statements". -- -- = Guarantee@@ -164,10 +164,11 @@ -- -- The audit of the trial balance is separate from presentation: ----- >>> import qualified Data.Map.Strict as Map--- >>> import qualified Data.Set as Set--- >>> TrialBalance.trialBalanceFindings (TrialBalance.TrialBalanceInput beforeClosing TrialBalance.BeforeClosing Map.empty [] Set.empty)--- []+-- >>> import qualified ExchangeAlgebra.Accounting.Audit as Audit+-- >>> Audit.impossibleBalances beforeClosing+-- NoProblem+-- >>> Audit.abnormalBalances beforeClosing+-- NoProblem module ExchangeAlgebra.IO.Input.Admission ( -- * Transaction keys -- | A ready-made note type for journals keyed by entity, reporting
src/ExchangeAlgebra/IO/Input/Admission/Engine.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -Wincomplete-patterns -Werror=incomplete-patterns #-} -- | Package-private implementation of @admit@.@@ -10,7 +11,7 @@ import qualified Data.HashMap.Strict as HashMap import ExchangeAlgebra.Accounting.Account (PostingCapability(NotPostable), postingCapabilityFor)-import ExchangeAlgebra.Accounting.Exchange (ExBaseClass(..), Exchange(decL, decR))+import ExchangeAlgebra.Accounting.Exchange (StandardBase, ExBaseClass(..), Exchange(decL, decR)) import ExchangeAlgebra.Algebra.Base.Representation (HatBaseClass(hat), Hat(..)) import qualified ExchangeAlgebra.Algebra.Core as Algebra import ExchangeAlgebra.Algebra.Value.Class (HatVal(..), isErrorValue)@@ -53,7 +54,7 @@ -- * The checks are per note: @admit (j1 .+ j2)@ succeeds when @admit j1@ and -- @admit j2@ succeed and @j1@ and @j2@ have disjoint notes. -- * @admit Zero@ succeeds.-admit :: (Note n, ExBaseClass b)+admit :: (Note n, StandardBase b) => Journal n MoneyDecimal b -> Either (AdmissionFailure n b) (Admitted n b) admit journal = case errors of
src/ExchangeAlgebra/IO/Input/Assist.hs view
@@ -42,10 +42,12 @@ , concreteAccountTitles ) import ExchangeAlgebra.IO.Input.Conversion- ( ConvError(..) )+ ( ConvErrorOf(..), ConvError ) import ExchangeAlgebra.IO.Input.Checked- ( EntryError(..)- , JournalError(..)+ ( EntryErrorOf(..)+ , EntryError+ , JournalErrorOf(..)+ , JournalError , SourceError(..) ) @@ -53,7 +55,7 @@ -- >>> :set -XOverloadedStrings -- >>> import Data.List.NonEmpty (NonEmpty(..)) -- >>> import ExchangeAlgebra.Accounting.Account (AccountTitles(..), PostingCapability(..))--- >>> import ExchangeAlgebra.IO.Input (ConvError(..), EntryError(..), JournalError(..), SourceError(..))+-- >>> import ExchangeAlgebra.IO.Input (ConvErrorOf(..), ConvError, EntryErrorOf(..), EntryError, JournalErrorOf(..), JournalError, SourceError(..)) -- >>> import ExchangeAlgebra.Accounting.Account (ProcessingContext(..)) -- | Account-title metadata for LLM-facing lookup.@@ -96,7 +98,7 @@ -- >>> take 1 (map aiTitle allAccountInfos) -- [Cash] -- >>> aiTitle (last allAccountInfos)--- ReversalOfAllowanceForBonuses+-- DirectorsCompensations allAccountInfos :: [AccountInfo] allAccountInfos = mapMaybe describeAccount concreteAccountTitles @@ -125,9 +127,9 @@ safeDescription NetLoss _ = "Period result: net loss (当期純損失). Engine-generated only; the legacy Revenue value is an internal direction encoding, not a revenue classification." safeDescription GrossProfit _ =- "Legacy engine coordinate: gross profit (売上総利益). Engine-generated only; the legacy Revenue value is an internal direction encoding, not a statement subtotal definition."+ "Period subtotal: gross profit (売上総利益). Engine-generated only; the legacy Revenue value is an internal direction encoding, not a statement subtotal definition." safeDescription OrdinaryProfit _ =- "Legacy engine coordinate: ordinary profit (経常利益). Engine-generated only; the legacy Revenue value is an internal direction encoding, not a statement subtotal definition."+ "Period subtotal: ordinary profit (経常利益). Engine-generated only; the legacy Revenue value is an internal direction encoding, not a statement subtotal definition." safeDescription IncomeSummary _ = "Closing device: income summary (損益). Available only during closing; the legacy Assets value is an internal direction encoding, not a balance-sheet classification." safeDescription SuspensePayments _ =@@ -215,6 +217,9 @@ postingAccount i account <> ": " <> showText capability <> " is not allowed in " <> showText context+explainEntryError (MissingPostingSemantics i account) =+ postingAccount i account+ <> ": the account vocabulary gives no posting semantics for this account" explainEntryError EmptyEntry = "entry has no postings" explainEntryError (Imbalanced debitTotal creditTotal) =
src/ExchangeAlgebra/IO/Input/Checked.hs view
@@ -1,6 +1,8 @@ {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE BangPatterns #-}-{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -Wincomplete-patterns -Werror=incomplete-patterns #-} {- |@@ -16,44 +18,55 @@ module ExchangeAlgebra.IO.Input.Checked ( -- $postingPolicy ProcessingContext(..)- , EntryError(..)- , JournalError(..)- , JournalCert(..)+ , EntryErrorOf(..)+ , EntryError+ , JournalErrorOf(..)+ , JournalError+ , JournalCertOf(..)+ , JournalCert , SourceError(..) , postingAllowedIn , checkedEntryIn , checkedEntry , checkedEntryTextIn+ , checkedEntryTextBy , checkedEntryAccountTextIn , checkedEntryText , checkedJournalIn , checkedJournal , certifyJournalTextIn+ , certifyJournalTextBy , certifyJournalText , reconcileSources ) where +import Data.Bifunctor (first) import Data.List.NonEmpty (NonEmpty(..)) import qualified Data.HashMap.Strict as HM import qualified Data.List as L import qualified Data.Map.Strict as M-import Data.Maybe (mapMaybe)+import Data.Maybe (fromMaybe) import Data.Text (Text)-import qualified Data.Text as T import ExchangeAlgebra.Algebra.Core (Alg, Redundant((.+), norm)) import ExchangeAlgebra.Algebra.Value.Class (HatVal(..), isErrorValue)-import ExchangeAlgebra.Accounting.Exchange (Exchange(decL, balance))+import ExchangeAlgebra.Accounting.Exchange+ ( Exchange(decL, balance), ExBaseClass, TitleOf, journalForSides ) import ExchangeAlgebra.Accounting.Account.PostingPolicy ( ProcessingContext(..) , postingAllowedIn- , postingCapabilityFor ) import ExchangeAlgebra.Accounting.Account- ( AccountTitles(..), PostingCapability(..), Side(..) )-import ExchangeAlgebra.Algebra.Base.Representation (HatBase)+ ( AccountTitles(..), AccountVocabulary(vocabSemantics)+ , AccountSemantics(asemPostingCapability), PostingCapability(..), Side(..) )+import ExchangeAlgebra.Algebra.Element.Representation (Element(isWildcard, wildcard))+import ExchangeAlgebra.Algebra.Base.Representation (BaseClass, HatBase) import ExchangeAlgebra.IO.Input.Conversion- ( ConvError+ ( ConvErrorOf(..)+ , AccountResolver+ , defaultAccountNames+ , extendAccountNames+ , resolveWith , journalFromSides , normalizeTitle , parseAccountTitle@@ -78,29 +91,45 @@ -- $postingPolicy -- 'ProcessingContext' and 'postingAllowedIn' are defined in--- "ExchangeAlgebra.Accounting.PostingPolicy" and re-exported here so the+-- "ExchangeAlgebra.Accounting.Account" and re-exported here so the -- historical import path keeps working. The gate itself is accounting-domain -- policy, not an input-adapter concern. --- | Validation errors for a single generated entry.+-- | Validation errors for a single generated entry, over an account-title+-- type @acct@. -- -- Posting positions are 0-origin indices in the input entry.-data EntryError v- = EntryParse Int ConvError- | NonPositiveAmount Int AccountTitles v+data EntryErrorOf acct v+ = EntryParse Int (ConvErrorOf acct)+ | NonPositiveAmount Int acct v+ -- ^ for an unresolved account the title is the wildcard | WildcardAccount Int | WildcardSide Int- | PostingNotAllowed Int AccountTitles PostingCapability ProcessingContext+ | PostingNotAllowed Int acct PostingCapability ProcessingContext+ | MissingPostingSemantics Int acct+ -- ^ the vocabulary gives no 'ExchangeAlgebra.Accounting.Account.Vocabulary.vocabSemantics'+ -- for this concrete title, so its posting capability is unknown and the+ -- posting is rejected. Reported at the place 'PostingNotAllowed' would be+ -- checked. Never produced for the built-in titles, which all carry+ -- semantics. | EmptyEntry | Imbalanced { _debitTotal :: v, _creditTotal :: v } deriving (Show, Eq) +-- | Validation errors for the built-in account titles. Import+-- @EntryErrorOf(..)@ for the constructors.+type EntryError = EntryErrorOf AccountTitles+ -- | Validation errors for a txid-indexed journal batch.-data JournalError n v- = EntryErrors n (NonEmpty (EntryError v))+data JournalErrorOf acct n v+ = EntryErrors n (NonEmpty (EntryErrorOf acct v)) | DuplicateTxId n deriving (Show, Eq) +-- | Batch errors for the built-in account titles. Import+-- @JournalErrorOf(..)@ for the constructors.+type JournalError = JournalErrorOf AccountTitles+ -- | Staged certification of a text-originated journal batch. -- -- A batch can be fully admitted, rejected for accounting or structural@@ -117,18 +146,22 @@ -- Per-entry balance implies batch balance, so the invariant -- @_certDebitTotal == _certCreditTotal@ holds, but the converse does not: the -- batch totals alone would not have been a sufficient gate.-data JournalCert n v- = FullyResolved (Journal n v (HatBase AccountTitles))+data JournalCertOf acct n v+ = FullyResolved (Journal n v (HatBase acct)) | BalancedUnresolved- { _certResolved :: [(n, [(Side, AccountTitles, v)])]- , _certUnresolved :: [(n, [(Int, Text, ConvError)])]+ { _certResolved :: [(n, [(Side, acct, v)])]+ , _certUnresolved :: [(n, [(Int, Text, ConvErrorOf acct)])] , _certDebitTotal :: v , _certCreditTotal :: v }- | Rejected (NonEmpty (JournalError n v))+ | Rejected (NonEmpty (JournalErrorOf acct n v)) deriving (Show) -instance (HatVal v, Note n) => Eq (JournalCert n v) where+-- | Certification for the built-in account titles. Import+-- @JournalCertOf(..)@ for the constructors.+type JournalCert = JournalCertOf AccountTitles++instance (HatVal v, Note n, BaseClass acct) => Eq (JournalCertOf acct n v) where FullyResolved left == FullyResolved right = toMap left == toMap right BalancedUnresolved resolvedLeft unresolvedLeft debitLeft creditLeft == BalancedUnresolved resolvedRight unresolvedRight debitRight creditRight =@@ -168,11 +201,14 @@ -> [(Side, AccountTitles, v)] -> Either (NonEmpty (EntryError v)) (Alg v (HatBase AccountTitles)) checkedEntryIn context rows =- case validateIndexed context (null rows) indexed of+ case entryErrors of [] -> Right (journalFromSides rows) e : es -> Left (e :| es) where- indexed = zip [0..] rows+ entryErrors = [EmptyEntry | null rows]+ ++ concat [ postingErrors context i (Just side) (Just account) amount+ | (i, (side, account, amount)) <- zip [0..] rows ]+ ++ balanceErrors [(side, amount) | (side, _, amount) <- rows] -- | Construct one ordinary-journal entry. This compatibility API delegates -- to 'checkedEntryIn' and therefore rejects closing-only, consolidation-only,@@ -196,11 +232,37 @@ => ProcessingContext -> [(Text, Text, v)] -> Either (NonEmpty (EntryError v)) (Alg v (HatBase AccountTitles))-checkedEntryTextIn context rows =+checkedEntryTextIn = checkedEntryTextBy parseAccountTitle++-- | As 'checkedEntryTextIn', but with a caller-supplied account resolver, so+-- the title type @acct@ is the caller's.+--+-- Laws:+--+-- * @checkedEntryTextBy parseAccountTitle == checkedEntryTextIn@.+-- * Errors are those of 'checkedEntryTextIn', in the same order, with titles+-- of type @acct@: resolver failures become 'EntryParse'; a resolved wildcard+-- gives 'WildcardAccount'; a concrete title whose 'vocabSemantics' is+-- 'Nothing' gives 'MissingPostingSemantics'; otherwise the posting capability+-- is @asemPostingCapability@ of its semantics, checked with 'postingAllowedIn'.+-- As in 'checkedEntryTextIn', a row whose side does not parse gets no+-- structural checks (no wildcard, amount, capability, or semantics error).+-- * Amounts of rows whose account did not resolve still enter the balance check.+-- * On success the term equals 'journalForSides' of the parsed rows.+checkedEntryTextBy :: (HatVal v, ExBaseClass (HatBase acct), TitleOf (HatBase acct) ~ acct)+ => AccountResolver acct+ -> ProcessingContext+ -> [(Text, Text, v)]+ -> Either (NonEmpty (EntryErrorOf acct v)) (Alg v (HatBase acct))+checkedEntryTextBy resolve context rows = checkedEntryParsedIn context- [(i, (parseSide side, parseAccountTitle account, amount))+ [(i, (parseInputSide side, resolve account, amount)) | (i, (side, account, amount)) <- zip [0..] rows] +-- | Keep the original side field in the error for any account type.+parseInputSide :: Text -> Either (ConvErrorOf acct) Side+parseInputSide t = first (const (UnknownSide t)) (parseSide t)+ -- | Check typed sides and account text in the supplied processing context. -- Account parse errors precede structural errors and imbalance. Amounts from -- unresolved accounts still contribute to the balance check.@@ -217,72 +279,30 @@ -- | Validate all indexed parse results without dropping unresolved rows. -- An unresolved side suppresses imbalance; an unresolved account does not. checkedEntryParsedIn- :: forall v. HatVal v+ :: (HatVal v, ExBaseClass (HatBase acct), TitleOf (HatBase acct) ~ acct) => ProcessingContext- -> [(Int, (Either ConvError Side, Either ConvError AccountTitles, v))]- -> Either (NonEmpty (EntryError v)) (Alg v (HatBase AccountTitles))+ -> [(Int, (Either (ConvErrorOf acct) Side, Either (ConvErrorOf acct) acct, v))]+ -> Either (NonEmpty (EntryErrorOf acct v)) (Alg v (HatBase acct)) checkedEntryParsedIn context rows =- case parseErrors ++ structuralErrors ++ textImbalanceErrors of- [] -> Right (journalFromSides (map snd parsedRows))+ case parseErrors ++ structuralErrors ++ imbalanceErrors of+ [] -> Right (journalForSides (map snd parsedRows)) e : es -> Left (e :| es) where- parsed = map parseIndexed rows- parseErrors = concatMap first parsed- parsedRows = mapMaybe second parsed- sideAmounts = mapMaybe third parsed- structuralErrors = filter (not . isImbalance)- (validateIndexed context (null rows) parsedRows)+ parseErrors = concat+ [ [EntryParse i err | Left err <- [side]] ++ [EntryParse i err | Left err <- [account]]+ | (i, (side, account, _)) <- rows ]+ parsedRows =+ [(i, (side, account, amount)) | (i, (Right side, Right account, amount)) <- rows]+ structuralErrors = [EmptyEntry | null rows]+ ++ concat [postingErrors context i (Just side) (Just account) amount+ | (i, (side, account, amount)) <- parsedRows] - -- Account vocabulary resolution and arithmetic balance are independent.- -- Retain every successfully parsed side/amount pair so an unknown account- -- does not make an otherwise balanced entry look imbalanced.- textImbalanceErrors- | null rows = []+ -- An unresolved account contributes its amount if the side is known.+ sideAmounts = [(side, amount) | (_, (Right side, _, amount)) <- rows]+ imbalanceErrors | length sideAmounts /= length rows = []- | any invalidSideAmount sideAmounts = []- | signAccum (mergeAccum debitState (negateAccum creditState)) == Just EQ = []- | otherwise = [Imbalanced debitTotal creditTotal]- where- debitState = L.foldl' (flip addAccum) emptyAccum- [ amount | (Debit, amount) <- sideAmounts ]- creditState = L.foldl' (flip addAccum) emptyAccum- [ amount | (Credit, amount) <- sideAmounts ]- debitTotal = roundAccum debitState- creditTotal = roundAccum creditState-- invalidSideAmount :: (Side, v) -> Bool- invalidSideAmount (side, amount) =- side == Side || isErrorValue amount || not (amount > 0)-- isImbalance :: EntryError v -> Bool- isImbalance Imbalanced{} = True- isImbalance _ = False-- first :: (a, b, c) -> a- first (x, _, _) = x- second :: (a, b, c) -> b- second (_, x, _) = x- third :: (a, b, c) -> c- third (_, _, x) = x-- parseIndexed- :: (Int, (Either ConvError Side, Either ConvError AccountTitles, v))- -> ([EntryError v], Maybe (Int, (Side, AccountTitles, v)), Maybe (Side, v))- parseIndexed (i, (sideResult, accountResult, amount)) =- let errs =- (case sideResult of- Left err -> [EntryParse i err]- Right _ -> [])- ++ (case accountResult of- Left err -> [EntryParse i err]- Right _ -> [])- parsedRow = case (sideResult, accountResult) of- (Right side, Right account) -> Just (i, (side, account, amount))- _ -> Nothing- sideAmount = case sideResult of- Right side -> Just (side, amount)- Left _ -> Nothing- in (errs, parsedRow, sideAmount)+ | any (\(side, amount) -> side == Side || invalidAmount amount) sideAmounts = []+ | otherwise = balanceErrors sideAmounts -- | Parse and check an ordinary-journal entry. checkedEntryText :: (HatVal v)@@ -352,7 +372,40 @@ => ProcessingContext -> [(n, [(Text, Text, v)])] -> JournalCert n v-certifyJournalTextIn context entries =+certifyJournalTextIn = certifyJournalTextBy+ (resolveWith (extendAccountNames [("AccountTitle", AccountTitle)] defaultAccountNames))++-- | As 'certifyJournalTextIn', but with a caller-supplied account resolver.+--+-- Laws:+--+-- * @certifyJournalTextBy (resolveWith (extendAccountNames [(\"AccountTitle\", AccountTitle)] defaultAccountNames)) == certifyJournalTextIn@.+-- The built-in path lists the wildcard's name so that a wildcard (a+-- structural defect) stays distinct from an unknown name (a vocabulary gap);+-- a caller extending the built-in table keeps that distinction the same way.+-- The side name @\"Side\"@ (after 'normalizeTitle') is read as the wildcard+-- side for every title type, as before.+-- * Decisions in order: duplicate txids, then structural errors of every+-- entry, then the balance of each entry (per txid, so two entries whose+-- imbalances cancel in the batch are 'Rejected'), then vocabulary gaps. The+-- first non-empty stage gives 'Rejected'.+-- * A resolved wildcard is a structural error. 'UnknownAccount' and+-- 'AmbiguousAccount' from the resolver are vocabulary gaps; any other 'Left'+-- from the resolver is a structural 'EntryParse' error.+-- * When only vocabulary gaps remain the result is 'BalancedUnresolved':+-- '_certResolved' and '_certUnresolved' keep transaction order and row order+-- and omit transactions with no rows in that group; '_certUnresolved' holds+-- the account text as given; the batch totals include the amounts of+-- unresolved rows. With no gaps the result is 'FullyResolved'.+-- * Titles are checked for posting capability as in 'checkedEntryTextBy'+-- (here a row with an unparsed side is still checked, as in+-- 'certifyJournalTextIn').+certifyJournalTextBy :: (HatVal v, Note n, ExBaseClass (HatBase acct), TitleOf (HatBase acct) ~ acct)+ => AccountResolver acct+ -> ProcessingContext+ -> [(n, [(Text, Text, v)])]+ -> JournalCertOf acct n v+certifyJournalTextBy resolve context entries = case duplicateErrors of e : es -> Rejected (e :| es) [] -> case structuralErrors of@@ -360,7 +413,7 @@ [] -> case imbalanceErrors of e : es -> Rejected (e :| es) []- | null unresolvedPostings ->+ | null unresolvedEntries -> FullyResolved (L.foldl' (.+) mempty journals) | otherwise -> BalancedUnresolved@@ -378,7 +431,7 @@ ] parsedEntries =- [ (txid, map parseCertPosting (zip [0..] rows))+ [ (txid, map (parseCertPosting resolve) (zip [0..] rows)) | (txid, rows) <- entries ] @@ -418,8 +471,6 @@ , not (null unresolved) ] - unresolvedPostings = concatMap snd unresolvedEntries- (debitTotal, creditTotal) = let (debitState, creditState) = L.foldl' addTotals (emptyAccum, emptyAccum) (map (certTotals . snd) parsedEntries)@@ -431,7 +482,7 @@ in (debitTotal, creditTotal) journals =- [ journalFromSides rows .| txid+ [ journalForSides rows .| txid | (txid, rows) <- resolvedEntries ] @@ -441,63 +492,40 @@ -> JournalCert n v certifyJournalText = certifyJournalTextIn OrdinaryJournal --- The tuple retains the original account text so resolution failures can be+-- | The tuple retains the original account text so resolution failures can be -- reported without reconstructing user input.-type CertPosting v =- (Int, Text, v, Either ConvError Side, Either ConvError AccountTitles)+type CertPosting acct v =+ (Int, Text, v, Either (ConvErrorOf acct) Side, Either (ConvErrorOf acct) acct) --- Wildcard names have to be recognized here rather than delegated to the--- parsers: 'parseAccountTitle' and 'parseSide' reject the wildcard--- constructors by design (the /correct-by-construction/ guard documented in--- "ExchangeAlgebra.IO.Input.Conversion"), so on the text path a wildcard is indistinguishable--- from an unknown name. Certification must tell them apart, because a wildcard--- is a structural defect ('Rejected') whereas an unknown name is a vocabulary--- gap ('BalancedUnresolved'). Matching uses the parsers' own 'normalizeTitle',--- so the two paths cannot drift apart.-parseCertPosting :: (Int, (Text, Text, v)) -> CertPosting v-parseCertPosting (i, (sideText, accountText, amount)) =- ( i- , accountText- , amount- , if normalizeTitle sideText == T.pack "side"- then Right Side- else parseSide sideText- , if normalizeTitle accountText == T.pack "accounttitle"- then Right AccountTitle- else parseAccountTitle accountText- )+-- | Preserve the row index and raw account name for unresolved entries.+parseCertPosting :: AccountResolver acct -> (Int, (Text, Text, v)) -> CertPosting acct v+parseCertPosting resolve (i, (sideText, accountText, amount)) =+ (i, accountText, amount, side, resolve accountText)+ where+ side | normalizeTitle sideText == "side" = Right Side+ | otherwise = parseInputSide sideText -certStructuralErrors :: (HatVal v)+-- | Collect row defects before the per-transaction balance check.+certStructuralErrors :: (HatVal v, AccountVocabulary acct) => ProcessingContext- -> [CertPosting v]- -> [EntryError v]+ -> [CertPosting acct v]+ -> [EntryErrorOf acct v] certStructuralErrors context rows =- [ EmptyEntry | null rows ] ++ concatMap rowErrors rows+ [EmptyEntry | null rows] ++ concatMap rowErrors rows where- rowErrors (i, _, amount, sideResult, accountResult) =- [ EntryParse i err | Left err <- [sideResult] ]- ++ [ NonPositiveAmount i (resolvedOrWildcard accountResult) amount- | isErrorValue amount || not (amount > 0)- ]- ++ [ WildcardAccount i | Right AccountTitle <- [accountResult] ]- ++ [ WildcardSide i | Right Side <- [sideResult] ]- ++ [ PostingNotAllowed i account capability context- | Right account <- [accountResult]- , account /= AccountTitle- , let capability = postingCapabilityFor account- , not (postingAllowedIn context capability)- ]+ rowErrors (i, _, amount, side, account) =+ [EntryParse i err | Left err <- [side]]+ ++ [EntryParse i err | Left err <- [account], not (vocabularyGap err)]+ ++ postingErrors context i (resolved side) (resolved account) amount - resolvedOrWildcard (Right account) = account- resolvedOrWildcard (Left _) = AccountTitle+ resolved = either (const Nothing) Just+ vocabularyGap UnknownAccount{} = True+ vocabularyGap AmbiguousAccount{} = True+ vocabularyGap _ = False -certTotals :: (HatVal v) => [CertPosting v] -> (Accum v, Accum v)-certTotals rows =- ( L.foldl' (flip addAccum) emptyAccum- [ amount | (_, _, amount, Right Debit, _) <- rows ]- , L.foldl' (flip addAccum) emptyAccum- [ amount | (_, _, amount, Right Credit, _) <- rows ]- )+-- | Include unresolved accounts in the totals for their parsed sides.+certTotals :: HatVal v => [CertPosting acct v] -> (Accum v, Accum v)+certTotals rows = sideTotals [(side, amount) | (_, _, amount, Right side, _) <- rows] -- | Compare source transactions against the note-indexed journal coverage. --@@ -544,40 +572,39 @@ , expectedAmount /= actualAmount ] -validateIndexed :: (HatVal v)- => ProcessingContext- -> Bool- -> [(Int, (Side, AccountTitles, v))]- -> [EntryError v]-validateIndexed context rawEmpty rows =- emptyErrors ++ rowErrors ++ imbalanceErrors- where- emptyErrors = [ EmptyEntry | rawEmpty ]-- rowErrors = concatMap validateRow rows+-- | Report amount, wildcard and capability errors in their input-validation order.+postingErrors :: (HatVal v, AccountVocabulary acct)+ => ProcessingContext -> Int -> Maybe Side -> Maybe acct -> v+ -> [EntryErrorOf acct v]+postingErrors context i side account amount =+ [NonPositiveAmount i (fromMaybe wildcard account) amount | invalidAmount amount]+ ++ [WildcardAccount i | Just title <- [account], isWildcard title]+ ++ [WildcardSide i | side == Just Side]+ ++ case account of+ Just title | not (isWildcard title) -> case vocabSemantics title of+ Nothing -> [MissingPostingSemantics i title]+ Just semantics ->+ let capability = asemPostingCapability semantics+ in [ PostingNotAllowed i title capability context+ | not (postingAllowedIn context capability) ]+ _ -> [] - validateRow (i, (side, account, amount)) =- [ NonPositiveAmount i account amount- | invalidAmount amount- ]- ++ [ WildcardAccount i | account == AccountTitle ]- ++ [ WildcardSide i | side == Side ]- ++ [ PostingNotAllowed i account capability context- | account /= AccountTitle- , let capability = postingCapabilityFor account- , not (postingAllowedIn context capability)- ]+-- | Checked postings require positive, finite amounts.+invalidAmount :: HatVal v => v -> Bool+invalidAmount amount = isErrorValue amount || not (amount > 0) - invalidAmount amount = isErrorValue amount || not (amount > 0)+-- | Accumulate debits and credits before rounding to the value type.+sideTotals :: HatVal v => [(Side, v)] -> (Accum v, Accum v)+sideTotals rows =+ ( L.foldl' (flip addAccum) emptyAccum [amount | (Debit, amount) <- rows]+ , L.foldl' (flip addAccum) emptyAccum [amount | (Credit, amount) <- rows]+ ) - imbalanceErrors- | null rows = []- | otherwise =- [ Imbalanced (roundAccum debit) (roundAccum credit)- | signAccum (mergeAccum debit (negateAccum credit)) /= Just EQ- ]- where- debit = L.foldl' (flip addAccum) emptyAccum- [amount | (_, (Debit, _, amount)) <- rows]- credit = L.foldl' (flip addAccum) emptyAccum- [amount | (_, (Credit, _, amount)) <- rows]+-- | Compare the accumulated totals and round only for error reporting.+balanceErrors :: HatVal v => [(Side, v)] -> [EntryErrorOf acct v]+balanceErrors [] = []+balanceErrors rows =+ [ Imbalanced (roundAccum debit) (roundAccum credit)+ | signAccum (mergeAccum debit (negateAccum credit)) /= Just EQ ]+ where+ (debit, credit) = sideTotals rows
src/ExchangeAlgebra/IO/Input/Conversion.hs view
@@ -1,10 +1,6 @@ {-# LANGUAGE GADTs #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-}--- The alias table intentionally references the deprecated 'Commutation'--- constructor so that its legacy Japanese label ("通信費") is recognized and--- flagged as ambiguous against 'CommunicationExpenses'; silence the warning.-{-# OPTIONS_GHC -Wno-deprecations #-} {- | Module : ExchangeAlgebra.IO.Input.Conversion@@ -18,7 +14,8 @@ so the algebra core stays serialization-free. The mapping from a debit\/credit side to the @Hat@\/@Not@ marker is derived from-the library's own 'whichSide', so the credit\/debit semantics are never duplicated.+the library's own 'ExchangeAlgebra.Accounting.Exchange.whichSide', so the+credit\/debit semantics are never duplicated. Unknown or wildcard account names are rejected (a /correct-by-construction/ guard against hallucinated accounts). Account names that are genuinely ambiguous (one Japanese label shared by several constructors, e.g. @準備預金@ for both the asset@@ -29,7 +26,18 @@ provided in "ExchangeAlgebra.IO.Input.Csv". -} module ExchangeAlgebra.IO.Input.Conversion- ( ConvError(..)+ ( -- * Errors+ ConvErrorOf(..)+ , ConvError+ -- * Account-name tables+ -- $accountNames+ , AccountResolver+ , AccountNameTable+ , accountNameTable+ , extendAccountNames+ , resolveWith+ , defaultAccountNames+ , vocabularyNames -- $concreteAccountTitles , concreteAccountTitles , normalizeTitle@@ -42,34 +50,163 @@ import Data.Char (isAlphaNum, isSpace) import qualified Data.List as L+import Data.List.NonEmpty (NonEmpty(..))+import qualified Data.List.NonEmpty as NE+import qualified Data.Map.Strict as M import Data.Text (Text) import qualified Data.Text as T -import ExchangeAlgebra.Algebra.Core ( Alg, Redundant((.+)), (.@) )+import ExchangeAlgebra.Algebra.Core (Alg) import ExchangeAlgebra.Algebra.Value.Class (HatVal)-import ExchangeAlgebra.Algebra.Base.Representation (HatBase(..), Hat(..))+import ExchangeAlgebra.Algebra.Base.Representation (HatBase, Hat(..)) import ExchangeAlgebra.Accounting.Account (AccountTitles(..), Side(..), accountAliases)-import ExchangeAlgebra.Accounting.Exchange (whichSide)-import ExchangeAlgebra.Accounting.Account.Registry ( concreteAccountTitles )+import ExchangeAlgebra.Accounting.Account.Vocabulary (AccountVocabulary(..))+import ExchangeAlgebra.Accounting.Exchange ( hatForSide+ , postingForSide+ , journalForSides+ )+import ExchangeAlgebra.Accounting.Account.Registry ( AccountSpec(..)+ , concreteAccountTitles )+import ExchangeAlgebra.Algebra.Element.Representation (isWildcard) -- $setup -- The examples use 'Text' literals, so enable @OverloadedStrings@ in doctest. -- >>> :set -XOverloadedStrings --- | Conversion errors. Kept structural so callers can report precisely.-data ConvError = UnknownAccount Text -- ^ name matched no concrete account title- | AmbiguousAccount Text [AccountTitles] -- ^ name matched several accounts (disambiguate by canonical name)- | UnknownSide Text -- ^ side string was not debit\/credit- | MalformedCsv Text -- ^ CSV header\/row was structurally invalid (see "ExchangeAlgebra.IO.Input.Csv")- | BadAmount Text -- ^ amount field was not a valid non-negative number+-- | Conversion errors over an account-title type @acct@. Kept structural so+-- callers can report precisely. 'UnknownAccount' and 'AmbiguousAccount' hold+-- the argument the resolver received, before normalization (the CSV readers+-- pass the field after trimming surrounding whitespace; the checked readers+-- pass the caller's 'Text' unchanged). 'UnknownSide' and 'BadAmount' hold the+-- field likewise; 'MalformedCsv' holds a diagnostic message.+data ConvErrorOf acct+ = UnknownAccount Text -- ^ name matched no title in the table+ | AmbiguousAccount Text [acct] -- ^ name matched several titles, listed in table order (disambiguate by another name)+ | UnknownSide Text -- ^ side string was not debit\/credit+ | MalformedCsv Text -- ^ CSV header\/row was structurally invalid (see "ExchangeAlgebra.IO.Input.Csv")+ | BadAmount Text -- ^ amount field was not a valid non-negative number deriving (Eq, Show) +-- | Conversion errors for the built-in account titles.+--+-- Import @ConvErrorOf(..)@ to bring the constructors into scope: a type+-- synonym does not carry them, so @ConvError(..)@ imports none.+type ConvError = ConvErrorOf AccountTitles++-- $accountNames+-- An 'AccountResolver' turns an external account name into a title. Input+-- readers that take a resolver (@parseJournalCsvBy@, @checkedEntryTextBy@,+-- @certifyJournalTextBy@) accept any title type, so a model with its own+-- vocabulary reads CSV and generated entries with its own names. The usual+-- resolver is 'resolveWith' applied to an t'AccountNameTable'.+--+-- Contract of a resolver @r@ (all readers rely on it):+--+-- * @r t@ fails only with @'UnknownAccount' t@ or @'AmbiguousAccount' t cs@,+-- where @t@ is the argument and @cs@ lists at least two distinct titles.+-- 'resolveWith' meets this. A reader that receives any other 'Left' from a+-- resolver treats it as a parse failure, never as a vocabulary gap.+-- * @r@ may return the wildcard (a table may list it). Readers do not accept+-- it as a posting: the CSV readers report @'UnknownAccount' t@, and the+-- checked readers report a wildcard-account error.++-- | Resolve an external account name. See the contract above.+type AccountResolver acct = Text -> Either (ConvErrorOf acct) acct++-- | Account names and the titles they denote.+--+-- The table holds a normalization function and, for each normalized name, the+-- candidate titles in the order they were added. A name with one candidate+-- resolves; a name with several is ambiguous and is never resolved by picking+-- one. The constructor is not exported: build tables with 'accountNameTable',+-- 'extendAccountNames', 'defaultAccountNames', or 'vocabularyNames'.+data AccountNameTable acct = AccountNameTable+ { _nameNormalize :: Text -> Text+ , _nameCandidates :: M.Map Text (NonEmpty acct)+ }++-- | Build a table from @(name, title)@ pairs.+--+-- Laws (for @tbl = accountNameTable f pairs@ and @r = resolveWith tbl@):+--+-- * The candidates for a name @t@ are the titles paired with some @n@ where+-- @f n == f t@, in the order of @pairs@, each title kept once.+-- * @r t == Right a@ iff that candidate list is @[a]@;+-- @r t == Left (AmbiguousAccount t cs)@ iff it is @cs@ with @length cs >= 2@;+-- @r t == Left (UnknownAccount t)@ iff it is empty.+-- * With @f = id@, matching is exact.+accountNameTable :: Eq acct => (Text -> Text) -> [(Text, acct)] -> AccountNameTable acct+accountNameTable normalize pairs =+ extendAccountNames pairs (AccountNameTable normalize M.empty)++-- | Add @(name, title)@ pairs to a table, normalizing the new names with the+-- table's own function.+--+-- Law: @extendAccountNames new (accountNameTable f old) == accountNameTable f (old ++ new)@,+-- compared through 'resolveWith' on every text. In particular a name that+-- already resolves keeps resolving to the same title unless @new@ pairs it with+-- a different title, in which case it becomes ambiguous with the existing+-- candidates listed first.+extendAccountNames :: Eq acct => [(Text, acct)] -> AccountNameTable acct -> AccountNameTable acct+extendAccountNames pairs (AccountNameTable normalize candidates) =+ AccountNameTable normalize (L.foldl' addName candidates pairs)+ where+ addName table (name, title) = M.alter addCandidate (normalize name) table+ where+ addCandidate Nothing = Just (title :| [])+ addCandidate (Just titles)+ | title `elem` titles = Just titles+ | otherwise = Just (titles <> (title :| []))++-- | The resolver of a table. Normalizes the argument with the table's function+-- and looks up its candidates; see the laws of 'accountNameTable'.+resolveWith :: AccountNameTable acct -> AccountResolver acct+resolveWith (AccountNameTable normalize candidates) name =+ case M.lookup (normalize name) candidates of+ Nothing -> Left (UnknownAccount name)+ Just (title :| []) -> Right title+ Just titles -> Left (AmbiguousAccount name (NE.toList titles))++-- | The names 'parseAccountTitle' accepts: the constructor name ('show') of+-- every title in 'concreteAccountTitles', then the 'accountAliases' of each+-- title, all normalized with 'normalizeTitle'. The wildcard is absent.+--+-- Laws: @resolveWith defaultAccountNames == parseAccountTitle@ on every text,+-- and the result equals the pre-0.7 lookup, including the candidate order of+-- shared labels (\"準備預金\" lists the asset title first, \"通信費\" lists+-- 'CommunicationExpenses' first).+defaultAccountNames :: AccountNameTable AccountTitles+defaultAccountNames = accountNameTable normalizeTitle defaultNameEntries++-- | Names for a user vocabulary, normalized with 'normalizeTitle'. For each+-- listed title, in list order: its 'show' text, then, from its 'vocabSpec',+-- @asNameEn@, @asLabelJa@, and each of @asAliases@. Wildcards in the list are+-- dropped ('isWildcard'), so the table never resolves to the wildcard.+--+-- The English name and the Japanese label are included because a title type+-- that wraps built-in titles (@Std Cash@) shows as a constructor phrase that no+-- external file carries. Two listed titles that share a name make that name+-- ambiguous; it is never resolved by list order.+--+-- @vocabularyNames concreteAccountTitles@ is not 'defaultAccountNames': it+-- lacks the JCCI aliases and the historical candidate order, and it adds the+-- English names and labels. Use 'extendAccountNames' to add names a+-- vocabulary does not carry.+vocabularyNames :: AccountVocabulary t => [t] -> AccountNameTable t+vocabularyNames titles = accountNameTable normalizeTitle+ [ (name, title)+ | title <- titles+ , not (isWildcard title)+ , name <- T.pack (show title) : specNames (vocabSpec title)+ ]+ where+ specNames Nothing = []+ specNames (Just spec) = asNameEn spec : asLabelJa spec : asAliases spec+ -- $concreteAccountTitles -- 'concreteAccountTitles' lists all concrete account titles, /excluding/ the--- wildcard 'AccountTitle', in stable Enum order. It is re-exported from--- "ExchangeAlgebra.Algebra.Base.Account.Registry", which is the single--- definition; external input must never resolve to the wildcard, so callers--- should use this safe range rather than @[minBound .. maxBound]@.+-- wildcard 'AccountTitle', in stable Enum order. Import it from+-- "ExchangeAlgebra.Accounting.Account" when building an input name table. -- -- >>> take 1 concreteAccountTitles -- [Cash]@@ -80,27 +217,17 @@ -- >>> AccountTitle `elem` concreteAccountTitles -- False --- | Account-name lookup table: every key (canonical constructor names and the--- Japanese\/abbreviation aliases below) is run through 'normalizeTitle', so matching is--- case-, whitespace-, and symbol-insensitive. Keys are tagged so that a single--- alias shared by several accounts is reported as 'AmbiguousAccount' rather than--- silently resolving to whichever entry happens to come first.+-- | Name entries of 'defaultAccountNames': canonical constructor names, then the+-- Japanese\/abbreviation aliases. A single alias shared by several accounts is+-- reported as 'AmbiguousAccount' rather than silently resolving to whichever+-- entry happens to come first. -- -- The canonical English names (derived from 'show' over 'concreteAccountTitles') -- are always unique, so they are never ambiguous and always resolve.-accountTable :: [(Text, [AccountTitles])]-accountTable = collapse [ (normalizeTitle k, a) | (k, a) <- entries ]+defaultNameEntries :: [(Text, AccountTitles)]+defaultNameEntries = canonical ++ aliases where- -- Group entries by normalized key, accumulating every account that key maps- -- to (so genuine collisions become ambiguous, not first-wins).- collapse kvs =- [ (k, L.nub as)- | k <- L.nub (L.map fst kvs)- , let as = [ a | (k', a) <- kvs, k' == k ] ] - entries :: [(Text, AccountTitles)]- entries = canonical ++ aliases- -- Canonical: the constructor name. Always unique. canonical = [ (T.pack (show a), a) | a <- concreteAccountTitles ] @@ -163,11 +290,7 @@ -- >>> parseAccountTitle "AccountTitle" -- Left (UnknownAccount "AccountTitle") parseAccountTitle :: Text -> Either ConvError AccountTitles-parseAccountTitle t =- case lookup (normalizeTitle t) accountTable of- Just [a] -> Right a- Just as -> Left (AmbiguousAccount t as)- Nothing -> Left (UnknownAccount t)+parseAccountTitle = resolveWith defaultAccountNames -- | Parse a side string (@"debit"@\/@"credit"@, case-insensitive) into t'Side'. --@@ -184,10 +307,12 @@ _ -> Left (UnknownSide t) -- | The @Hat@\/@Not@ marker that places @account@ on the requested debit\/credit--- @side@. Derived from the library's 'whichSide' so the credit\/debit rule is not--- duplicated: an account sits on its \"natural\" side under 'Not'; if the+-- @side@. Derived from 'ExchangeAlgebra.Accounting.Exchange.whichSide' so the+-- credit\/debit rule is not duplicated: an account sits on its \"natural\" side under 'Not'; if the -- requested side differs, the v'Hat' (reversal) marker is used. --+-- Use 'hatForSide' for bases with components besides the account title.+-- -- >>> markerForSide Debit Cash -- Not -- >>> markerForSide Credit Cash@@ -197,29 +322,31 @@ -- >>> markerForSide Debit Sales -- Hat markerForSide :: Side -> AccountTitles -> Hat-markerForSide side account- | whichSide (Not :< account) == side = Not- | otherwise = Hat+markerForSide = hatForSide -- | Build a single posting term: @amount .\@ (marker :< account)@, with the -- marker chosen so the posting lands on @side@. Built through the smart--- constructor '(.@)' so the non-negative\/non-error value invariant is enforced.+-- constructor 'ExchangeAlgebra.Algebra.Core..@' so the non-negative\/non-error+-- value invariant is enforced. --+-- Use 'postingForSide' for bases with components besides the account title.+-- -- >>> postingFromSide Debit Cash (1000 :: Double) -- 1000.00:@Not:<Cash -- >>> postingFromSide Credit Sales (1000 :: Double) -- 1000.00:@Not:<Sales postingFromSide :: (HatVal v) => Side -> AccountTitles -> v -> Alg v (HatBase AccountTitles)-postingFromSide side account amount =- amount .@ (markerForSide side account :< account)+postingFromSide = postingForSide -- | Fold a list of @(side, account, amount)@ postings into one algebra term. -- Balance (debit == credit) is /not/ enforced here; check it with the library's -- balance functions after conversion. --+-- Use 'journalForSides' for bases with components besides the account title.+-- -- >>> journalFromSides [(Debit, Cash, 1000), (Credit, Sales, 1000)] :: Alg Double (HatBase AccountTitles) -- 1000.00:@Not:<Cash .+ 1000.00:@Not:<Sales journalFromSides :: (HatVal v) => [(Side, AccountTitles, v)] -> Alg v (HatBase AccountTitles)-journalFromSides = foldr (\(s, a, v) acc -> postingFromSide s a v .+ acc) mempty+journalFromSides = journalForSides
src/ExchangeAlgebra/IO/Input/Csv.hs view
@@ -1,5 +1,7 @@ {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-} {- | Module : ExchangeAlgebra.IO.Input.Csv@@ -29,14 +31,16 @@ caller-supplied function so the value type @v@ stays open; 'scientificAmount' covers the common case (a non-negative decimal literal via 'Data.Scientific'). All values are placed through the non-negative smart constructor @(.@)@ inside-'postingFromSide'.+'journalForSides'. -} module ExchangeAlgebra.IO.Input.Csv ( -- * Parsing journal CSV parseJournalCsv , parseJournalCsvWith+ , parseJournalCsvBy -- * Note-keyed journal (when the optional @note@ column is present) , parseNotedJournalCsv+ , parseNotedJournalCsvBy -- * Amount parsers , scientificAmount -- * Field splitting@@ -47,14 +51,17 @@ import Data.Text (Text) import qualified Data.Text as T -import ExchangeAlgebra.Algebra.Core ( Alg, Redundant((.+)) )-import ExchangeAlgebra.Algebra.Value.Class (HatVal)+import ExchangeAlgebra.Algebra.Core (Alg)+import ExchangeAlgebra.Algebra.Value.Class (HatVal, valueError) import ExchangeAlgebra.Algebra.Base.Representation (HatBase) import ExchangeAlgebra.Accounting.Account (AccountTitles, Side)-import ExchangeAlgebra.IO.Input.Conversion ( ConvError(..)+import ExchangeAlgebra.Accounting.Exchange (ExBaseClass, TitleOf, journalForSides)+import ExchangeAlgebra.IO.Input.Conversion ( ConvErrorOf(..)+ , ConvError+ , AccountResolver , parseAccountTitle- , parseSide- , postingFromSide )+ , parseSide )+import ExchangeAlgebra.Algebra.Element.Representation (isWildcard) -- $setup -- >>> :set -XOverloadedStrings@@ -74,7 +81,7 @@ -- Left (BadAmount "-3") -- >>> scientificAmount "1,000" :: Either ConvError Double -- Left (BadAmount "1,000")-scientificAmount :: (Fractional v) => Text -> Either ConvError v+scientificAmount :: (Fractional v) => Text -> Either (ConvErrorOf acct) v scientificAmount t = case reads (T.unpack (T.strip t)) :: [(Sci.Scientific, String)] of [(s, "")] | s >= 0 -> Right (fromRational (toRational s))@@ -98,10 +105,34 @@ => (Text -> Either ConvError v) -> Text -> Either ConvError (Alg v (HatBase AccountTitles))-parseJournalCsvWith amount txt = do- rows <- parseRows amount txt- Right (foldr (\(s, a, v) acc -> postingFromSide s a v .+ acc) mempty rows)+parseJournalCsvWith = parseJournalCsvBy parseAccountTitle +-- | As 'parseJournalCsvWith', but with a caller-supplied account resolver, so+-- the title type @acct@ is the caller's (see+-- 'ExchangeAlgebra.IO.Input.AccountResolver').+--+-- The title type must be the base's own title type+-- (@TitleOf (HatBase acct) ~ acct@), so the wildcard test and the side of each+-- posting read the same vocabulary.+--+-- Laws:+--+-- * @parseJournalCsvBy parseAccountTitle == parseJournalCsvWith@.+-- * @parseJournalCsvBy r a t == fmap (journalForSides . map dropNote) (parseNotedJournalCsvBy r a t)@,+-- where @dropNote (s, k, v, _) = (s, k, v)@. So the term equals+-- 'ExchangeAlgebra.Accounting.Exchange.journalForSides' of the rows in file+-- order: every posting goes through @(.\@)@, nonzero terms on the same+-- base are not combined, and a zero-amount row adds nothing.+parseJournalCsvBy :: (HatVal v, ExBaseClass (HatBase acct), TitleOf (HatBase acct) ~ acct)+ => AccountResolver acct+ -> (Text -> Either (ConvErrorOf acct) v)+ -> Text+ -> Either (ConvErrorOf acct) (Alg v (HatBase acct))+parseJournalCsvBy resolver amount txt =+ journalForSides . map dropNote <$> parseNotedJournalCsvBy resolver amount txt+ where+ dropNote (side, account, value, _) = (side, account, value)+ -- | Parse the rows of a journal CSV into @(Side, AccountTitles, value, note)@ -- tuples, where @note@ is the optional 4th column (empty 'Text' if absent). The -- note is returned as raw 'Text' so the caller can key an@@ -118,10 +149,31 @@ => (Text -> Either ConvError v) -> Text -> Either ConvError [(Side, AccountTitles, v, Text)]-parseNotedJournalCsv amount txt = do- keptHeader <- splitHeader txt- traverse (rowNoted amount) keptHeader+parseNotedJournalCsv = parseNotedJournalCsvBy parseAccountTitle +-- | As 'parseNotedJournalCsv', but with a caller-supplied account resolver.+--+-- Laws:+--+-- * @parseNotedJournalCsvBy parseAccountTitle == parseNotedJournalCsv@.+-- * The header is checked first, then each row in file order: side, then+-- account, then amount; the first failure gives the 'Left'.+-- * A row whose resolver result is the wildcard fails with+-- @'UnknownAccount' t@ (@t@ the trimmed account field).+-- * A row whose amount parser returns @Right x@ with @valueError x /= Nothing@+-- (negative or non-finite) fails with @'BadAmount' t@ (@t@ the trimmed+-- amount field). Before 0.7 such a value passed and @(.\@)@ raised an error+-- when the term was built.+-- * On success the rows are returned in file order, zero amounts included.+parseNotedJournalCsvBy :: (HatVal v, ExBaseClass (HatBase acct), TitleOf (HatBase acct) ~ acct)+ => AccountResolver acct+ -> (Text -> Either (ConvErrorOf acct) v)+ -> Text+ -> Either (ConvErrorOf acct) [(Side, acct, v, Text)]+parseNotedJournalCsvBy resolver amount txt = do+ rows <- splitHeader txt+ traverse (rowNotedBy resolver amount) rows+ -- | Split one line on commas and strip surrounding whitespace from each field. -- No quoting is recognized, so a comma inside a field always separates. An -- empty line yields a single empty field, matching 'T.splitOn'.@@ -132,18 +184,10 @@ -- Internal: minimal CSV plumbing (no quoting), header check, row parse. ------------------------------------------------------------------ --- Parse to bare (Side, AccountTitles, v) triples (note dropped).-parseRows :: (Text -> Either ConvError v)- -> Text- -> Either ConvError [(Side, AccountTitles, v)]-parseRows amount txt = do- keptHeader <- splitHeader txt- traverse (\fs -> (\(s, a, v, _) -> (s, a, v)) <$> rowNoted amount fs) keptHeader- -- | Drop blank\/comment lines, validate the header (@side,account,amount@ with an -- optional @note@ column), and return the remaining data rows as already-split, -- trimmed field lists.-splitHeader :: Text -> Either ConvError [[Text]]+splitHeader :: Text -> Either (ConvErrorOf acct) [[Text]] splitHeader txt = case keptLines of [] -> Left (MalformedCsv "empty CSV (no header)")@@ -159,11 +203,13 @@ keptLines = filter keep (T.lines txt) keep l = let s = T.strip l in not (T.null s) && not ("#" `T.isPrefixOf` s) --- | Parse one already-split row into @(Side, AccountTitles, value, note)@.-rowNoted :: (Text -> Either ConvError v)- -> [Text]- -> Either ConvError (Side, AccountTitles, v, Text)-rowNoted amount fields = case fields of+-- | Parse one already-split row, checking side, account, then amount.+rowNotedBy :: (HatVal v, ExBaseClass (HatBase acct), TitleOf (HatBase acct) ~ acct)+ => AccountResolver acct+ -> (Text -> Either (ConvErrorOf acct) v)+ -> [Text]+ -> Either (ConvErrorOf acct) (Side, acct, v, Text)+rowNotedBy resolver amount fields = case fields of [s, a, v] -> build s a v "" [s, a, v, n] -> build s a v n other -> Left (MalformedCsv@@ -172,7 +218,18 @@ <> T.intercalate "," other)) where build s a v n = do- side <- parseSide s- account <- parseAccountTitle a- value <- amount v- Right (side, account, value, n)+ side <- parseSideBy s+ account <- resolver a+ case isWildcard account of+ True -> Left (UnknownAccount a)+ False -> do+ value <- amount v+ case valueError value of+ Just _ -> Left (BadAmount v)+ Nothing -> Right (side, account, value, n)++-- | Reuse the built-in side parser without fixing the account error type.+parseSideBy :: Text -> Either (ConvErrorOf acct) Side+parseSideBy text = case parseSide text of+ Right side -> Right side+ Left _ -> Left (UnknownSide text)
src/ExchangeAlgebra/IO/Output/Statements.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE OverloadedStrings #-}@@ -92,9 +93,9 @@ -- Subtotal rows must not be summed together with line rows; the @row@ column -- distinguishes them, but the rendered 'Text' cannot enforce it. financialStatementRows- :: HatVal v+ :: (Show t, HatVal v) => [Presentation.StatementSection]- -> Presentation.FinancialStatements v+ -> Presentation.FinancialStatementsOf t v -> Either StatementRowsError [[Text]] financialStatementRows sections statements | requestsResult && not hasResult = Left (PeriodResultMissing@@ -129,10 +130,10 @@ -- | Write 'financialStatementRows' as CSV with 'writeCSV' (every cell quoted). -- Nothing is written when the rows cannot be rendered. writeFinancialStatements- :: HatVal v+ :: (Show t, HatVal v) => FilePath -> [Presentation.StatementSection]- -> Presentation.FinancialStatements v+ -> Presentation.FinancialStatementsOf t v -> IO (Either StatementRowsError ()) writeFinancialStatements path sections statements = case financialStatementRows sections statements of@@ -163,33 +164,44 @@ -- | Build the rows of a journal (仕訳帳), as a pure value (the part -- 'writeJournal' renders to CSV). ----- Entries are grouped by date (via @f@) into a deterministic, deduplicated,--- ascending day sequence; within a day the debit and credit postings are--- listed by 'decL'\/'decR' and padded to equal length with @toSameLength@ ----- no aggregation\/@bar@ is applied, so a day with more debit than credit--- postings (or vice versa) simply gets blank cells on the shorter side.+-- Dates returned by @f@ appear in ascending order. Within each day, debit+-- and credit terms are each listed in account-title order, then by hat base.+-- The sort preserves the relative order of terms with the same hat base.+-- Each term occupies its own row. Blank cells pad the shorter side. -- -- ==== __Examples__ ----- Three days: a capital contribution, a cash sale, and a day with two debit--- postings against one credit posting (the debit column is one line longer,--- and the credit/date cells of that extra line are padded blank):+-- The example records a capital contribution, a cash sale, and a transaction+-- with two debit terms and one credit term. On the third day, the extra debit+-- row has blank date and credit cells. -- -- >>> import Data.Time (fromGregorian)--- >>> type T = Alg Double (HatBase (AccountTitles, Day))--- >>> let d1 = fromGregorian 2024 4 1--- >>> let d2 = fromGregorian 2024 4 2--- >>> let d3 = fromGregorian 2024 4 3--- >>> let getDay (_ :< (_, d)) = d--- >>> let alg = (100 .@ Not:<(Cash,d1)) .+ (100 .@ Not:<(CapitalStock,d1)) .+ (50 .@ Not:<(Cash,d2)) .+ (50 .@ Not:<(Sales,d2)) .+ (30 .@ Not:<(Cash,d3)) .+ (10 .@ Not:<(AccountsReceivable,d3)) .+ (40 .@ Not:<(Sales,d3)) :: T+-- >>> import ExchangeAlgebra.Algebra.Element (Wild(..))+-- >>> type T = Alg Double (HatBase (AccountTitles, Wild Day))+-- >>> let d1 = Exactly (fromGregorian 2024 4 1)+-- >>> let d2 = Exactly (fromGregorian 2024 4 2)+-- >>> let d3 = Exactly (fromGregorian 2024 4 3)+-- >>> :{+-- let getDay (_ :< (_, Exactly day)) = day+-- getDay (_ :< (_, Wild)) = error "journal example requires a date on every entry"+-- alg :: T+-- alg = 100 .@ Not :< (Cash, d1)+-- .+ 100 .@ Not :< (CapitalStock, d1)+-- .+ 50 .@ Not :< (Cash, d2)+-- .+ 50 .@ Not :< (Sales, d2)+-- .+ 30 .@ Not :< (Cash, d3)+-- .+ 10 .@ Not :< (AccountsReceivable, d3)+-- .+ 40 .@ Not :< (Sales, d3)+-- :}+-- -- >>> mapM_ print (journalRows alg getDay) -- ["Day","Debit","Amount","Credit","Amount"] -- ["2024-04-01","Cash","100.0","CapitalStock","100.0"] -- ["2024-04-02","Cash","50.0","Sales","50.0"]--- ["2024-04-03","AccountsReceivable","10.0","Sales","40.0"]--- ["","Cash","30.0","",""]+-- ["2024-04-03","Cash","30.0","Sales","40.0"]+-- ["","AccountsReceivable","10.0","",""] ----- Complexity: O(s * log d) (s = number of entries, d = number of distinct dates)+-- Complexity: O(s * (d + log s)) (s = number of terms, d = number of distinct dates) journalRows :: (HatVal n, HatBaseClass b, ExBaseClass b) => Alg n b -> (b -> Day)@@ -198,18 +210,26 @@ where days = L.sort $ Set.toList . Set.fromList $ L.map (f . _hatBase) $ EA.toList alg rows = L.map perDay days++ perDay :: Day -> ([Text], [Text], [Text], [Text], [Text]) perDay d = let da = EA.filter (\y -> (f . _hatBase) y == d) alg- dl = decL da- dr = decR da- dlTexts = L.map (tshow . getAccountTitle . _hatBase) (EA.toList dl)- drTexts = L.map (tshow . getAccountTitle . _hatBase) (EA.toList dr)- dlValues = L.map (tshow . _val) (EA.toList dl)- drValues = L.map (tshow . _val) (EA.toList dr)+ debitTerms = L.sortOn termOrder $ EA.toList $ decL da+ creditTerms = L.sortOn termOrder $ EA.toList $ decR da+ dlTexts = L.map (tshow . getAccountTitle . _hatBase) debitTerms+ drTexts = L.map (tshow . getAccountTitle . _hatBase) creditTerms+ dlValues = L.map (tshow . _val) debitTerms+ drValues = L.map (tshow . _val) creditTerms (dt', ct') = toSameLength dlTexts drTexts (dv', cv') = toSameLength dlValues drValues (ds', _) = toSameLength [tshow d] cv' in (ds', dt', dv', ct', cv')++ termOrder :: (HatVal v, ExBaseClass a) => Alg v a -> (TitleOf a, a)+ termOrder term =+ let base = _hatBase term+ in (getAccountTitle base, base)+ ds = [T.pack "Day"] ++ concatMap (\(a,_,_,_,_) -> a) rows dt = [T.pack "Debit"] ++ concatMap (\(_,a,_,_,_) -> a) rows dv = [T.pack "Amount"] ++ concatMap (\(_,_,a,_,_) -> a) rows@@ -220,7 +240,7 @@ -- Groups by date and records the debit/credit account titles and amounts for each day. -- Pure layout is delegated to 'journalRows'; this function only writes the file. ----- Complexity: O(s * log d) (s = number of entries, d = number of distinct dates; see 'journalRows')+-- See 'journalRows' for the row order and complexity. writeJournal :: (HatVal n, HatBaseClass b, ExBaseClass b) => FilePath -> Alg n b@@ -265,8 +285,8 @@ -- ["2024-04-01","10.0","",""] -- -- Complexity: O(t * s) (t = number of titles, s = number of entries).-accountLedgerRows :: (HatVal n, HatBaseClass b, ExBaseClass b)- => [AccountTitles]+accountLedgerRows :: (HatVal n, ExBaseClass b)+ => [TitleOf b] -> Alg n b -> (b -> Day) -> [[T.Text]]@@ -298,8 +318,8 @@ -- trail — see 'accountLedgerRows'). -- -- Complexity: O(t * s) (t = number of titles, s = number of entries).-writeAccountOf :: (HatVal n, HatBaseClass b, ExBaseClass b)- => [AccountTitles]+writeAccountOf :: (HatVal n, ExBaseClass b)+ => [TitleOf b] -> FilePath -> Alg n b -> (b -> Day)@@ -337,8 +357,8 @@ -- ["\"sale\"","100.0",""] -- -- Complexity: O(t * s) (t = number of titles, s = number of postings).-accountLedgerRowsJournal :: (HatVal n, HatBaseClass b, ExBaseClass b, EJ.Note note)- => [AccountTitles]+accountLedgerRowsJournal :: (HatVal n, ExBaseClass b, EJ.Note note)+ => [TitleOf b] -> EJ.Journal note n b -> [[T.Text]] accountLedgerRowsJournal titles j =@@ -366,8 +386,8 @@ -- -- Complexity: O(t * s) (t = number of titles, s = number of postings; see -- 'accountLedgerRowsJournal').-writeAccountOfJournal :: (HatVal n, HatBaseClass b, ExBaseClass b, EJ.Note note)- => [AccountTitles]+writeAccountOfJournal :: (HatVal n, ExBaseClass b, EJ.Note note)+ => [TitleOf b] -> FilePath -> EJ.Journal note n b -> IO ()@@ -380,7 +400,7 @@ ------------------------------------------------------------------ -- | Per-account gross debit/credit totals, accumulated in a __single pass__ over--- the algebra's scalar entries (O(s)), keyed by 'AccountTitles' in 'Ord' order.+-- the algebra's scalar entries (O(s)), keyed by 'TitleOf' in 'Ord' order. -- -- Each entry contributes its (non-negative) value to either the debit or the -- credit total of its account title, classified by 'whichSide' (which already@@ -399,7 +419,7 @@ -- -- Complexity: O(s) (s = number of scalar entries). accountGrossTotals :: (HatVal n, ExBaseClass b)- => Alg n b -> OMap.Map AccountTitles (Accum n, Accum n)+ => Alg n b -> OMap.Map (TitleOf b) (Accum n, Accum n) accountGrossTotals = EA.foldEntries step OMap.empty where step totals value base =@@ -450,7 +470,7 @@ -- ["100.0","100.0","Total","100.0","100.0"] -- -- Complexity: O(s) (single pass over s scalar entries; see @accountGrossTotals@)-compoundTrialBalanceRows :: (HatVal n, HatBaseClass b, ExBaseClass b)+compoundTrialBalanceRows :: (HatVal n, ExBaseClass b) => Alg n b -> [[T.Text]] compoundTrialBalanceRows alg = header : lines' ++ [totalLine]@@ -512,7 +532,7 @@ -- -- Complexity: O(s) (single pass over s scalar entries; see -- 'compoundTrialBalanceRows')-writeCompoundTrialBalance :: (HatVal n, HatBaseClass b, ExBaseClass b)+writeCompoundTrialBalance :: (HatVal n, ExBaseClass b) => FilePath -> Alg n b -> IO ()@@ -588,7 +608,7 @@ -- -- Complexity: O(s) (single pass per algebra over s scalar entries; -- see @accountGrossTotals@).-worksheetRows :: (HatVal n, HatBaseClass b, ExBaseClass b)+worksheetRows :: (HatVal n, HatBaseClass b, StandardBase b) => Alg n b -- ^ pre-adjustment ledger (決算整理前残高) -> Alg n b -- ^ adjustment entries (決算整理仕訳) -> [[T.Text]]@@ -694,7 +714,7 @@ -- (P\/L vs B\/S balancing figure) semantics. -- -- Complexity: O(s) (single pass per algebra; see 'worksheetRows').-writeWorksheet :: (HatVal n, HatBaseClass b, ExBaseClass b)+writeWorksheet :: (HatVal n, HatBaseClass b, StandardBase b) => FilePath -> Alg n b -- ^ pre-adjustment ledger -> Alg n b -- ^ adjustment entries@@ -733,7 +753,7 @@ -- ["60.0","Total","60.0"] -- -- Complexity: O(s) (single pass over s scalar entries; see @accountGrossTotals@).-postClosingTrialBalanceRows :: (HatVal n, HatBaseClass b, ExBaseClass b)+postClosingTrialBalanceRows :: (HatVal n, ExBaseClass b) => Alg n b -> [[T.Text]] postClosingTrialBalanceRows alg = header : bodyRows ++ [totalRow]@@ -743,7 +763,7 @@ -- keep only real (Assets/Liability/Equity) titles. totals = accountGrossTotals alg titles = L.filter isReal (OMap.keys totals)- isReal t = let d = classifyAccountDivision t+ isReal t = let d = vocabDivision t in d == Assets || d == Liability || d == Equity (bodyRows, debitTotal, creditTotal) = L.foldl' step ([], emptyAccum, emptyAccum) titles@@ -767,7 +787,7 @@ -- 'Cost'\/'Revenue' accounts are excluded — see 'postClosingTrialBalanceRows'. -- -- Complexity: O(s) (single pass; see 'postClosingTrialBalanceRows').-writePostClosingTrialBalance :: (HatVal n, HatBaseClass b, ExBaseClass b)+writePostClosingTrialBalance :: (HatVal n, ExBaseClass b) => FilePath -> Alg n b -> IO ()
src/ExchangeAlgebra/Journal.hs view
@@ -6,7 +6,7 @@ Import "ExchangeAlgebra.Journal.Core" for generic journal operations and "ExchangeAlgebra.Accounting.Exchange" for accounting operations. - Released under the OWL license+ Released under the MIT license Package for Exchange Algebra defined by Hiroshi Deguchi. @@ -38,9 +38,9 @@ , BaseForSingleHat(..) , HatBase(..) , Element(..)- , AxisKey(..)- , axisIsWildcard- , AxisDecompose(..)+ , ElementKey(..)+ , elementKeyIsWildcard+ , HasElementKeys(..) , (.#) , Name , Subject@@ -54,8 +54,8 @@ , pattern (:@) , (.@) , Note(..)- , NoteAxisKey(..)- , NoteAxisPosting+ , NoteFieldKey(..)+ , NoteFieldIndex , Journal , pattern ExchangeAlgebra.Journal.Zero , mkJournal@@ -78,7 +78,7 @@ , projWithBaseNetNorm , projWithNoteBaseNetNorm , filterWithNote- , filterByAxis+ , filterByNoteField , postFromNetBy , gather ) where@@ -88,8 +88,8 @@ import ExchangeAlgebra.Algebra.Core.Representation (Redundant(..), pattern (:@), (.@)) import ExchangeAlgebra.Journal.Core.Representation as ExchangeAlgebra.Journal ( Note(..)- , NoteAxisKey(..)- , NoteAxisPosting+ , NoteFieldKey(..)+ , NoteFieldIndex , Journal , pattern Zero , mkJournal@@ -112,7 +112,7 @@ , projWithBaseNetNorm , projWithNoteBaseNetNorm , filterWithNote- , filterByAxis+ , filterByNoteField , postFromNetBy , gather )
src/ExchangeAlgebra/Journal/Core.hs view
@@ -11,7 +11,7 @@ -- Combine journals fromList, sigma -- Read entries as an Alg toAlg -- Select notes or bases projWithNote, projWithBase--- Select an indexed note component filterByAxis+-- Select an indexed note field filterByNoteField -- Replace whole notes replaceNotes -- @ --@@ -20,9 +20,9 @@ -- and "ExchangeAlgebra.Accounting.Exchange". "ExchangeAlgebra.Journal" -- re-exports the generic Journal API. module ExchangeAlgebra.Journal.Core ( Note(..)- , HasTermAxis(..)- , NoteAxisKey(..)- , NoteAxisPosting+ , HasNotePeriod(..)+ , NoteFieldKey(..)+ , NoteFieldIndex , Journal , pattern Zero , mkJournal@@ -45,16 +45,16 @@ , projWithBaseNetNorm , projWithNoteBaseNetNorm , filterWithNote- , filterByAxis+ , filterByNoteField , postFromNetBy , gather ) where import Prelude hiding (map) import ExchangeAlgebra.Journal.Core.Representation ( Note(..)- , HasTermAxis(..)- , NoteAxisKey(..)- , NoteAxisPosting+ , HasNotePeriod(..)+ , NoteFieldKey(..)+ , NoteFieldIndex , Journal , pattern Zero , mkJournal@@ -77,7 +77,7 @@ , projWithBaseNetNorm , projWithNoteBaseNetNorm , filterWithNote- , filterByAxis+ , filterByNoteField , postFromNetBy , gather )
src/ExchangeAlgebra/Journal/Core/Representation.hs view
@@ -9,15 +9,16 @@ {-# LANGUAGE BangPatterns #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE ScopedTypeVariables #-} -- | Generic journals, note indices, and redundancy-preserving operations. -- This Journal layer owns the representation and instances for Definitions 10-12. -- It uses generic Algebra owners; "ExchangeAlgebra.Journal.Core" exposes the -- public operations. Read the note definitions before the journal operations. module ExchangeAlgebra.Journal.Core.Representation ( Note(..)- , HasTermAxis(..)- , NoteAxisKey(..)- , NoteAxisPosting+ , HasNotePeriod(..)+ , NoteFieldKey(..)+ , NoteFieldIndex , Journal , pattern Zero , mkJournal@@ -40,7 +41,7 @@ , projWithBaseNetNorm , projWithNoteBaseNetNorm , filterWithNote- , filterByAxis+ , filterByNoteField , postFromNetBy , gather ) where@@ -74,39 +75,39 @@ -- >>> :set -XOverloadedStrings --------------------------------------------------------------------- * NoteAxisKey+-- * NoteFieldKey ------------------------------------------------------------------ --- | An existential type that holds one component of a note with its type erased.--- Used to decompose multi-dimensional Note types (tuples) into keys for each component position--- for indexing, mirroring how @AxisKey@ works for bases in 'Alg'.-data NoteAxisKey = forall a. (Eq a, Hashable a, Typeable a) => NoteAxisKey !a+-- | An existential type that holds one note field with its type erased.+-- Used to decompose tuple notes into keys for their field positions+-- for indexing, mirroring how @ElementKey@ works for bases in 'Alg'.+data NoteFieldKey = forall a. (Eq a, Hashable a, Typeable a) => NoteFieldKey !a -instance Eq NoteAxisKey where- NoteAxisKey x == NoteAxisKey y = case cast y of+instance Eq NoteFieldKey where+ NoteFieldKey x == NoteFieldKey y = case cast y of Nothing -> False Just y' -> x == y' -instance Hashable NoteAxisKey where- hashWithSalt salt (NoteAxisKey x) = salt `hashWithSalt` typeOf x `hashWithSalt` x+instance Hashable NoteFieldKey where+ hashWithSalt salt (NoteFieldKey x) = salt `hashWithSalt` typeOf x `hashWithSalt` x --------------------------------------------------------------------- * NoteAxisPosting+-- * NoteFieldIndex ------------------------------------------------------------------ --- | Per-component index for Note keys.--- Maps axis_number -> axis_value -> set of Notes.+-- | Index of notes by field position and value.+-- Each field value maps to the set of notes that contain it at that position. -- Mirrors @AxisPosting@ in 'Alg'.-type NoteAxisPosting n = IntMap (Map.HashMap NoteAxisKey (HashSet n))+type NoteFieldIndex n = IntMap (Map.HashMap NoteFieldKey (HashSet n)) -{-# INLINE emptyNoteAxisPosting #-}-emptyNoteAxisPosting :: NoteAxisPosting n-emptyNoteAxisPosting = IntMap.empty+{-# INLINE emptyNoteFieldIndex #-}+emptyNoteFieldIndex :: NoteFieldIndex n+emptyNoteFieldIndex = IntMap.empty -{-# INLINE insertNoteAxisPosting #-}+{-# INLINE insertNoteFieldIndex #-} -- | Complexity: O(d) where d is the number of components in the Note-insertNoteAxisPosting :: (Eq n, Hashable n) => [NoteAxisKey] -> n -> NoteAxisPosting n -> NoteAxisPosting n-insertNoteAxisPosting !keys !note !idx =+insertNoteFieldIndex :: (Eq n, Hashable n) => [NoteFieldKey] -> n -> NoteFieldIndex n -> NoteFieldIndex n+insertNoteFieldIndex !keys !note !idx = snd $ L.foldl' step (0 :: Int, idx) keys where step (!axis, !acc) !k =@@ -117,35 +118,12 @@ !acc' = IntMap.insert axis axisMap' acc in (axis + 1, acc') -{-# INLINE deleteNoteAxisPosting #-}--- | Complexity: O(d) where d is the number of components in the Note-deleteNoteAxisPosting :: (Eq n, Hashable n) => [NoteAxisKey] -> n -> NoteAxisPosting n -> NoteAxisPosting n-deleteNoteAxisPosting !keys !note !idx =- snd $ L.foldl' step (0 :: Int, idx) keys- where- step (!axis, !acc) !k =- case IntMap.lookup axis acc of- Nothing -> (axis + 1, acc)- Just axisMap ->- case Map.lookup k axisMap of- Nothing -> (axis + 1, acc)- Just notes0 ->- let !notes1 = HSet.delete note notes0- !axisMap' = if HSet.null notes1- then Map.delete k axisMap- else Map.insert k notes1 axisMap- !acc' = if Map.null axisMap'- then IntMap.delete axis acc- else IntMap.insert axis axisMap' acc- in (axis + 1, acc')--{-# INLINE queryNoteAxisPosting #-}--- | Query the 'NoteAxisPosting' index for one component position.--- Returns the set of Notes whose value matches on the specified component position.+{-# INLINE queryNoteFieldIndex #-}+-- | Query the 'NoteFieldIndex' for notes with the given value at the specified field position. -- -- Complexity: O(1) (two map lookups)-queryNoteAxisPosting :: Int -> NoteAxisKey -> NoteAxisPosting n -> HashSet n-queryNoteAxisPosting !axis !key !idx =+queryNoteFieldIndex :: Int -> NoteFieldKey -> NoteFieldIndex n -> HashSet n+queryNoteFieldIndex !axis !key !idx = case IntMap.lookup axis idx of Nothing -> HSet.empty Just axisMap -> Map.lookupDefault HSet.empty key axisMap@@ -157,10 +135,10 @@ -- | Type class for journal annotations (notes attached to postings). -- @plank@ represents a blank note (analogous to @mempty@ in @Monoid@). ----- @toNoteAxisKeys@ decomposes a Note into keys for each component position for 'NoteAxisPosting'--- indexing, mirroring how @toAxisKeys@ works for bases.--- For tuple Note types, the index uses the position of each component.--- The default returns a single indexed component containing the Note itself.+-- @toNoteFieldKeys@ returns a key for each note field for 'NoteFieldIndex'+-- indexing, mirroring how @toElementKeys@ works for bases.+-- For tuple notes, the index uses the position of each field.+-- The default returns a single key containing the note itself. -- -- == Prefer an ADT note over @String@ --@@ -189,38 +167,37 @@ plank :: a isPlank :: a -> Bool isPlank x = x == plank- -- | Decompose a Note into keys for each component position for 'NoteAxisPosting' indexing.- -- Default: single indexed component with the Note itself.- toNoteAxisKeys :: a -> [NoteAxisKey]- toNoteAxisKeys a = [NoteAxisKey a]+ -- | Return a key for each note field for 'NoteFieldIndex' indexing.+ -- The default returns a single key containing the note itself.+ toNoteFieldKeys :: a -> [NoteFieldKey]+ toNoteFieldKeys a = [NoteFieldKey a] --- | The convention that fixes /which/ part of a 'Note' is the simulation term.+-- | Extracts the simulation period from a 'Note'. ----- A simulation policy or a multi-period ledger maps a Note to its term to--- decide which entries belong to a period. Since a tuple Note has no intrinsic "term" component, the rule--- is fixed here: __the term is the last component of the Note__. The shipped--- instances follow this rule; a custom Note type provides a one-line instance.+-- A simulation policy or a multi-period ledger uses this period to group+-- entries. The built-in tuple instances use the last field as the period.+-- Define an instance to specify the period for a custom note type. ----- >>> termOf ("buy" :: T.Text, 7 :: Int)+-- >>> periodOf ("buy" :: T.Text, 7 :: Int) -- 7 ----- >>> termOf ("buy" :: T.Text, "shopA" :: T.Text, 3 :: Int)+-- >>> periodOf ("buy" :: T.Text, "shopA" :: T.Text, 3 :: Int) -- 3-class (Note n, Ord (TermOf n)) => HasTermAxis n where- -- | The term type extracted from the Note.- type TermOf n- -- | Extract the term (last Note component, by the library convention).- termOf :: n -> TermOf n+class (Note n, Ord (PeriodOf n)) => HasNotePeriod n where+ -- | The type of the period extracted from the note.+ type PeriodOf n+ -- | Extract the period. The tuple instances use the last field.+ periodOf :: n -> PeriodOf n --- | Pair Note: the term is the second (last) component.-instance (Note e, Note t) => HasTermAxis (e, t) where- type TermOf (e, t) = t- termOf = snd+-- | The second field of a pair note is its period.+instance (Note e, Note t) => HasNotePeriod (e, t) where+ type PeriodOf (e, t) = t+ periodOf = snd --- | Triple Note: the term is the third (last) component.-instance (Note e1, Note e2, Note t) => HasTermAxis (e1, e2, t) where- type TermOf (e1, e2, t) = t- termOf (_, _, t) = t+-- | The third field of a triple note is its period.+instance (Note e1, Note e2, Note t) => HasNotePeriod (e1, e2, t) where+ type PeriodOf (e1, e2, t) = t+ periodOf (_, _, t) = t -- | Default instance for using @Int@ to represent a simulation term. -- @plank = -1@ is distinguished from non-negative term numbers.@@ -246,30 +223,32 @@ instance (Note a, Note b) => Note (a, b) where plank = (plank, plank)- toNoteAxisKeys (a, b) = [NoteAxisKey a, NoteAxisKey b]+ toNoteFieldKeys (a, b) = [NoteFieldKey a, NoteFieldKey b] instance (Note a, Note b, Note c) => Note (a, b, c) where plank = (plank, plank, plank)- toNoteAxisKeys (a, b, c) = [NoteAxisKey a, NoteAxisKey b, NoteAxisKey c]+ toNoteFieldKeys (a, b, c) = [NoteFieldKey a, NoteFieldKey b, NoteFieldKey c] instance (Note a, Note b, Note c, Note d) => Note (a, b, c, d) where plank = (plank, plank, plank, plank)- toNoteAxisKeys (a, b, c, d) = [NoteAxisKey a, NoteAxisKey b, NoteAxisKey c, NoteAxisKey d]+ toNoteFieldKeys (a, b, c, d) = [NoteFieldKey a, NoteFieldKey b, NoteFieldKey c, NoteFieldKey d] ------------------------------------------------------------------ -- * Journal ------------------------------------------------------------------ -- | Transaction data with annotations.--- Stored in a base + delta two-layer structure with indices by component position.--- Base index is lazy (built on first component query), while delta index is updated incrementally.+-- Stored in two layers, base and delta, with a note index for each layer.+-- A query by note component builds both indices on first use. Each append leaves+-- a new unevaluated delta index, so alternating queries and appends rebuild it in time+-- proportional to the delta note count, bounded by compaction at 128 notes. -- Updates are appended only to delta and periodically compacted into base. -- -- __Invariants.__ The constructor is not exported; build with 'mkJournal', -- '(.|)' or 'fromList'. Its internal cache\/index fields @_jBaseAxis@ and -- @_jDeltaAxis@ must be--- exactly the note component indices (@buildNoteAxisPosting@) of @_jBase@ and--- @_jDelta@ respectively. The component-filtered query path ('filterByAxis') reads+-- exactly the note field indices (@buildNoteFieldIndex@) of @_jBase@ and+-- @_jDelta@ respectively. The component-filtered query path ('filterByNoteField') reads -- those indices, so a value whose indices disagree with its maps yields wrong -- answers silently (not an exception). --@@ -288,20 +267,22 @@ Journal :: (Note n, HatVal v, HatBaseClass b) => { _jBase :: !(Map.HashMap n (Alg v b)) , _jDelta :: !(Map.HashMap n (Alg v b))- , _jBaseAxis :: NoteAxisPosting n- , _jDeltaAxis :: !(NoteAxisPosting n)+ , _jBaseAxis :: NoteFieldIndex n+ , _jDeltaAxis :: NoteFieldIndex n+ -- ^ Built lazily: only 'filterByNoteField' reads this cache.+ -- A strict field builds an index on every '(.|)' and append. } -> Journal n v b deltaCompactThreshold :: Int deltaCompactThreshold = 128 --- | Build note component index from map keys.-{-# INLINE buildNoteAxisPosting #-}-buildNoteAxisPosting :: Note n => Map.HashMap n a -> NoteAxisPosting n-buildNoteAxisPosting =+-- | Build the note field index from map keys.+{-# INLINE buildNoteFieldIndex #-}+buildNoteFieldIndex :: Note n => Map.HashMap n a -> NoteFieldIndex n+buildNoteFieldIndex = Map.foldlWithKey'- (\acc n _ -> insertNoteAxisPosting (toNoteAxisKeys n) n acc)- emptyNoteAxisPosting+ (\acc n _ -> insertNoteFieldIndex (toNoteFieldKeys n) n acc)+ emptyNoteFieldIndex -- | The only safe way to build a t'Journal' from a base layer and a delta -- layer. It keeps the note component indices consistent with both layers and@@ -312,8 +293,7 @@ -- given, and only a map that holds one is rebuilt without it. -- -- Complexity: O(n) where n is the number of notes in both layers; each note's--- algebra is evaluated to WHNF. The base component index is lazy, while the delta--- component index is built eagerly.+-- algebra is evaluated to WHNF. Both note indices are built on demand. {-# INLINE mkJournal #-} mkJournal :: (Note n, HatVal v, HatBaseClass b) => Map.HashMap n (Alg v b) -> Map.HashMap n (Alg v b) -> Journal n v b@@ -329,14 +309,14 @@ -- Internal constructor for callers that already hold the normal form (see the -- invariants note on t'Journal'): neither map may hold a note whose algebra is -- zero. It does not check this. It builds the note component indices as--- 'mkJournal' does: the base component index lazily, the delta component index eagerly.+-- 'mkJournal' does: both indices are built on demand. {-# INLINE mkJournalNonZero #-} mkJournalNonZero :: (Note n, HatVal v, HatBaseClass b) => Map.HashMap n (Alg v b) -> Map.HashMap n (Alg v b) -> Journal n v b mkJournalNonZero bs delta = Journal bs delta baseIdx deltaIdx where- ~baseIdx = buildNoteAxisPosting bs- !deltaIdx = buildNoteAxisPosting delta+ ~baseIdx = buildNoteFieldIndex bs+ ~deltaIdx = buildNoteFieldIndex delta -- | Construct a Journal from a HashMap. A note whose algebra is zero is -- dropped (see 'mkJournal').@@ -393,34 +373,26 @@ | otherwise = mkJournalNonZero (Map.unionWith (.+) bs delta) Map.empty {-# INLINE appendMap #-}-appendMap :: (HatVal v, HatBaseClass b, Note n)+appendMap :: forall v b n. (HatVal v, HatBaseClass b, Note n) => Map.HashMap n (Alg v b) -> Journal n v b -> Journal n v b-appendMap rhs j@(Journal bs delta baseAxis deltaAxis)+appendMap rhs j@(Journal bs delta baseAxis _) | Map.null rhs = j | otherwise = compactIfNeeded $ Journal bs delta' baseAxis deltaAxis' where- (delta', deltaAxis') = Map.foldlWithKey' step (delta, deltaAxis) rhs+ ~deltaAxis' = buildNoteFieldIndex delta'+ !delta' = Map.foldlWithKey' step delta rhs - step (!dAcc, !idxAcc) !k !v =+ step :: Map.HashMap n (Alg v b) -> n -> Alg v b -> Map.HashMap n (Alg v b)+ step !dAcc !k !v = case Map.lookup k dAcc of- -- New note key: index it (insert) unless the value is zero. Nothing- | EA.isZero v -> (dAcc, idxAcc)- | otherwise ->- ( Map.insert k v dAcc- , insertNoteAxisPosting (toNoteAxisKeys k) k idxAcc )- -- Existing note key: 'k' is already in the delta component index- -- (the index tracks exactly the keys present in delta, and the- -- note IS the key, so its component keys are unchanged). The- -- re-insert was therefore idempotent — skip it. Only a result- -- that collapses to zero changes the index, via delete- -- (audit R5 / ROAD_MAP P1b).+ | EA.isZero v -> dAcc+ | otherwise -> Map.insert k v dAcc Just dv -> let !dMerged = dv .+ v in if EA.isZero dMerged- then ( Map.delete k dAcc- , deleteNoteAxisPosting (toNoteAxisKeys k) k idxAcc )- else ( Map.insert k dMerged dAcc, idxAcc )+ then Map.delete k dAcc+ else Map.insert k dMerged dAcc -- | Serialize a journal as its note count followed by each note and its -- algebra. Decoding checks each algebra as the 'Alg' instance does and fails@@ -473,6 +445,17 @@ -- Returns an empty Journal when the member of the redundant algebra is zero, consistent with -- the zero-value handling in @appendMap@ and 'sigmaOn'. --+-- Fixity @infix 5@: it binds more tightly than '(.+)' and less tightly than+-- '(.@)', so each term carries its own note and a multi-term algebra needs+-- parentheses.+--+-- >>> type FixityTest = Journal T.Text Double (HatBase CountUnit)+-- >>> j = 10.00.@Not:<Yen .| "a" .+ 20.00.@Hat:<Yen .| "b" :: FixityTest+-- >>> toMap j == toMap ((10.00.@Not:<Yen .| "a") .+ (20.00.@Hat:<Yen .| "b"))+-- True+-- >>> toMap ((10.00.@Not:<Yen .+ 20.00.@Hat:<Dollar) .| "a" :: FixityTest) == toMap ((10.00.@Not:<Yen .| "a") .+ (20.00.@Hat:<Dollar .| "a"))+-- True+-- -- Complexity: O(1) (.|) :: (HatVal v, HatBaseClass b, Note n) => Alg v b -> n -> Journal n v b@@ -480,15 +463,16 @@ | EA.isZero alg = mempty | otherwise = mkJournalNonZero Map.empty (Map.singleton n alg) -infixr 2 .|+infix 5 .| ------------------------------------------------------------------ -- Show --------------------------------------------------------------------- | Render each non-blank note as the sum of its algebra entries followed by--- one '(.|)'. A single group needs no parentheses because '(.+)' binds more--- tightly than '(.|)'; multiple groups are parenthesized individually so the--- result can be pasted back as an expression with the current fixities.+-- | Render each non-blank note as its algebra entries followed by one '(.|)'.+-- Because '(.|)' binds more tightly than '(.+)', the entries of one note are+-- parenthesized when there are two or more of them, and the groups are joined+-- with '(.+)' without parentheses. The result can be pasted back as an+-- expression with the current fixities. -- -- The blank note remains invisible when it is the only group. In a mixed -- journal it is rendered explicitly, so every summand is one complete group.@@ -498,18 +482,18 @@ -- 0 -- >>> (5.00.@Not:<Yen .| plank :: ShowTest) -- 5.00:@Not:<Yen--- >>> one = 20.00.@Not:<Yen .+ 20.00.@Hat:<Dollar .| "N" :: ShowTest+-- >>> one = (20.00.@Not:<Yen .+ 20.00.@Hat:<Dollar) .| "N" :: ShowTest -- >>> one--- 20.00:@Hat:<Dollar .+ 20.00:@Not:<Yen .| "N"--- >>> toMap (20.00.@Hat:<Dollar .+ 20.00.@Not:<Yen .| "N" :: ShowTest) == toMap one+-- (20.00:@Hat:<Dollar .+ 20.00:@Not:<Yen) .| "N"+-- >>> toMap ((20.00.@Hat:<Dollar .+ 20.00.@Not:<Yen) .| "N" :: ShowTest) == toMap one -- True -- >>> two = 10.00.@Hat:<Yen .| "M" :: ShowTest--- >>> show (one .+ two) `elem` ["(10.00:@Hat:<Yen .| \"M\") .+ (20.00:@Hat:<Dollar .+ 20.00:@Not:<Yen .| \"N\")", "(20.00:@Hat:<Dollar .+ 20.00:@Not:<Yen .| \"N\") .+ (10.00:@Hat:<Yen .| \"M\")"]+-- >>> show (one .+ two) `elem` ["10.00:@Hat:<Yen .| \"M\" .+ (20.00:@Hat:<Dollar .+ 20.00:@Not:<Yen) .| \"N\"", "(20.00:@Hat:<Dollar .+ 20.00:@Not:<Yen) .| \"N\" .+ 10.00:@Hat:<Yen .| \"M\""] -- True--- >>> toMap ((10.00.@Hat:<Yen .| "M") .+ (20.00.@Hat:<Dollar .+ 20.00.@Not:<Yen .| "N") :: ShowTest) == toMap (one .+ two)+-- >>> toMap ((10.00.@Hat:<Yen .| "M") .+ ((20.00.@Hat:<Dollar .+ 20.00.@Not:<Yen) .| "N") :: ShowTest) == toMap (one .+ two) -- True -- >>> blank = 5.00.@Not:<Yen .| plank :: ShowTest--- >>> show (one .+ blank) `elem` ["(20.00:@Hat:<Dollar .+ 20.00:@Not:<Yen .| \"N\") .+ (5.00:@Not:<Yen .| \"\")", "(5.00:@Not:<Yen .| \"\") .+ (20.00:@Hat:<Dollar .+ 20.00:@Not:<Yen .| \"N\")"]+-- >>> show (one .+ blank) `elem` ["(20.00:@Hat:<Dollar .+ 20.00:@Not:<Yen) .| \"N\" .+ 5.00:@Not:<Yen .| \"\"", "5.00:@Not:<Yen .| \"\" .+ (20.00:@Hat:<Dollar .+ 20.00:@Not:<Yen) .| \"N\""] -- True instance (HatVal v, HatBaseClass b, Note n) => Show (Journal n v b) where showsPrec d js =@@ -517,7 +501,7 @@ [] -> showString "0" [(k, a)] | isPlank k -> showsPrec d a- | otherwise -> showParen (d > 2) (showsGroup k a)+ | otherwise -> showParen (d > 5) (showsGroup k a) _ -> showParen (d > 3) (showsGroups groups) where m = toMap js@@ -528,20 +512,22 @@ | otherwise = (k, a) : acc showsGroups [] = id- showsGroups [(k, a)] = showParen True (showsGroup k a)+ showsGroups [(k, a)] = showsGroup k a showsGroups ((k, a):rest) =- showParen True (showsGroup k a)+ showsGroup k a . showString " .+ " . showsGroups rest showsGroup k a = showsGroupAlg k a . showString " .| "- . showsPrec 3 k+ . showsPrec 6 k - showsGroupAlg k a- | isPlank k = showsPrec 3 a- | otherwise = showsAlgEntries (reverse (EA.toASCList a))+ showsGroupAlg k a =+ case (if isPlank k then id else reverse) (EA.toASCList a) of+ [] -> showString "0"+ [x] -> showsPrec 6 x+ xs -> showParen True (showsAlgEntries xs) showsAlgEntries [] = showString "0" showsAlgEntries [x] = showsPrec 3 x@@ -560,9 +546,9 @@ -- Complexity: Amortized O(size(rhs)); O(n) compaction when the delta exceeds the threshold -- -- >>> type Test = Journal T.Text Double (HatBase CountUnit)--- >>> x = 20.00.@Not:<Yen .+ 20.00.@Hat:<Dollar .| "Withdrawal" :: Test--- >>> y = 10.00.@Hat:<Yen .+ 10.00.@Not:<Dollar .| "Deposits" :: Test--- >>> toMap (x .+ y) == toMap ((10.00.@Not:<Dollar .+ 10.00.@Hat:<Yen .| "Deposits") .+ (20.00.@Hat:<Dollar .+ 20.00.@Not:<Yen .| "Withdrawal") :: Test)+-- >>> x = (20.00.@Not:<Yen .+ 20.00.@Hat:<Dollar) .| "Withdrawal" :: Test+-- >>> y = (10.00.@Hat:<Yen .+ 10.00.@Not:<Dollar) .| "Deposits" :: Test+-- >>> toMap (x .+ y) == toMap (((10.00.@Not:<Dollar .+ 10.00.@Hat:<Yen) .| "Deposits") .+ ((20.00.@Hat:<Dollar .+ 20.00.@Not:<Yen) .| "Withdrawal") :: Test) -- True addJournal :: (HatVal v, HatBaseClass b, Note n) => Journal n v b -> Journal n v b -> Journal n v b@@ -600,33 +586,8 @@ compress = map compress --------------------------------------------------------------------- | Build a t'Journal' from a list of postings. @O(N)@ via a strict left fold--- (@L.foldl' (.+) mempty@).------ == Why a strict left fold------ This was previously a lazy right fold (@foldr (.+) mempty@), kept that way to--- freeze the same-base accumulation order for 'Double' (whose addition is--- non-associative, so reordering affected the former sequential 'norm'). The strict left--- fold is far cheaper at scale — the lazy right fold builds a deep right-nested--- thunk that is expensive to force (≈40x at N=20000, ~15x at N=10000 in the core--- benchmark). The fold direction was switched to the fast version once the--- audited/exact path moved to t'ExchangeAlgebra.Algebra.Value.MoneyDecimal'; see--- plans/in-progress/LAZY_EVAL_AUDIT.md and SELECTABLE_VALUE_TYPE_PLAN.md.------ == Behavior contract------ 'fromList' preserves the /multiset/ of postings exactly (no posting is added,--- dropped, or merged across bases that would otherwise be kept apart). When two--- postings collide on the /same note key and same base/ (and therefore land in--- one t'ExchangeAlgebra.Algebra.Core.Alg' sequence) the strict left fold orders that--- @Seq@ opposite to the old lazy right fold. That order is observable through--- 'Eq' \/ 'Show' \/ @Binary@, and for 'Double' through the sequential--- sums in 'barWithin' (IEEE-754 addition is non-associative). Postings that differ in--- note or base land in separate map entries and are unaffected.------ For finite postings, 'norm', 'bar', and balance are independent of--- construction order for every value type, including Double and MoneyDouble.+-- | Build a t'Journal' from a list using a strict left fold.+-- Each note retains the input order of the terms on each base and side. -- -- >>> type Test = Journal T.Text Double (HatBase CountUnit) -- >>> x = [(1.00.@Hat:<Yen .| z) | z <- ["Loan Payment","Purchace Apple"]] :: [Test]@@ -650,7 +611,7 @@ where mergeOne !m !n !alg | EA.isZero alg = m- | otherwise = Map.insertWith (.+) n alg m+ | otherwise = Map.insertWith (flip (.+)) n alg m {-# INLINE mergeJournalMapIfNonZero #-} mergeJournalMapIfNonZero :: (HatVal v, HatBaseClass b, Note n)@@ -661,7 +622,8 @@ | isZero js = acc | otherwise = mergeJournalMap acc js --- | Summation function that applies a function to each list element and sums the resulting Journals.+-- | Apply a function to each list element and sum the resulting journals.+-- Terms for each note, base, and side retain their list order. -- -- Complexity: O(|xs| * union cost) {-# INLINE sigma #-}@@ -764,26 +726,19 @@ -- -- Complexity: O(|xs| * cost(f)) ----- NOTE: kept as @mconcat <$> forM xs f@ deliberately. A strict @foldM@ left fold--- was tried (plan WI-3) but it changes the '<>' association order, which for--- 'Alg'/t'Journal' reorders the audit-trail sequence. The order is observable--- through Eq, Show, Binary, and the sequential sums in barWithin. For finite--- postings, norm, bar, and balance are order-independent for every value type.--- See plans/in-progress/LAZY_EVAL_AUDIT.md (WI-3).+-- Effects run in list order. The result combines their values using 'mconcat'. sigmaM :: (Monoid m, Monad m0) => [a] -> (a -> m0 m) -> m0 m sigmaM xs f = mconcat <$> CM.forM xs f --------------------------------------------------------------------- | Combine entries from all Notes in a Journal into a single Alg.+-- | Combine all notes into a single algebra.+-- Merge both layers of each note first, then combine notes in the traversal+-- order of the resulting @HashMap@. ----- Complexity: O(total number of base keys across all Notes)+-- Complexity: O(total number of base keys across all notes) toAlg :: (HatVal v, HatBaseClass b, Note n) => Journal n v b -> Alg v b-toAlg (Journal bs delta _ _) =- -- Fold the base terms directly onto the delta term list instead of- -- @Map.elems base ++ Map.elems delta@, which avoids materializing the- -- separate @Map.elems base@ list and the @(++)@ traversal.- EA.unionsMerge (Map.foldr (:) (Map.elems delta) bs)+toAlg = EA.unionsMerge . materializeMap ------------------------------------------------------------------ -- | Apply function f to the entry of each Note in the Journal.@@ -831,10 +786,10 @@ -- returned unchanged (the blank note matches every note). -- -- >>> type Test = Journal T.Text Double (HatBase CountUnit)--- >>> x = 1.00.@Hat:<Yen .+ 1.00.@Not:<Amount .| "cat" :: Test--- >>> y = 2.00.@Hat:<Yen .+ 2.00.@Not:<Amount .| "dog" :: Test--- >>> z = 3.00.@Hat:<Yen .+ 3.00.@Not:<Amount .| "fish" :: Test--- >>> toMap (projWithNote ["dog","cat"] (x .+ y .+ z)) == toMap ((1.00.@Not:<Amount .+ 1.00.@Hat:<Yen .| "cat") .+ (2.00.@Not:<Amount .+ 2.00.@Hat:<Yen .| "dog") :: Test)+-- >>> x = (1.00.@Hat:<Yen .+ 1.00.@Not:<Amount) .| "cat" :: Test+-- >>> y = (2.00.@Hat:<Yen .+ 2.00.@Not:<Amount) .| "dog" :: Test+-- >>> z = (3.00.@Hat:<Yen .+ 3.00.@Not:<Amount) .| "fish" :: Test+-- >>> toMap (projWithNote ["dog","cat"] (x .+ y .+ z)) == toMap (((1.00.@Not:<Amount .+ 1.00.@Hat:<Yen) .| "cat") .+ ((2.00.@Not:<Amount .+ 2.00.@Hat:<Yen) .| "dog") :: Test) -- True projWithNote :: (HatVal v, HatBaseClass b, Note n) => [n] -> Journal n v b -> Journal n v b@@ -858,9 +813,9 @@ -- normal form on t'Journal'). -- -- >>> type Test = Journal T.Text Double (HatBase CountUnit)--- >>> x = 1.00.@Hat:<Yen .+ 1.00.@Not:<Amount .| "cat" :: Test--- >>> y = 2.00.@Not:<Yen .+ 2.00.@Hat:<Amount .| "dog" :: Test--- >>> z = 3.00.@Hat:<Yen .+ 3.00.@Not:<Amount .| "fish" :: Test+-- >>> x = (1.00.@Hat:<Yen .+ 1.00.@Not:<Amount) .| "cat" :: Test+-- >>> y = (2.00.@Not:<Yen .+ 2.00.@Hat:<Amount) .| "dog" :: Test+-- >>> z = (3.00.@Hat:<Yen .+ 3.00.@Not:<Amount) .| "fish" :: Test -- >>> L.sort [(n, EA.toASCList a) | (n, a) <- Map.toList (toMap (projWithBase [Not:<Amount] (x .+ y .+ z)))] -- [("cat",[1.00:@Not:<Amount]),("fish",[3.00:@Not:<Amount])] projWithBase :: (HatVal v, HatBaseClass b, Note n)@@ -906,9 +861,9 @@ -- all notes (falls back to 'projWithBase'). -- -- >>> type Test = Journal T.Text Double (HatBase CountUnit)--- >>> x = 1.00.@Hat:<Yen .+ 1.00.@Not:<Amount .| "cat" :: Test--- >>> y = 2.00.@Not:<Yen .+ 2.00.@Hat:<Amount .| "dog" :: Test--- >>> z = 3.00.@Hat:<Yen .+ 3.00.@Not:<Amount .| "fish" :: Test+-- >>> x = (1.00.@Hat:<Yen .+ 1.00.@Not:<Amount) .| "cat" :: Test+-- >>> y = (2.00.@Not:<Yen .+ 2.00.@Hat:<Amount) .| "dog" :: Test+-- >>> z = (3.00.@Hat:<Yen .+ 3.00.@Not:<Amount) .| "fish" :: Test -- >>> projWithNoteBase ["dog","fish"] [Not:<Amount] (x .+ y .+ z) -- 3.00:@Not:<Amount .| "fish" projWithNoteBase :: (HatVal v, HatBaseClass b, Note n)@@ -982,45 +937,68 @@ -- 'projWithNoteBaseNetNorm' explicitly. --------------------------------------------------------------------- | Filter by a predicate on Note-entry pairs.--- Applies the filter to both the base and delta layers.+-- | Retain a note and all its terms when the predicate accepts the note and+-- its algebra. The predicate runs once per note and receives the same algebra+-- as in 'toMap'. A shared note's algebra is combined only if the predicate+-- evaluates it. ----- Complexity: O(n) where n is the number of Notes-filterWithNote :: (HatVal v, HatBaseClass b, Note n)- => (n -> Alg v b -> Bool) -> Journal n v b -> Journal n v b-filterWithNote f (Journal bs delta _ _) =- let !base' = Map.filterWithKey f bs- !delta' = Map.filterWithKey f delta- in mkJournalNonZero base' delta'+-- Complexity: O(n) expected for scanning both layers and looking up notes,+-- plus the costs of the predicates and any algebra additions they evaluate.+-- Here n is the number of notes across the two layers.+filterWithNote :: forall v b n. (HatVal v, HatBaseClass b, Note n)+ => (n -> Alg v b -> Bool)+ -> Journal n v b+ -> Journal n v b+filterWithNote predicate (Journal baseLayer deltaLayer _ _)+ | Map.null deltaLayer = mkJournalNonZero (Map.filterWithKey predicate baseLayer) Map.empty+ | Map.null baseLayer = mkJournalNonZero Map.empty (Map.filterWithKey predicate deltaLayer)+ | otherwise = mkJournalNonZero retainedBase retainedDelta+ where+ retainedBase :: Map.HashMap n (Alg v b)+ retainedBase = Map.filterWithKey keepBase baseLayer --- | Efficiently filter a Journal to entries whose Note matches on the specified component position.--- Uses base/delta NoteAxisPosting indices for O(|result|) retrieval after index construction.+ retainedDelta :: Map.HashMap n (Alg v b)+ retainedDelta = Map.filterWithKey keepDelta deltaLayer++ keepBase :: n -> Alg v b -> Bool+ keepBase note algebra = case Map.lookup note deltaLayer of+ Nothing -> predicate note algebra+ Just delta -> predicate note (algebra .+ delta)++ keepDelta :: n -> Alg v b -> Bool+ keepDelta note algebra+ | Map.member note baseLayer = Map.member note retainedBase+ | otherwise = predicate note algebra++-- | Select journal entries whose note has the specified value at the given field position.+-- Uses the base and delta 'NoteFieldIndex' caches for O(|result|) retrieval+-- after index construction. ----- Component positions are 0-indexed. For a Note type @(EventName, Term)@:+-- Field positions are zero-based. For a note of type @(EventName, Term)@: ----- * position 0 corresponds to EventName--- * position 1 corresponds to Term+-- * Position 0 holds the event name.+-- * Position 1 holds the period. ----- For non-tuple Note types, position 0 is the only valid position.+-- For non-tuple notes, position 0 is the only valid position. ----- Complexity: O(|result|) after index construction; O(n) for first base component query on a Journal value+-- Complexity: O(|result|) after index construction; O(n) for the first base note field query on a Journal value -- -- >>> type Test = Journal (T.Text, Int) Double (HatBase CountUnit) -- >>> x = 10.00.@Not:<Yen .| ("A", 1) :: Test -- >>> y = 20.00.@Hat:<Yen .| ("B", 1) :: Test -- >>> z = 30.00.@Not:<Yen .| ("A", 2) :: Test--- >>> toMap (filterByAxis 0 (NoteAxisKey ("A" :: T.Text)) (x .+ y .+ z)) == toMap ((10.00.@Not:<Yen .| ("A",1)) .+ (30.00.@Not:<Yen .| ("A",2)) :: Test)+-- >>> toMap (filterByNoteField 0 (NoteFieldKey ("A" :: T.Text)) (x .+ y .+ z)) == toMap ((10.00.@Not:<Yen .| ("A",1)) .+ (30.00.@Not:<Yen .| ("A",2)) :: Test) -- True ----- >>> toMap (filterByAxis 1 (NoteAxisKey (1 :: Int)) (x .+ y .+ z)) == toMap ((10.00.@Not:<Yen .| ("A",1)) .+ (20.00.@Hat:<Yen .| ("B",1)) :: Test)+-- >>> toMap (filterByNoteField 1 (NoteFieldKey (1 :: Int)) (x .+ y .+ z)) == toMap ((10.00.@Not:<Yen .| ("A",1)) .+ (20.00.@Hat:<Yen .| ("B",1)) :: Test) -- True-{-# INLINE filterByAxis #-}-filterByAxis :: (HatVal v, HatBaseClass b, Note n)- => Int -> NoteAxisKey -> Journal n v b -> Journal n v b-filterByAxis axis key j@(Journal _ _ baseIdx deltaIdx) =+{-# INLINE filterByNoteField #-}+filterByNoteField :: (HatVal v, HatBaseClass b, Note n)+ => Int -> NoteFieldKey -> Journal n v b -> Journal n v b+filterByNoteField axis key j@(Journal _ _ baseIdx deltaIdx) = let !matched = HSet.union- (queryNoteAxisPosting axis key baseIdx)- (queryNoteAxisPosting axis key deltaIdx)+ (queryNoteFieldIndex axis key baseIdx)+ (queryNoteFieldIndex axis key deltaIdx) !result = HSet.foldl' (\acc n -> case lookupNote n j of Nothing -> acc@@ -1034,10 +1012,10 @@ -- Gathers all Alg into one on the given Note. -- -- >>> type Test = Journal T.Text Double (EA.HatBase EA.CountUnit)--- >>> x = 20.00.@Not:<Yen .+ 20.00.@Hat:<Dollar .| "Withdrawal" :: Test--- >>> y = 10.00.@Hat:<Yen .+ 10.00.@Not:<Dollar .| "Deposits" :: Test+-- >>> x = (20.00.@Not:<Yen .+ 20.00.@Hat:<Dollar) .| "Withdrawal" :: Test+-- >>> y = (10.00.@Hat:<Yen .+ 10.00.@Not:<Dollar) .| "Deposits" :: Test -- >>> gather "A" (x .+ y)--- 10.00:@Not:<Dollar .+ 20.00:@Hat:<Dollar .+ 20.00:@Not:<Yen .+ 10.00:@Hat:<Yen .| "A"+-- (10.00:@Not:<Dollar .+ 20.00:@Hat:<Dollar .+ 20.00:@Not:<Yen .+ 10.00:@Hat:<Yen) .| "A" gather :: (HatVal v, HatBaseClass b, Note n) => n -> Journal n v b -> Journal n v b gather n js = (toAlg js) .| n
src/ExchangeAlgebra/Journal/Transfer/Rule.hs view
@@ -17,8 +17,7 @@ module ExchangeAlgebra.Journal.Transfer.Rule ( -- * Additional entries- transferEntries- , carryEntries+ carryEntries -- * Complete results , carryBefore -- * Side totals@@ -36,8 +35,6 @@ , Redundant((.^)) ) import qualified ExchangeAlgebra.Algebra.Core as Algebra-import ExchangeAlgebra.Algebra.Transfer.Representation (TransferRules, TransferApplyError)-import qualified ExchangeAlgebra.Algebra.Transfer.Representation as Rule import ExchangeAlgebra.Algebra.Base.Representation (Hat(..), HatBaseClass(..)) import ExchangeAlgebra.Algebra.Value.Class (HatVal(..), isErrorValue) import qualified ExchangeAlgebra.Algebra.Value.Class as Value@@ -45,31 +42,12 @@ , Note , (.|) , toMap- , fromMap ) import qualified ExchangeAlgebra.Journal.Core as Journal import ExchangeAlgebra.Algebra.Posting (PostSide(..)) -- * Additional entries -{-# DEPRECATED transferEntries "Use transferEntriesBy of ExchangeAlgebra.Accounting.Transfer, which reads the exact balance per target note." #-}---- | Generate additional entries under the same notes as their sources.--- Each note is processed in the traversal order of 'toMap'. The first failure--- aborts the whole operation; no partial Journal is returned. This order is--- an implementation traversal, not a chronological ordering of notes.--- Input posting values must be valid and finite. No @bar@ is applied.-transferEntries :: (Note n, HatVal v, HatBaseClass b)- => TransferRules v b- -> Journal n v b- -> Either (TransferApplyError v b) (Journal n v b)-transferEntries rules journal = fromMap . Map.fromList- <$> traverse apply (Map.toList (toMap journal))- where- apply (note, algebra) = do- entries <- Rule.transferEntries rules algebra- pure (note, entries)- -- | Round selected complete-base nets once and attach the carry note. -- Each complete base's Not and Hat values are accumulated exactly with the -- 'HatVal' accumulator; the net is rounded once. Failures are reported as@@ -206,7 +184,7 @@ -- -- The selected net is accumulated exactly and rounded once per complete base, -- with the same 'CarryError' failures as 'carryEntries'. Structurally, 'carryEntries' resembles--- 'ExchangeAlgebra.Algebra.Transfer.Rule.collapseNetEntries': both generate+-- 'ExchangeAlgebra.Algebra.Transfer.collapseNetEntries': both generate -- reversals and moved nets. The latter uses @bar@ after rewriting and has a -- different numeric contract. Complexity: O(e log(k + 1)) for e selected -- scalars and k distinct selected complete bases, plus filtering and merge.
− src/ExchangeAlgebra/Posting.hs
@@ -1,8 +0,0 @@--- | Compatibility entry for checked postings. Import--- "ExchangeAlgebra.Algebra.Posting" for new code.-module ExchangeAlgebra.Posting {-# DEPRECATED "Use ExchangeAlgebra.Algebra.Posting instead." #-}- ( Posted, PostedError(..), posted, unPosted- , PostSide(..), sideHat, Posting, entry, postingAlg- ) where--import ExchangeAlgebra.Algebra.Posting
− src/ExchangeAlgebra/Render/Bookkeeping.hs
@@ -1,32 +0,0 @@-{- |- Module : ExchangeAlgebra.Render.Bookkeeping- Copyright : (c) Kaya Akagi. 2018-2026- Maintainer : yakagika@icloud.com-- Released under the OWL license-- Journals, account ledgers, trial balances, and closing worksheets.- These layouts and their file writers are re-exported from- "ExchangeAlgebra.IO.Output.Statements". For financial statements, use- "ExchangeAlgebra.Accounting.Statements.Presentation" followed by- 'ExchangeAlgebra.IO.Output.Statements.financialStatementRows'.--}--module ExchangeAlgebra.Render.Bookkeeping {-# DEPRECATED "Import ExchangeAlgebra.IO.Output.Statements instead." #-}- ( -- * Journal and ledgers- writeJournal- , journalRows- , writeAccountOf- , accountLedgerRows- , writeAccountOfJournal- , accountLedgerRowsJournal- -- * Trial balances and closing documents- , writeCompoundTrialBalance- , compoundTrialBalanceRows- , writeWorksheet- , worksheetRows- , writePostClosingTrialBalance- , postClosingTrialBalanceRows- ) where--import ExchangeAlgebra.IO.Output.Statements
− src/ExchangeAlgebra/Render/Csv.hs
@@ -1,26 +0,0 @@-{- |- Module : ExchangeAlgebra.Render.Csv- Copyright : (c) Kaya Akagi. 2018-2026- Maintainer : yakagika@icloud.com-- Released under the OWL license-- CSV serialization of text tables: 'writeCSV' (every cell quoted) and- 'csvTranspose' (transpose with blank padding). Both names are- re-exported unchanged from "ExchangeAlgebra.IO.Output.Csv"; this module only- separates the file format from the bookkeeping layouts- ("ExchangeAlgebra.Render.Bookkeeping") and the simulation dumps- ("ExchangeAlgebra.Simulation.Output").-- >>> import qualified Data.Text as T- >>> csvTranspose [[T.pack "a", T.pack "b"], [T.pack "c"]]- [["a","c"],["b",""]]--}--module ExchangeAlgebra.Render.Csv {-# DEPRECATED "Import ExchangeAlgebra.IO.Output.Csv instead." #-}- ( writeCSV- , csvTranspose- ) where---import ExchangeAlgebra.IO.Output.Csv (writeCSV, csvTranspose)
src/ExchangeAlgebra/Render/Simulation.hs view
@@ -3,7 +3,7 @@ Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license Compatibility entry point for simulation CSV output. The CSV functions live in "ExchangeAlgebra.Simulation.Output".
− src/ExchangeAlgebra/Reporting/Group.hs
@@ -1,23 +0,0 @@--- | Compatibility exports for statement presentation groups.-module ExchangeAlgebra.Reporting.Group-{-# DEPRECATED "Import ExchangeAlgebra.Accounting.Statements.Group instead." #-}- ( -- * Groups- PresentationGroup(..)- , PresentationGroupDef(..)- , defaultPresentationGrouping- , presentationGroupOf- , lookupGroupDef- , groupNormalSide- , groupingForDivisions- -- * Amounts- , RelativeAmount(..)- , relativeTo- , addGross- -- * Grouped rows- , GroupRowKind(..)- , GroupRow(..)- , GroupedPresentation(..)- , presentGroups- ) where--import ExchangeAlgebra.Accounting.Statements.Group
− src/ExchangeAlgebra/Reporting/Metric.hs
@@ -1,16 +0,0 @@--- | Compatibility exports for reporting metrics.-module ExchangeAlgebra.Reporting.Metric-{-# DEPRECATED "Import ExchangeAlgebra.Accounting.Statements.Metric instead." #-}- ( MetricId- , mkMetricId- , metricIdText- , DerivedMetric(..)- , PeriodResult(..)- , MetricError(..)- , metricForLegacyTitle- , legacyTitlesForMetric- , periodResultOfAlg- , periodResultOf- ) where--import ExchangeAlgebra.Accounting.Statements.Metric
− src/ExchangeAlgebra/Reporting/Presentation.hs
@@ -1,28 +0,0 @@--- | Compatibility exports for financial statement presentation.-module ExchangeAlgebra.Reporting.Presentation-{-# DEPRECATED "Import ExchangeAlgebra.Accounting.Statements.Presentation instead." #-}- ( AccountingFramework(..)- , ReportingScope(..)- , PresentationProfile(..)- , StatementSection(..)- , StatementLine(..)- , PresentationAllocation(..)- , PresentationRelabel(..)- , MaterialityTreatment(..)- , MaterialityDecision(..)- , ContraPresentationRule(..)- , CustomMetricLabel(..)- , SubtotalCoverage(..)- , SubtotalDefinition(..)- , StatementSubtotal(..)- , ReportingContext(..)- , jcciSecondGradeContext- , PresentationAuditEvent(..)- , PresentationIssue(..)- , FinancialStatements(..)- , presentationLabel- , metricLabel- , present- ) where--import ExchangeAlgebra.Accounting.Statements.Presentation
src/ExchangeAlgebra/Simulate.hs view
@@ -3,7 +3,7 @@ Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license State-space framework for Exchange-Algebra-based simulation: 'StateSpace', 'Updatable', 'runSimulation', ripple-effect utilities@@ -46,14 +46,14 @@ == Planned removal - Version 0.7 is planned to move simulation into the separate+ Version 0.8 is planned to move simulation into the separate @exchangealgebra-simulation@ package and to remove this module, together with "ExchangeAlgebra.Simulate.Engine", "ExchangeAlgebra.Simulate.Random", "ExchangeAlgebra.Simulate.Lite", and "ExchangeAlgebra.Simulate.Policy", without a compatibility module. The model evaluator in that package is the successor. The modules under @ExchangeAlgebra.Simulation@ (networks, analysis, optimization, output) and "ExchangeAlgebra.Simulate.Spill" are- planned to move to that package. 0.6 emits no deprecation warning because+ planned to move to that package. 0.6 and 0.7 emit no deprecation warning because that package has not been released. -}
src/ExchangeAlgebra/Simulate/Analysis.hs view
@@ -3,7 +3,7 @@ Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license Compatibility entry point for matrix analysis. Import "ExchangeAlgebra.Simulation.Analysis" for new code.
src/ExchangeAlgebra/Simulate/Engine.hs view
@@ -3,7 +3,7 @@ Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license The state-space engine of "ExchangeAlgebra.Simulate" on its own: terms ('StateTime'), the per-variable update protocol ('Updatable',@@ -20,9 +20,9 @@ in "ExchangeAlgebra.Simulation.Analysis" and the random helpers in "ExchangeAlgebra.Simulate.Random". - /Note:/ version 0.7 is planned to remove this module without a+ /Note:/ version 0.8 is planned to remove this module without a compatibility module. Its successor is the model evaluator in the- separate @exchangealgebra-simulation@ package. 0.6 emits no deprecation+ separate @exchangealgebra-simulation@ package. 0.6 and 0.7 emit no deprecation warning because that package has not been released. -}
src/ExchangeAlgebra/Simulate/Lite.hs view
@@ -19,7 +19,7 @@ Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license == What this module is @@ -111,9 +111,9 @@ applied by 'runLiteWithPolicy'. Snapshot-dependent term-boundary recomputation and parallel speedup measurement remain out of scope. - /Note:/ version 0.7 is planned to remove this module without a+ /Note:/ version 0.8 is planned to remove this module without a compatibility module. Its successor is the model evaluator in the- separate @exchangealgebra-simulation@ package. 0.6 emits no deprecation+ separate @exchangealgebra-simulation@ package. 0.6 and 0.7 emit no deprecation warning because that package has not been released. -} @@ -191,7 +191,7 @@ import ExchangeAlgebra.Simulate.Policy ( LedgerPolicy(..) , Retention(..) , Compaction(..)- , HasTermAxis(..) )+ , HasNotePeriod(..) ) ------------------------------------------------------------------ -- * Term-boundary field rules@@ -652,7 +652,7 @@ -- This is norm- and balance-preserving; only the within-term posting -- sequence is collapsed. The in-progress term is never touched. -- 2. __retention / spill__ — if @'retain' = 'RetainRecent' w@, terms with--- @'termOf' n '<=' t - w@ are evicted from the in-memory ledger. If+-- @'periodOf' n '<=' t - w@ are evicted from the in-memory ledger. If -- @'spillTo' = 'Just' path@, each newly-closed-and-evicted term is first -- appended to that binary file (compatible with 'defaultBinarySpillWriter', -- so 'ExchangeAlgebra.Simulate.Policy.restoreLedger' can read it back).@@ -669,7 +669,7 @@ :: forall w t n v b r. ( forall s. LiteWorld w s , HatVal v, HatBaseClass b- , HasTermAxis n, TermOf n ~ t+ , HasNotePeriod n, PeriodOf n ~ t , StateTime t , Binary.Binary t, Binary.Binary (Journal n v b) ) => LedgerPolicy@@ -694,7 +694,7 @@ :: forall w t n v b r. ( forall s. LiteWorld w s , HatVal v, HatBaseClass b- , HasTermAxis n, TermOf n ~ t+ , HasNotePeriod n, PeriodOf n ~ t , StateTime t , Binary.Binary t, Binary.Binary (Journal n v b) ) => (t -> w SnapT -> IO ())@@ -711,7 +711,7 @@ :: forall w t n v b r. ( forall s. LiteWorld w s , HatVal v, HatBaseClass b- , HasTermAxis n, TermOf n ~ t+ , HasNotePeriod n, PeriodOf n ~ t , StateTime t , Binary.Binary t, Binary.Binary (Journal n v b) ) => Maybe (t -> w SnapT -> IO ())@@ -777,7 +777,7 @@ ledger <- stToIO (readSTRef (specLedger spec wr)) let lo = firstUnspilled spilledHi chunk = filterWithNote- (\nn _ -> let tt = termOf nn+ (\nn _ -> let tt = periodOf nn in tt >= lo && tt <= boundary) ledger -- Suppress empty spill chunks: at early term boundaries the@@ -790,7 +790,7 @@ defaultBinarySpillWriter h (lo, boundary) chunk -- delete evicted terms from memory (whether or not spilled) stToIO $ modifySTRef' (specLedger spec wr)- (filterWithNote (\nn _ -> termOf nn > boundary))+ (filterWithNote (\nn _ -> periodOf nn > boundary)) writeIORef spilledRef (Just boundary) final <- stToIO (gFreezeR wr) pure (k final)@@ -820,9 +820,9 @@ -- before @t@ (a /closed/ term), leaving the in-progress term untouched. Uses -- 'toMap'\/'fromMap' so the traversal order does not affect the result. compressClosedTerms- :: (HasTermAxis n, TermOf n ~ t, Ord t, HatVal v, HatBaseClass b)+ :: (HasNotePeriod n, PeriodOf n ~ t, Ord t, HatVal v, HatBaseClass b) => t -> Journal n v b -> Journal n v b compressClosedTerms t j = fromMap (HM.mapWithKey- (\nn alg -> if termOf nn < t then EA.compress alg else alg)+ (\nn alg -> if periodOf nn < t then EA.compress alg else alg) (toMap j))
src/ExchangeAlgebra/Simulate/Policy.hs view
@@ -10,7 +10,7 @@ Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license == What this module is @@ -18,9 +18,9 @@ the point a ledger is built — how a long simulation should manage the size of its audit trail. Instead of hand-wiring t'ExchangeAlgebra.Simulate.Spill.SpillOptions'- (seven fields plus 'filterWithNote' calls for term extraction and eviction),+ (seven fields plus 'filterWithNote' calls for period extraction and eviction), the user declares a t'LedgerPolicy' and lets the plumbing be /derived from the- Note's term component/.+ note period/. A policy answers three orthogonal questions: @@ -78,17 +78,17 @@ signatures of the existing spill API; it is a thin declarative front-end over it. - == The term component+ == The note period - A policy needs to know /which term/ a 'Note' belongs to. Because a tuple+ A policy uses the period of each 'Note'. Because a tuple Note carries no intrinsic notion of "which component is the period", the- convention is fixed by the 'HasTermAxis' class: __the last component of the- Note is the term__. The library ships instances for @(e, t)@ and+ 'HasNotePeriod' instances for tuples use the last field as the period.+ The library provides instances for @(e, t)@ and @(e1, e2, t)@; a bespoke Note needs a one-line instance. - /Note:/ version 0.7 is planned to remove this module without a+ /Note:/ version 0.8 is planned to remove this module without a compatibility module. Its successor is the model evaluator in the- separate @exchangealgebra-simulation@ package. 0.6 emits no deprecation+ separate @exchangealgebra-simulation@ package. 0.6 and 0.7 emit no deprecation warning because that package has not been released. -} @@ -98,8 +98,8 @@ , Compaction(..) , LedgerPolicy(..) , defaultLedgerPolicy- -- * Term component convention- , HasTermAxis(..)+ -- * Note period+ , HasNotePeriod(..) -- * Bridges to the classic spill engine , policySpillOptions , restoreLedger@@ -112,7 +112,7 @@ , HatVal , HatBaseClass , filterWithNote )-import ExchangeAlgebra.Journal.Core (HasTermAxis(..))+import ExchangeAlgebra.Journal.Core (HasNotePeriod(..)) import ExchangeAlgebra.Simulate (StateTime) import ExchangeAlgebra.Simulate.Spill ( SpillOptions(..) , SpillDeletePolicy(..)@@ -176,10 +176,10 @@ } --------------------------------------------------------------------- * Term component convention+-- * Note period ------------------------------------------------------------------ --- 'HasTermAxis' and 'TermOf' are defined in "ExchangeAlgebra.Journal.Core"+-- 'HasNotePeriod' and 'PeriodOf' are defined in "ExchangeAlgebra.Journal.Core" -- and re-exported here, so the 0.5.x import path keeps working. ------------------------------------------------------------------@@ -189,7 +189,7 @@ -- | Build a binary t'ExchangeAlgebra.Simulate.SpillOptions' for the classic -- @runSimulationWithSpill@ from -- a t'LedgerPolicy', deriving the per-chunk extraction and the eviction range--- from the Note's term component ('termOf'). This replaces the ~20 lines of+-- from the note period ('periodOf'). This replaces the ~20 lines of -- hand-written 'filterWithNote' plumbing (cf. @fixedPriceIOSpill@) with a single call. -- -- The caller supplies @spillEvery@ (the chunk size in terms) and two accessors@@ -209,7 +209,7 @@ -- the policy vocabulary onto t'SpillOptions' (design-review C4). policySpillOptions :: forall n v b t a.- ( HasTermAxis n, TermOf n ~ t, StateTime t+ ( HasNotePeriod n, PeriodOf n ~ t, StateTime t , HatVal v, HatBaseClass b , Binary.Binary t, Binary.Binary (Journal n v b) ) => LedgerPolicy@@ -226,7 +226,7 @@ , spillExtractChunk = Just $ \(chunkStart, chunkEnd) world -> do ledger <- readLedger world pure $ filterWithNote- (\n _ -> let t = termOf n+ (\n _ -> let t = periodOf n in t >= chunkStart && t <= chunkEnd) ledger , spillWriteChunk = defaultBinarySpillWriter@@ -235,7 +235,7 @@ RetainRecent w -> KeepRecentTerms w , spillDeleteRange = \(_, deleteEnd) world -> modifyLedger- (filterWithNote (\n _ -> termOf n > deleteEnd))+ (filterWithNote (\n _ -> periodOf n > deleteEnd)) world } @@ -250,11 +250,11 @@ -- with an exact value type such as @MoneyDecimal@). With @'spillTo' = 'Nothing'@ -- there is nothing to restore — the evicted terms are gone. restoreLedger- :: ( HasTermAxis n, TermOf n ~ t, Ord t, Enum t, Show t+ :: ( HasNotePeriod n, PeriodOf n ~ t, Ord t, Enum t, Show t , HatVal v, HatBaseClass b , Binary.Binary t, Binary.Binary (Journal n v b) ) => FilePath -- ^ binary spill file written under the policy -> Journal n v b -- ^ in-memory remainder (recent terms) -> IO (Journal n v b) restoreLedger path remainder =- restoreJournalFromBinarySpill path termOf remainder+ restoreJournalFromBinarySpill path periodOf remainder
src/ExchangeAlgebra/Simulate/Random.hs view
@@ -3,7 +3,7 @@ Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license Random-number helpers used by simulations: Box-Muller normal variates ('normal', 'normal'') and generator advancement ('updateGen'). All three@@ -15,9 +15,9 @@ >>> fst (normal' (5, 0) (mkStdGen 1)) :: Double 5.0 - /Note:/ version 0.7 is planned to remove this module without a+ /Note:/ version 0.8 is planned to remove this module without a compatibility module. Its successor is the model evaluator in the- separate @exchangealgebra-simulation@ package. 0.6 emits no deprecation+ separate @exchangealgebra-simulation@ package. 0.6 and 0.7 emit no deprecation warning because that package has not been released. -}
src/ExchangeAlgebra/Simulate/Spill.hs view
@@ -7,9 +7,9 @@ Maintainer : yakagika@icloud.com Description : Spill-to-disk codec and restore for long simulations: chunk writers, checked readers, and ledger restoration. Shared by the classic engine ("ExchangeAlgebra.Simulate"), the Lite runner and the ledger policy layer; depends only on Algebra and Journal. - Released under the OWL license+ Released under the MIT license - /Note:/ version 0.7 is planned to move this module to the separate+ /Note:/ version 0.8 is planned to move this module to the separate @exchangealgebra-simulation@ package. -}
src/ExchangeAlgebra/Simulate/Visualize.hs view
@@ -6,7 +6,7 @@ Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license Package for Exchange Algebra defined by Hiroshi Deguchi. @@ -17,7 +17,7 @@ <https://repository.kulib.kyoto-u.ac.jp/dspace/bitstream/2433/82987/1/0809-7.pdf> - /Note:/ version 0.7 decides whether this module moves to the separate+ /Note:/ version 0.8 decides whether this module moves to the separate @exchangealgebra-simulation@ package behind Chart or is removed. -}
src/ExchangeAlgebra/Simulation/Analysis.hs view
@@ -6,7 +6,7 @@ Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license Matrix analysis for ripple effects. Import this module to compute a Leontief inverse or extract the response to one industry's demand.
src/ExchangeAlgebra/Simulation/Network/Csv.hs view
@@ -19,7 +19,7 @@ -- lines whose first non-space character is @#@ are skipped, surrounding -- whitespace on each field is trimmed. The first non-skipped line must be the -- header. Avoids a @cassava@ dependency for these fixed schemas. Line splitting--- is shared with "ExchangeAlgebra.Convert.Csv" through 'splitTrim'.+-- is shared with "ExchangeAlgebra.IO.Input.Csv" through 'splitTrim'. -- | Parse an edge CSV with header @from,to@ into @(from, to)@ pairs. --
src/ExchangeAlgebra/Simulation/Network/Representation.hs view
@@ -10,13 +10,17 @@ module ExchangeAlgebra.Simulation.Network.Representation where import Control.DeepSeq (NFData (..))-import Data.List (foldl', sortBy)+import Control.Monad (forM_)+import Control.Monad.ST (ST, runST)+import Data.Bits ((.&.), countLeadingZeros, finiteBitSize, shiftL, shiftR)+import Data.List (foldl', insert, sortBy) import qualified Data.Map.Strict as M import Data.Map.Strict (Map) import Data.Maybe (fromMaybe) import qualified Data.Set as S import Data.Set (Set) import qualified Data.Vector as V+import qualified Data.Vector.Unboxed.Mutable as MV import System.Random (StdGen, mkStdGen, randomR) import ExchangeAlgebra.Algebra.Value.Class (HatVal(..), isErrorValue) import qualified ExchangeAlgebra.Algebra.Value.Class as EJ@@ -282,21 +286,37 @@ -- (sampling without replacement, excluding itself). Deterministic in the given -- 'StdGen'. --+-- Keys must satisfy the 'Eq' and 'Ord' laws.+-- Sampling takes @O(N d^2)@ time for @d = min k (N-1)@ when @d > 0@.+-- -- >>> let g = kRegular (mkStdGen 1) [1..6] 2 :: TradeNetwork Int -- >>> all (\j -> length (suppliersOf g j) == 2) (nodes g) -- True kRegular :: Ord k => StdGen -> [k] -> Int -> TradeNetwork k kRegular gen ks k =- buildNetwork nodeSet (concat (snd (foldl' pick (gen, []) xs)))+ buildNetwork nodeSet builtEdges where nodeSet = S.fromList ks xs = S.toAscList nodeSet- deg = max 0 (min k (length xs - 1))- pick (g0, acc) j =- let candidates = filter (/= j) xs- (chosen, g1) = sampleWithout g0 deg candidates- in (g1, [ (i, j) | i <- chosen ] : acc)+ keys = V.fromList xs+ count = V.length keys - 1+ deg = max 0 (min k count)+ builtEdges+ | deg == 0 = []+ | otherwise = snd (V.ifoldl' pick (gen, []) keys) + pick (!g0, acc) buyerIndex buyer =+ let (chosen, g1) = sampleRegularRanks g0 deg count+ !nextEdges = foldl' addEdge acc chosen+ in (g1, nextEdges)+ where+ addEdge es rank =+ (keys V.! supplierIndex, buyer) : es+ where+ supplierIndex+ | rank < buyerIndex = rank+ | otherwise = rank + 1+ -- | An Erdős–Rényi @G(n, p)@ directed network: each ordered pair @(i, j)@, -- @i /= j@, becomes an edge independently with probability @p@. @p <= 0@ yields -- the empty network, @p >= 1@ yields 'completeNetwork'. Deterministic in the@@ -331,6 +351,10 @@ -- @C(m+1, 2)·1 + (N - m - 1)·m@ counting the directed buyer→supplier edges as -- one per attachment; the property test checks the exact value. --+-- Keys must satisfy the 'Eq' and 'Ord' laws.+-- Sampling and weight updates take @O(N m log N)@ time with @m@ clamped to at least 1.+-- Weighted draws assume the total weight stays below @2^53@.+-- -- >>> let g = scaleFree (mkStdGen 7) [1..10] 2 :: TradeNetwork Int -- >>> edgeCount g -- 17@@ -340,37 +364,56 @@ where nodeSet = S.fromList ks xs = S.toAscList nodeSet+ keys = V.fromList xs+ n = V.length keys m = max 1 m0- -- State threads the generator, the edge accumulator and an incremental- -- degree table (@node ↦ current degree@). The degree table replaces the- -- O(E) rescan that the naive @degree i = length (filter …) acc@ performed- -- for every candidate at every node: each added edge bumps both endpoints'- -- degrees in O(log N), so the per-node weight list is built without ever- -- touching @acc@. The weights produced are bit-for-bit identical to the- -- rescan version, so the generated network is unchanged.- (_, builtEdges0, _) = foldl' addNode (gen, [], M.empty) (zip [0 ..] xs)- builtEdges = reverse builtEdges0+ firstStride = 1 `shiftL` max 0 (finiteBitSize n - countLeadingZeros n - 1) - -- addNode :: (StdGen, [(k,k)], Map k Int)- -- -> (Int, k) -> (StdGen, [(k,k)], Map k Int)- addNode st@(g0, acc, deg) (ix, j)- | ix == 0 = st -- first node: nothing to attach to- | ix <= m = -- seed phase: attach to all earlier nodes- let suppliers = take ix xs- newEdges = [ (i, j) | i <- suppliers ]- in (g0, newEdges ++ acc, bumpEdges newEdges deg)- | otherwise = -- preferential attachment- let present = take ix xs -- nodes already added- degree i = M.findWithDefault 0 i deg- weighted = [ (i, fromIntegral (1 + degree i) :: Double) | i <- present ]- (chosen, g1) = sampleWeightedWithout g0 m weighted- newEdges = [ (i, j) | i <- chosen ]- in (g1, newEdges ++ acc, bumpEdges newEdges deg)+ builtEdges = runST $ do+ weights <- MV.replicate n 0+ tree <- MV.replicate (n + 1) 0 - -- Increment both endpoints' degree counts for each newly added edge.- bumpEdges es d = foldl' (\d' (i, t) -> bump i (bump t d')) d es- bump k = M.insertWith (+) k 1+ let changeWeight i delta = do+ MV.modify weights (+ delta) i+ addFenwickWeight tree i delta + drawSuppliers !g 0 _ chosen = pure (g, chosen)+ drawSuppliers !g remaining total chosen = do+ let (u, g1) = randomR (0, fromIntegral total) g :: (Double, StdGen)+ -- A draw of zero selects the first positive weight.+ target+ | u <= 0 = 1+ | otherwise = u+ i <- fenwickLowerBound tree firstStride target+ weight <- MV.read weights i+ changeWeight i (negate weight)+ drawSuppliers g1 (remaining - 1) (total - weight) ((i, weight) : chosen)++ chooseSuppliers ix degree g total+ | ix <= m = do+ let earlier = [0 .. ix - 1]+ forM_ earlier (\i -> changeWeight i 1)+ pure (g, earlier)+ | otherwise = do+ (nextGen, chosen) <- drawSuppliers g degree total []+ -- Restore each removed weight and include the new edge.+ forM_ chosen (\(i, weight) -> changeWeight i (weight + 1))+ pure (nextGen, map fst chosen)++ addNode ix g total !acc+ | ix == n = pure acc+ | otherwise = do+ let degree = min ix m+ (g1, suppliers) <- chooseSuppliers ix degree g total+ changeWeight ix (degree + 1)+ let !buyer = keys V.! ix+ nextEdges = foldl' (\es i -> (keys V.! i, buyer) : es) acc suppliers+ -- Every edge adds weight at both ends, and each new node adds one.+ !nextTotal = total + 2 * degree + 1+ addNode (ix + 1) g1 nextTotal nextEdges++ addNode 0 gen 0 []+ -- | A stochastic block network: each node carries a sector label, and an -- ordered pair @(i, j)@ (@i /= j@) becomes an edge with probability -- @p (sector i, sector j)@. Deterministic in the given 'StdGen'. Generalizes@@ -804,45 +847,49 @@ -- * Internal sampling helpers ------------------------------------------------------------------ --- | Uniform sampling without replacement of @n@ elements from a list,--- deterministic in the 'StdGen'. Returns the chosen elements (in the order they--- were drawn) and the advanced generator. If @n >= length xs@ the whole list is--- returned.-sampleWithout :: StdGen -> Int -> [a] -> ([a], StdGen)-sampleWithout g0 n xs0 = go g0 (max 0 n) xs0 []+-- Translate each rank in the remaining candidates back to its original rank+-- by skipping the removed ranks in ascending order.+sampleRegularRanks :: StdGen -> Int -> Int -> ([Int], StdGen)+sampleRegularRanks gen draws size = go gen draws size [] [] where- go g _ [] acc = (reverse acc, g)- go g k xs acc- | k <= 0 = (reverse acc, g)- | otherwise =- let (ix, g1) = randomR (0, length xs - 1) g- (chosen, rest) = pick ix xs- in go g1 (k - 1) rest (chosen : acc)- pick i ys = case splitAt i ys of- (pre, y : post) -> (y, pre ++ post)- (pre, []) -> (last pre, init pre) -- unreachable (ix in range)+ go !g 0 _ _ chosen = (chosen, g)+ go !g remaining len removed chosen =+ let (rank, nextGen) = randomR (0, len - 1) g+ !originalRank = foldl' skipRemoved rank removed+ in go nextGen (remaining - 1) (len - 1)+ (insert originalRank removed) (originalRank : chosen) --- | Weighted sampling without replacement: pick @n@ elements, each draw--- proportional to its weight, deterministic in the 'StdGen'.-sampleWeightedWithout :: StdGen -> Int -> [(a, Double)] -> ([a], StdGen)-sampleWeightedWithout g0 n xs0 = go g0 (max 0 n) xs0 []+ skipRemoved rank removedRank+ | removedRank <= rank = rank + 1+ | otherwise = rank++-- The Fenwick tree stores partial sums in slots 1 through N.+addFenwickWeight :: MV.MVector s Int -> Int -> Int -> ST s ()+addFenwickWeight tree index delta = go (index + 1) where- go g _ [] acc = (reverse acc, g)- go g k ws acc- | k <= 0 = (reverse acc, g)- | otherwise =- let total = sum (map snd ws)- (u, g1) = randomR (0, total) g :: (Double, StdGen)- (chosen, rest) = drawAt u ws- in go g1 (k - 1) rest (chosen : acc)- drawAt u ws = walk u ws []+ go i+ | i >= MV.length tree = pure ()+ | otherwise = do+ MV.modify tree (+ delta) i+ go (i + (i .&. negate i))++-- Find the longest prefix whose sum is strictly below the positive target.+-- Its length is the zero-based index of the selected supplier.+fenwickLowerBound :: MV.MVector s Int -> Int -> Double -> ST s Int+fenwickLowerBound tree firstStride target = go 0 0 firstStride+ where+ go i _ 0 = pure i+ go i prefix stride+ | candidate >= MV.length tree = go i prefix nextStride+ | otherwise = do+ partial <- MV.read tree candidate+ advance (prefix + partial) where- walk _ [] seen = case reverse seen of- ((a, _) : _) -> (a, []) -- exhausted (shouldn't happen)- [] -> error "sampleWeightedWithout: empty"- walk acc ((a, w) : rest) seen- | acc <= w = (a, reverse seen ++ rest)- | otherwise = walk (acc - w) rest ((a, w) : seen)+ candidate = i + stride+ nextStride = stride `shiftR` 1+ advance candidateSum+ | fromIntegral candidateSum < target = go candidate candidateSum nextStride+ | otherwise = go i prefix nextStride ------------------------------------------------------------------ -- * Small utilities
src/ExchangeAlgebra/Simulation/Output.hs view
@@ -3,7 +3,7 @@ Copyright : (c) Kaya Akagi. 2018-2026 Maintainer : yakagika@icloud.com - Released under the OWL license+ Released under the MIT license CSV output of simulation results. Import this module to stream function results as time-series CSV without requiring Chart.
− src/ExchangeAlgebra/TrialBalance/Balance.hs
@@ -1,15 +0,0 @@--- | Compatibility exports for trial balance construction.-module ExchangeAlgebra.TrialBalance.Balance-{-# DEPRECATED "Import ExchangeAlgebra.Accounting.TrialBalance.Balance instead." #-}- ( AccountBalance(..)- , balancePair- , addPair- , netPair- , combineBalances- , balanceFor- , balanceSide- , balanceAmount- , accountBalances- ) where--import ExchangeAlgebra.Accounting.TrialBalance.Balance
− src/ExchangeAlgebra/TrialBalance/Validation.hs
@@ -1,12 +0,0 @@--- | Compatibility exports for trial balance validation.-module ExchangeAlgebra.TrialBalance.Validation-{-# DEPRECATED "Import ExchangeAlgebra.Accounting.TrialBalance.Validation instead." #-}- ( TrialBalanceStage(..)- , AccountBalance(..)- , ReclassificationRule(..)- , TrialBalanceInput(..)- , TBFinding(..)- , trialBalanceFindings- ) where--import ExchangeAlgebra.Accounting.TrialBalance.Validation
− src/ExchangeAlgebra/Value.hs
@@ -1,74 +0,0 @@-{-# LANGUAGE GeneralizedNewtypeDeriving #-}-{-# LANGUAGE DerivingStrategies #-}--{- |- Module : ExchangeAlgebra.Value- Copyright : (c) Kaya Akagi. 2018-2026- Maintainer : yakagika@icloud.com-- Released under the OWL license-- Exact, non-negative decimal value type t'MoneyDecimal' for use as the @v@- parameter of @Alg v b@ / @Journal n v b@.-- == Why this exists (DESIGN, 2026-06-06)-- The accounting value type is selectable:-- * @Double@ — fast IEEE-754; the default. Addition is /non-associative/,- so the order in which same-base postings are summed (which depends on how a- value was /constructed/) can change @norm@ / @bar@ results. In the- agent-based simulations this manifested as a ~3% swing in a stock value when- the construction order changed (see plans/in-progress/LAZY_EVAL_AUDIT.md and- FP_SUMMATION_SURVEY.md). This is acceptable for relative-price ABM work where- speed matters, but it is not deterministic/auditable.-- * @MoneyDecimal@ — exact base-10 fixed-point (a non-negative 'Data.Decimal').- Addition is /exact and associative/, so results are independent of- construction order: the fromList fold direction, parallel merges, etc. no- longer change the answer. This is the right choice for audited ledgers and- for making the construction-order optimizations (fromList O(N)) safe.-- @Integer@ (minimal-currency-unit) is intentionally NOT offered: ABM simulations- use relative prices with base unit 1 and sub-unit fractional prices, which an- integer cannot represent.-- == Ergonomics-- Numeric literals work without wrapping, because 'Num'/'Fractional' are derived:-- > import ExchangeAlgebra.Algebra- > import ExchangeAlgebra.Algebra.Value (MoneyDecimal)- >- > entry :: Alg MoneyDecimal (HatBase CountUnit)- > entry = 10.5 .@ Hat :< Amount .+ 2 .@ Not :< Yen-- == Rounding-- The core algebra only adds/subtracts, which is exact for t'MoneyDecimal' and needs no- rounding. Rounding is only needed by /multiplication and division/ (tax ratios,- proration, scalar multiplication) at the point a monetary amount is /finalized/. Use- 'bankersRound': it rounds half-to-even (the unbiased financial default; also GHC's- 'Prelude.round' and IEEE-754's default mode). A ceiling variant ('ceilingRound') is- provided for jurisdictions whose- rules differ. There is no single correct rule (e.g. Japanese consumption tax rounding- varies by company), so the rounding function is explicit and swappable.--}-module ExchangeAlgebra.Value {-# DEPRECATED "Use ExchangeAlgebra.Algebra.Value instead." #-} - ( MoneyDecimal(..)- , toDecimal- , bankersRound- , ceilingRound- , MoneyParseError(..)- , moneyDecimalFromText- , moneyDecimalFromScientific- , MoneyDouble(..)- , toDouble- ) where--import ExchangeAlgebra.Algebra.Value- ( MoneyDecimal(..), toDecimal, bankersRound, ceilingRound- , MoneyParseError(..), moneyDecimalFromText, moneyDecimalFromScientific- , MoneyDouble(..), toDouble )--- Preserve the existing Hashable Day and TimeOfDay instance visibility.-import ExchangeAlgebra.Algebra.Element.Representation ()
+ test/Accounting/AuditSpec.hs view
@@ -0,0 +1,172 @@+{-# LANGUAGE PatternSynonyms #-}++-- | Audit laws for structure priority, empty inputs, exclusions, and severity.+-- Results and duplicate-group sizes are compared exactly; no Alg equality is used.+module Accounting.AuditSpec (runTests) where++import Control.Monad (forM_)+import qualified Data.HashMap.Strict as HM+import Data.List (sort)+import Data.List.NonEmpty (NonEmpty(..))+import qualified Data.List.NonEmpty as NE+import ExchangeAlgebra.Accounting.Account (AccountTitles(..))+import ExchangeAlgebra.Accounting.Audit+import ExchangeAlgebra.Accounting.TrialBalance.Balance (TrialBalance)+import ExchangeAlgebra.Algebra.Base (Hat(..), HatBase(..))+import ExchangeAlgebra.Algebra.Core (Redundant(..), (.@))+import ExchangeAlgebra.Algebra.Internal (Alg(Single))+import qualified ExchangeAlgebra.Journal.Core as J+import Support (assertEqual)++-- | A structure error must contain only structure findings, never accounting findings.+isStructureError :: AuditResult s f -> Bool+isStructureError (Error findings) = all isStructure (NE.toList findings)+ where+ isStructure :: Finding s f -> Bool+ isStructure (StructureFinding _) = True+ isStructure (AccountingFinding _) = False+isStructureError _ = False++-- | Observe severity without requiring the different finding types to coincide.+resultKind :: AuditResult s f -> String+resultKind NoProblem = "none"+resultKind (Warning _) = "warning"+resultKind (Error _) = "error"++-- | Observe the number and sizes of duplicate groups, independently of note names.+duplicateGroupSizes :: J.Journal Int Double (HatBase AccountTitles) -> Either String [Int]+duplicateGroupSizes journal = case duplicateTransactions journal of+ NoProblem -> Right []+ Warning findings -> Right $ sort+ [1 + NE.length rest | DuplicateTransactions _ rest <- NE.toList findings]+ Error findings -> Left (show findings)++-- | Check laws (a)-(f) on explicit inputs and all concrete account/side combinations.+runTests :: IO ()+runTests = do+ putStrLn "Accounting.AuditSpec: laws (a)-(f)"++ -- (a) Each defect blocks all six audits, before any side-dependent readout.+ -- Invalid fixtures use Single because (.@) rejects invalid values and HatNot.+ let malformed :: [(String, TrialBalance Double)]+ malformed =+ [ ("invalid value", Single (1 / 0) (Not :< Cash))+ , ("wildcard account", 1 .@ Not :< AccountTitle)+ , ("wildcard side", Single 1 (HatNot :< Cash))+ , ("three defects", Single (1 / 0) (HatNot :< AccountTitle))+ ]+ forM_ malformed $ \(label, input) -> do+ let journal :: J.Journal Int Double (HatBase AccountTitles)+ journal = input J..| 1+ assertEqual ("structure priority: " ++ label) (replicate 6 True)+ [ isStructureError (impossibleBalances input)+ , isStructureError (abnormalBalances input)+ , isStructureError (temporaryAccountBalances input)+ , isStructureError (closingResiduals input)+ , isStructureError (duplicateTransactions journal)+ , isStructureError (contraryNominalPostings journal)+ ]+ assertEqual "all defects of one posting, in kind order"+ (Error (StructureFinding (InvalidValue (1 / 0) (HatNot :< AccountTitle)) :|+ [ StructureFinding (WildcardAccount (HatNot :< AccountTitle))+ , StructureFinding (WildcardSide (HatNot :< AccountTitle))+ ]))+ (impossibleBalances (Single (1 / 0) (HatNot :< AccountTitle) :: TrialBalance Double))+ let repeated :: TrialBalance Double+ repeated = 1 .@ Not :< AccountTitle .+ 2 .@ Not :< AccountTitle+ repeatedIssues :: NonEmpty (TrialBalanceIssue Double)+ repeatedIssues = WildcardAccount (Not :< AccountTitle) :|+ [WildcardAccount (Not :< AccountTitle)]+ assertEqual "structure findings retain each posting"+ (Error (fmap StructureFinding repeatedIssues)) (closingResiduals repeated)++ -- (b) The additive zero has no findings for any audit.+ let emptyTrial :: TrialBalance Double+ emptyTrial = mempty+ emptyJournal :: J.Journal Int Double (HatBase AccountTitles)+ emptyJournal = J.Zero+ assertEqual "empty inputs" (replicate 6 "none")+ [ resultKind (impossibleBalances emptyTrial)+ , resultKind (abnormalBalances emptyTrial)+ , resultKind (temporaryAccountBalances emptyTrial)+ , resultKind (closingResiduals emptyTrial)+ , resultKind (duplicateTransactions emptyJournal)+ , resultKind (contraryNominalPostings emptyJournal)+ ]++ -- (c) Both directions of each B1 account are outside B2's domain.+ forM_ [Cash, PettyCash, CapitalStock, AccumulatedDepreciation] $ \title ->+ forM_ [Not, Hat] $ \side -> do+ let input :: TrialBalance Double+ input = 10 .@ side :< title+ assertEqual ("B1 excluded from B2: " ++ show (title, side))+ NoProblem (abnormalBalances input)++ -- (d) Injective renaming preserves the duplicate partition, including a+ -- reversed name order, two different group sizes, and an ungrouped note.+ let rent :: TrialBalance Double+ rent = 10 .@ Not :< RentExpense .+ 10 .@ Hat :< Cash+ sale :: TrialBalance Double+ sale = 20 .@ Not :< Cash .+ 20 .@ Not :< Sales+ journal :: J.Journal Int Double (HatBase AccountTitles)+ journal = (rent J..| 1)+ .+ (rent J..| 2)+ .+ (sale J..| 3)+ .+ (sale J..| 4)+ .+ (sale J..| 5)+ .+ ((30 .@ Not :< Cash) J..| 6)+ renamings :: [Int -> Int]+ renamings = [(+ 10), (100 -), (\note -> note * note + 1)]+ assertEqual "duplicate group sizes before renaming" (Right [2, 3]) (duplicateGroupSizes journal)+ forM_ renamings $ \rename -> do+ let renamed :: J.Journal Int Double (HatBase AccountTitles)+ renamed = J.fromMap $ HM.fromList+ [(rename note, transaction) | (note, transaction) <- HM.toList (J.toMap journal)]+ assertEqual "injective note renaming preserves groups"+ (duplicateGroupSizes journal) (duplicateGroupSizes renamed)++ -- (e) A note containing IncomeSummary is excluded as a whole, even when+ -- it contains both kinds of contrary nominal postings.+ let ordinary :: J.Journal Int Double (HatBase AccountTitles)+ ordinary = ((5 .@ Hat :< Sales) J..| 1)+ .+ ((7 .@ Hat :< RentExpense) J..| 2)+ closing :: J.Journal Int Double (HatBase AccountTitles)+ closing = ((20 .@ Hat :< Sales+ .+ 10 .@ Hat :< RentExpense+ .+ 10 .@ Hat :< IncomeSummary) J..| 3)+ assertEqual "ordinary contrary postings are observed" "warning"+ (resultKind (contraryNominalPostings ordinary))+ assertEqual "adding a closing transaction changes no contrary finding"+ (contraryNominalPostings ordinary) (contraryNominalPostings (ordinary .+ closing))++ let contraPostings :: J.Journal Int Double (HatBase AccountTitles)+ contraPostings = ((10 .@ Not :< SalesAllowances+ .+ 10 .@ Hat :< Cash) J..| 1)+ .+ ((10 .@ Not :< PurchaseAllowances+ .+ 10 .@ Not :< Cash) J..| 2)+ .+ ((10 .@ Hat :< SalesAllowances+ .+ 10 .@ Not :< Cash) J..| 3)+ assertEqual "contra nominal postings are compared with their home side"+ (Warning (ContraryNominalPosting 3 10 (Hat :< SalesAllowances) :| []))+ (contraryNominalPostings contraPostings)++ -- (f) Every concrete title in either Hat direction has only the severity+ -- promised by each function; zero and mixed inputs are covered as well.+ let validInputs :: [TrialBalance Double]+ validInputs = emptyTrial : rent : sale :+ [10 .@ side :< title | title <- [minBound .. maxBound]+ , title /= AccountTitle+ , side <- [Not, Hat]]+ forM_ validInputs $ \input -> do+ let validJournal :: J.Journal Int Double (HatBase AccountTitles)+ validJournal = (input J..| 1) .+ (input J..| 2)+ assertEqual "warning audits never return accounting errors" (replicate 4 False)+ [ resultKind (abnormalBalances input) == "error"+ , resultKind (temporaryAccountBalances input) == "error"+ , resultKind (duplicateTransactions validJournal) == "error"+ , resultKind (contraryNominalPostings validJournal) == "error"+ ]+ assertEqual "error audits never return warnings" [False, False]+ [ resultKind (impossibleBalances input) == "warning"+ , resultKind (closingResiduals input) == "warning"+ ]
+ test/Accounting/ClosingTargetSpec.hs view
@@ -0,0 +1,285 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE UndecidableInstances #-}++-- | Closing-target validation, vocabulary renaming, and closing laws.+module Accounting.ClosingTargetSpec (runTests) where++import Control.Monad (forM_)+import Data.Bifunctor (first, second)+import Data.Either (isLeft)+import Data.Hashable (Hashable)+import qualified Data.Map.Strict as Map+import Data.Proxy (Proxy(..))+import Data.Typeable (Typeable)+import GHC.Generics (Generic)+import Test.QuickCheck+ ( Gen, Property, chooseInt, chooseInteger, conjoin, counterexample, elements+ , forAll, frequency, once, property, vectorOf, (===) )++import ExchangeAlgebra.Accounting.Account+import ExchangeAlgebra.Accounting.Closing+import ExchangeAlgebra.Accounting.Exchange (ExBaseClass(..), decL, decR)+import ExchangeAlgebra.Algebra.Base+ ( BaseClass, CountUnit(..), Element(..), Hat(..), HatBase((:<)), HatBaseClass )+import ExchangeAlgebra.Algebra.Core+ ( Alg, Redundant(..), (.@), foldEntries, foldEntriesToMap, mapBasePart, vals )+import qualified ExchangeAlgebra.Algebra.Internal as Internal+import ExchangeAlgebra.Algebra.Value (HatVal, MoneyDecimal)+import Support (assertEqual, genSide, genUnit, quickProp)++-- * Reference classifications for the built-in chart++referenceTarget :: AccountTitles -> Maybe ClosingTargetViolation+referenceTarget AccountTitle = Just ClosingTargetIsWildcard+referenceTarget title = case accountSpec title of+ Nothing -> Just ClosingTargetWithoutSpec+ Just spec+ | asDivision spec /= Equity -> Just (ClosingTargetNotEquity (asDivision spec))+ | asIsContra spec -> Just ClosingTargetIsContra+ | otherwise -> Nothing++-- | The built-in classifier before closing was generalized to vocabularies.+referenceSide :: AccountTitles -> Maybe ClosingSide+referenceSide title = case asClosing <$> accountSpec title of+ Just CloseByDivision -> case direction of+ IN -> Just ClosingKeep+ OUT -> Just ClosingFlip+ _ -> Nothing+ _ -> Nothing+ where+ normal = pimoFromDivision (classifyAccountDivision title)+ direction+ | classifyAccountContra title = pimoFlip normal+ | otherwise = normal++-- * Four vocabularies with invalid closing targets++data TargetFault = WildcardTarget | MissingSpec | RevenueTarget | ContraEquity++newtype BadTitle (fault :: TargetFault) = BadTitle AccountTitles+ deriving (Eq, Ord, Show, Generic)++instance Hashable (BadTitle fault)+instance Typeable fault => Element (BadTitle fault) where+ wildcard = BadTitle AccountTitle+instance Typeable fault => BaseClass (BadTitle fault)++instance AccountVocabulary (BadTitle 'WildcardTarget) where+ vocabSpec (BadTitle title) = accountSpec title+ closingTarget = BadTitle AccountTitle++instance AccountVocabulary (BadTitle 'MissingSpec) where+ vocabSpec (BadTitle RetainedEarnings) = Nothing+ vocabSpec (BadTitle title) = accountSpec title+ closingTarget = BadTitle RetainedEarnings++instance AccountVocabulary (BadTitle 'RevenueTarget) where+ vocabSpec (BadTitle title) = accountSpec title+ closingTarget = BadTitle SalesRebates++instance AccountVocabulary (BadTitle 'ContraEquity) where+ vocabSpec (BadTitle RetainedEarnings) =+ (\spec -> spec { asIsContra = True }) <$> accountSpec RetainedEarnings+ vocabSpec (BadTitle title) = accountSpec title+ closingTarget = BadTitle RetainedEarnings++instance (Typeable fault, AccountVocabulary (BadTitle fault))+ => ExBaseClass (HatBase (BadTitle fault)) where+ type TitleOf (HatBase (BadTitle fault)) = BadTitle fault+ getAccountTitle (_ :< title) = title+ setAccountTitle (side :< _) title = side :< title++-- | Invalid targets must win even when reading the input would give another error.+checkInvalid :: forall fault. (Typeable fault, AccountVocabulary (BadTitle fault))+ => BadTitle fault -> ClosingTargetViolation -> IO ()+checkInvalid target reason = do+ let sales = BadTitle Sales :: BadTitle fault+ nonFinite = 1 / 0 :: Double+ -- The raw singleton admits the deliberately invalid posting.+ badLedger = Internal.Single nonFinite (Not :< sales)+ checkName name = "C2 " ++ show reason ++ " " ++ name+ forM_ [("empty ledger", mempty), ("non-finite ledger", badLedger)] $ \(name, ledger) ->+ case closingEntries ledger of+ Left (InvalidClosingTarget actual why) ->+ assertEqual (checkName name) (target, reason) (actual, why)+ other -> fail (checkName name ++ ": " ++ show other)+ forM_ [("empty map", Map.empty), ("non-finite map", Map.singleton sales nonFinite)] $+ \(name, nets) -> case settleEntries retainedEarningsRule nets+ :: Either (SettleError (HatBase (BadTitle fault)))+ (SettlementBatch (HatBase (BadTitle fault))) of+ Left err -> assertEqual (checkName name) (InvalidSettleTarget target reason) err+ Right _ -> fail (checkName name ++ ": accepted invalid target")++-- * Renaming the closing target while preserving the unit axis++data ShopTitle = Std AccountTitles | OwnersCapital+ deriving (Eq, Ord, Show, Generic)++instance Hashable ShopTitle+instance Element ShopTitle where+ wildcard = Std AccountTitle++instance AccountVocabulary ShopTitle where+ vocabSpec (Std title) = accountSpec title+ vocabSpec OwnersCapital =+ (\spec -> spec { asNameEn = "Owner's capital", asNameJa = "元入金"+ , asLabelJa = "元入金", asAliases = [] }) <$> accountSpec RetainedEarnings+ vocabSemantics (Std title) = accountSemantics title+ vocabSemantics OwnersCapital = accountSemantics RetainedEarnings+ closingTarget = OwnersCapital++type UnitBase t = HatBase (CountUnit, t)++instance ExBaseClass (UnitBase ShopTitle) where+ type TitleOf (UnitBase ShopTitle) = ShopTitle+ getAccountTitle (_ :< (_, title)) = title+ setAccountTitle (side :< (unit, _)) title = side :< (unit, title)++shopTitle :: AccountTitles -> ShopTitle+shopTitle RetainedEarnings = OwnersCapital+shopTitle title = Std title++type Ledger v t = Alg v (UnitBase t)+type Nets t = Map.Map (CountUnit, t) SignedNet++renameLedger :: HatVal v => (AccountTitles -> ShopTitle)+ -> Ledger v AccountTitles -> Ledger v ShopTitle+renameLedger f = mapBasePart (second f)++-- | Give closing directions, contra accounts, NoClose and the target frequent collisions.+genCoordinates :: Gen (CountUnit, AccountTitles)+genCoordinates = (,) <$> genUnit <*> frequency+ [ (4, elements [Sales, InterestEarned, SalesCost, SalesRebates, PurchaseRebates,+ NetIncome, Cash, RetainedEarnings])+ , (1, elements concreteAccountTitles)+ ]++genLedger :: HatVal v => Gen (Ledger v AccountTitles)+genLedger = do+ count <- chooseInt (0, 35)+ fmap mconcat $ vectorOf count $ do+ coordinates <- genCoordinates+ side <- genSide+ value <- frequency+ [ (1, fromInteger <$> chooseInteger (1, 1000000))+ , (2, elements [0.1, 0.2, 0.3, 1, 2 ^ (53 :: Int)])+ ]+ pure (value .@ side :< coordinates)++genNets :: Gen (Nets AccountTitles)+genNets = do+ count <- chooseInt (0, 35)+ fmap Map.fromList $ vectorOf count $+ (,) <$> genCoordinates <*> elements [-1e100, -2.5, -0.1, 0, 0.2, 3, 1e100]++-- | L2v observes summed values at complete Hat/Not bases after bar.+obs :: (HatVal v, HatBaseClass b) => Alg v b -> Map.Map b v+obs = foldEntriesToMap (\v b -> Just (b, v)) . bar++-- | A failed call may identify a different first source under the new Ord.+sameOutcome :: (Eq a, Show a) => Either e a -> Either e' a -> Property+sameOutcome expected actual = first (const ()) actual === first (const ()) expected++closingRenaming :: HatVal v => Ledger v AccountTitles -> Property+closingRenaming ledger = sameOutcome+ (obs . renameLedger shopTitle <$> closingEntries ledger)+ (obs <$> closingEntries (renameLedger shopTitle ledger))++settlements :: ExBaseClass (UnitBase t) => Nets t+ -> Either (SettleError (UnitBase t)) (SettlementBatch (UnitBase t))+settlements = settleEntries retainedEarningsRule++-- | Index observations by the mapped source, independently of traversal order.+settleRenaming :: (AccountTitles -> ShopTitle) -> Nets AccountTitles -> Property+settleRenaming f nets = sameOutcome (observeOriginal <$> settlements nets)+ (observeShop <$> settlements (Map.mapKeys (second f) nets))+ where+ -- Keep every pair so that a repeated source cannot overwrite an earlier one.+ observeOriginal batch = Map.fromListWith (++)+ [(second f k, [obs (renameLedger f pair)]) | (k, pair) <- settlementSteps batch]+ observeShop batch = Map.fromListWith (++)+ [(k, [obs pair]) | (k, pair) <- settlementSteps batch]++-- | Move the exact signed net to the target on its prescribed side, per unit.+-- This oracle also retains opening equity and every ineligible source balance.+expectedNet :: (CountUnit, ShopTitle) -> Rational -> ((CountUnit, ShopTitle), Rational)+expectedNet k@(unit, Std title) net = case referenceSide title of+ Just ClosingKeep -> ((unit, OwnersCapital), net)+ Just ClosingFlip -> ((unit, OwnersCapital), negate net)+ Nothing -> (k, net)+expectedNet k net = (k, net)++exactNets :: (Real v, HatVal v) => Ledger v ShopTitle -> Map.Map (CountUnit, ShopTitle) Rational+exactNets = foldEntries add Map.empty+ where+ add totals value (side :< k) = Map.insertWith (+) k signed totals+ where+ signed | side == Hat = negate (toRational value)+ | otherwise = toRational value++shopLaws :: (Real v, HatVal v) => (v -> v -> Bool) -> Ledger v AccountTitles -> Property+shopLaws equalTotal original = case closingEntries ledger of+ Left err -> counterexample (show err) False+ Right entries -> conjoin+ [ counterexample "L2 exact net at each source and target" $+ Map.filter (/= 0) (exactNets (ledger .+ entries)) === Map.filter (/= 0) expected+ , counterexample ("L3 debit and credit totals " ++ show (debits, credits)) $+ equalTotal debits credits+ , counterexample "L5 raw posting values" $ all (>= 0) (vals entries)+ ]+ where+ debits = norm (decL entries)+ credits = norm (decR entries)+ where+ ledger = renameLedger shopTitle original+ expected = Map.fromListWith (+) [expectedNet k v | (k, v) <- Map.toList (exactNets ledger)]++runValueLaws :: forall v. (Real v, HatVal v)+ => Proxy v -> String -> (v -> v -> Bool) -> IO ()+runValueLaws _ name equalTotal = do+ quickProp ("C4 L2v closing " ++ name) (forAll ledgers closingRenaming)+ quickProp ("C5 L2/L3/L5 shop " ++ name) (forAll ledgers (shopLaws equalTotal))+ where+ ledgers = genLedger :: Gen (Ledger v AccountTitles)++runTests :: IO ()+runTests = do+ let titles = [minBound .. maxBound]+ assertEqual "C1 concrete target violations" []+ [(t, referenceTarget t, closingTargetViolation t) | t <- titles, t /= AccountTitle,+ referenceTarget t /= closingTargetViolation t]+ assertEqual "C1 retained earnings" Nothing (closingTargetViolation RetainedEarnings)+ assertEqual "C1 wildcard" (Just ClosingTargetIsWildcard) (closingTargetViolation AccountTitle)+ checkInvalid (BadTitle AccountTitle :: BadTitle 'WildcardTarget) ClosingTargetIsWildcard+ checkInvalid (BadTitle RetainedEarnings :: BadTitle 'MissingSpec) ClosingTargetWithoutSpec+ checkInvalid (BadTitle SalesRebates :: BadTitle 'RevenueTarget) (ClosingTargetNotEquity Revenue)+ checkInvalid (BadTitle RetainedEarnings :: BadTitle 'ContraEquity) ClosingTargetIsContra+ assertEqual "C3 built-in closing sides" []+ [(t, referenceSide t, closingSide t) | t <- titles, referenceSide t /= closingSide t]+ runValueLaws (Proxy :: Proxy Double) "Double" (\a b -> abs (a - b) <= 1e-9 * max (abs a) (abs b))+ runValueLaws (Proxy :: Proxy MoneyDecimal) "MoneyDecimal" (==)+ quickProp "C4 L2v settlement by source key" (forAll genNets (settleRenaming shopTitle))+ let swap Sales = Std InterestEarned+ swap InterestEarned = Std Sales+ swap t = shopTitle t+ twoSources = Map.fromList [((Yen, Sales), 3), ((Yen, InterestEarned), -7)]+ largeSale = 1e308 .@ Not :< (Yen, Sales) :: Ledger Double AccountTitles+ overflow = largeSale .+ largeSale+ invalidNets = Map.map (const (1 / 0)) twoSources+ quickProp "C4 L2v settlement with reversed source order" $+ once $ conjoin+ [ fmap (length . settlementSteps) (settlements twoSources) === Right 2+ , settleRenaming swap twoSources+ ]+ quickProp "C4 L2v closing and settlement failures" $ once $ conjoin+ [ property (isLeft (closingEntries overflow))+ , closingRenaming overflow+ , property (isLeft (settlements invalidNets))+ , settleRenaming swap invalidNets+ ]
+ test/Accounting/ConsolidationVocabularySpec.hs view
@@ -0,0 +1,482 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE KindSignatures #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeFamilies #-}++-- | Worksheet laws for account vocabulary, posting authority, and balance.+module Accounting.ConsolidationVocabularySpec (runTests) where++import Data.Hashable (Hashable)+import Data.List (sort, sortOn)+import Data.List.NonEmpty (NonEmpty(..))+import qualified Data.List.NonEmpty as NE+import qualified Data.Map.Strict as M+import Data.Proxy (Proxy(..))+import Data.Typeable (Typeable)+import GHC.Generics (Generic)++import ExchangeAlgebra.Accounting.Account+ ( AccountDivision(..)+ , AccountSemantics(asemPostingCapability)+ , AccountSpec(asDivision, asIsContra)+ , AccountTitles(..)+ , AccountVocabulary(..)+ , PostingCapability(..)+ , accountSemantics+ , accountSpec+ )+import ExchangeAlgebra.Accounting.Consolidation+ ( TrialBalanceSourceOf(..)+ , ValidatedWorksheetOf+ , WorksheetAdjustmentOf(..)+ , WorksheetErrorOf(..)+ , WorksheetInputOf(..)+ , WorksheetLinkage(..)+ , combinedWorksheet+ , validateConsolidationWorksheet+ , validatedAdjustments+ , validatedSources+ )+import ExchangeAlgebra.Accounting.Exchange (ExBaseClass(..))+import ExchangeAlgebra.Accounting.Statements.Metric (PeriodResult(PeriodBreakEven))+import ExchangeAlgebra.Accounting.TrialBalance.Balance (AccountBalance(NoBalance))+import ExchangeAlgebra.Algebra.Base+ ( HasElementKeys+ , BaseClass+ , Element(..)+ , Hat(..)+ , HatBase(..)+ )+import ExchangeAlgebra.Algebra.Core (Alg, (.@), foldEntries)+import Support (assertEqual)++-- | Independent fixtures use exact integer-valued Double postings.+type Row t = (Hat, t, Double)++-- | The validator returns every finding with its original provenance.+type Result t =+ Either (NonEmpty (WorksheetErrorOf t String String Double))+ (ValidatedWorksheetOf t String String Double)++-- | The built-in vocabulary with its exact order reversed.+newtype Rev = Rev AccountTitles+ deriving (Eq, Show, Generic)++instance Ord Rev where+ compare (Rev left) (Rev right) = compare right left++instance Hashable Rev++instance Element Rev where+ wildcard = Rev (wildcard :: AccountTitles)++instance BaseClass Rev++instance AccountVocabulary Rev where+ vocabSpec (Rev title) = vocabSpec title+ vocabSemantics (Rev title) = vocabSemantics title+ vocabDivision (Rev title) = vocabDivision title+ vocabContra (Rev title) = vocabContra title+ vocabReciprocalPairs =+ [(Rev left, Rev right) | (left, right) <- vocabReciprocalPairs]+ closingTarget = Rev closingTarget+ vocabImpossibleBalanceSides =+ [(Rev title, side) | (title, side) <- vocabImpossibleBalanceSides]+ vocabSuspenseTitles = map Rev vocabSuspenseTitles+ vocabAdditionalClosingResidualTitles = map Rev vocabAdditionalClosingResidualTitles++instance ExBaseClass (HatBase Rev) where+ type TitleOf (HatBase Rev) = Rev+ getAccountTitle (_ :< title) = title+ setAccountTitle (side :< _) title = side :< title++-- | This wrapper delegates title specifications and omits posting semantics.+newtype NoSemantics = NoSemantics AccountTitles+ deriving (Eq, Ord, Show, Generic)++instance Hashable NoSemantics++instance Element NoSemantics where+ wildcard = NoSemantics AccountTitle++instance BaseClass NoSemantics++instance AccountVocabulary NoSemantics where+ vocabSpec (NoSemantics title) = vocabSpec title+ closingTarget = NoSemantics closingTarget++instance ExBaseClass (HatBase NoSemantics) where+ type TitleOf (HatBase NoSemantics) = NoSemantics+ getAccountTitle (_ :< title) = title+ setAccountTitle (side :< _) title = side :< title++-- | Vary one tested property at a time while retaining the same title constructors.+data Policy+ = WithCapability PostingCapability+ | BothAssets+ | ContraEquity++-- | Custom coordinates with a wildcard and a separate non-contra closing target.+data LocalTitle (policy :: Policy)+ = A+ | B+ | ClosingTarget+ | AnyAccount+ deriving (Eq, Ord, Show, Generic)++instance Hashable (LocalTitle policy)++instance Typeable policy => Element (LocalTitle policy) where+ wildcard = AnyAccount++instance Typeable policy => BaseClass (LocalTitle policy)++instance FixturePolicy policy => ExBaseClass (HatBase (LocalTitle policy)) where+ type TitleOf (HatBase (LocalTitle policy)) = LocalTitle policy+ getAccountTitle (_ :< title) = title+ setAccountTitle (side :< _) title = side :< title++-- | Defaults describe A as an ordinary asset and B as non-contra ordinary equity.+class Typeable policy => FixturePolicy (policy :: Policy) where+ capabilityOfA :: Proxy policy -> PostingCapability+ capabilityOfA _ = OrdinaryPosting++ divisionOfB :: Proxy policy -> AccountDivision+ divisionOfB _ = Equity++ contraOfB :: Proxy policy -> Bool+ contraOfB _ = False++instance FixturePolicy ('WithCapability 'OrdinaryPosting)++instance FixturePolicy ('WithCapability 'ConsolidationOnly) where+ capabilityOfA _ = ConsolidationOnly++instance FixturePolicy ('WithCapability 'ClosingOnly) where+ capabilityOfA _ = ClosingOnly++instance FixturePolicy ('WithCapability 'EngineGeneratedOnly) where+ capabilityOfA _ = EngineGeneratedOnly++instance FixturePolicy ('WithCapability 'NotPostable) where+ capabilityOfA _ = NotPostable++instance FixturePolicy 'BothAssets where+ divisionOfB _ = Assets++instance FixturePolicy 'ContraEquity where+ contraOfB _ = True++instance FixturePolicy policy => AccountVocabulary (LocalTitle policy) where+ vocabSpec A = accountSpec Cash+ vocabSpec B = fmap alterSpec (accountSpec CapitalStock)+ where+ alterSpec :: AccountSpec -> AccountSpec+ alterSpec spec = spec+ { asDivision = divisionOfB (Proxy :: Proxy policy)+ , asIsContra = contraOfB (Proxy :: Proxy policy)+ }+ vocabSpec ClosingTarget = accountSpec RetainedEarnings+ vocabSpec AnyAccount = Nothing++ vocabSemantics A = fmap grantCapability (accountSemantics Cash)+ where+ grantCapability :: AccountSemantics -> AccountSemantics+ grantCapability semantics = semantics+ { asemPostingCapability = capabilityOfA (Proxy :: Proxy policy) }+ vocabSemantics B = accountSemantics CapitalStock+ vocabSemantics ClosingTarget = accountSemantics RetainedEarnings+ vocabSemantics AnyAccount = Nothing++ closingTarget = ClosingTarget++-- | Build each source and adjustment from raw Hat/Not directions.+worksheet+ :: forall a t. (BaseClass t, HasElementKeys t)+ => (a -> t)+ -> NonEmpty (String, [Row a])+ -> [(String, NonEmpty String, [Row a])]+ -> WorksheetInputOf t String String Double+worksheet rename sources adjustments =+ WorksheetInput (fmap source sources) (map adjustment adjustments) linkage+ where+ source :: (String, [Row a]) -> TrialBalanceSourceOf t String Double+ source (identifier, rows) = TrialBalanceSource identifier (ledger rows)++ adjustment :: (String, NonEmpty String, [Row a]) -> WorksheetAdjustmentOf t String String Double+ adjustment (identifier, refs, rows) = WorksheetAdjustment identifier refs (ledger rows)++ ledger :: [Row a] -> Alg Double (HatBase t)+ ledger rows = mconcat [amount .@ (side :< rename title) | (side, title, amount) <- rows]++-- | Use zero balances and break-even results in every cross-column equation.+linkage :: WorksheetLinkage Double+linkage = WorksheetLinkage+ { _profitOrLossNetIncome = PeriodBreakEven+ , _profitOrLossNetIncomeAttributableToOwners = PeriodBreakEven+ , _statementOfChangesNetIncomeAttributableToOwners = PeriodBreakEven+ , _openingRetainedEarnings = NoBalance+ , _retainedEarningsDividends = 0+ , _statementOfChangesClosingRetainedEarnings = NoBalance+ , _balanceSheetRetainedEarnings = NoBalance+ , _openingNonControllingInterests = NoBalance+ , _nonControllingInterestsPeriodShare = PeriodBreakEven+ , _nonControllingInterestsDividends = 0+ , _statementOfChangesClosingNonControllingInterests = NoBalance+ , _balanceSheetNonControllingInterests = NoBalance+ }++-- | Read all posting rows in traversal order.+postings :: forall t. (BaseClass t, HasElementKeys t) => Alg Double (HatBase t) -> [Row t]+postings alg = reverse (foldEntries collect [] alg)+ where+ collect :: [Row t] -> Double -> HatBase t -> [Row t]+ collect rows amount (side :< title) = (side, title, amount) : rows++-- | Compare a complete error multiset, retaining repeated equal findings.+expectErrors+ :: (Eq t, Show t)+ => String+ -> NonEmpty (WorksheetErrorOf t String String Double)+ -> Result t+ -> IO ()+expectErrors label expected result = case result of+ Left errors -> assertEqual label (ordered expected) (ordered errors)+ Right _ -> fail (label ++ " unexpectedly accepted")+ where+ ordered :: Show a => NonEmpty a -> [a]+ ordered = sortOn show . NE.toList++-- | Access accepted data so a successful validation still checks its content.+requireWorksheet :: Show t => String -> Result t -> IO (ValidatedWorksheetOf t String String Double)+requireWorksheet label result = case result of+ Left errors -> fail (label ++ " rejected " ++ show errors)+ Right accepted -> pure accepted++-- | Assert the full posting multiset and the amount sequence within each base.+expectCombined+ :: (BaseClass t, HasElementKeys t)+ => String+ -> [((Hat, t), [Double])]+ -> ValidatedWorksheetOf t String String Double+ -> IO ()+expectCombined label expected accepted = do+ assertEqual (label ++ " posting multiset") (sort expectedRows) (sort actualRows)+ assertEqual (label ++ " per-base amount order") (M.fromList expected) actualSequences+ where+ expectedRows = [(side, title, amount) | ((side, title), amounts) <- expected, amount <- amounts]+ actualRows = postings (combinedWorksheet accepted)+ actualSequences = M.fromListWith (flip (++))+ [((side, title), [amount]) | (side, title, amount) <- actualRows]++-- | Run the same rejected case through both vocabularies with a manual error oracle.+expectRenamedErrors+ :: String+ -> NonEmpty (String, [Row AccountTitles])+ -> [(String, NonEmpty String, [Row AccountTitles])]+ -> (forall t. (AccountTitles -> t) -> NonEmpty (WorksheetErrorOf t String String Double))+ -> IO ()+expectRenamedErrors label sources adjustments expected = do+ expectErrors (label ++ " built-in") (expected id)+ (validateConsolidationWorksheet (worksheet id sources adjustments))+ expectErrors (label ++ " reversed") (expected Rev)+ (validateConsolidationWorksheet (worksheet Rev sources adjustments))++-- | L2 preserves worksheet terms and provenance under title renaming.+checkRenaming :: IO ()+checkRenaming = do+ builtIn <- requireWorksheet "L2 built-in" $+ validateConsolidationWorksheet (worksheet id sources adjustments)+ reversed <- requireWorksheet "L2 reversed" $+ validateConsolidationWorksheet (worksheet Rev sources adjustments)+ expectCombined "L2 built-in"+ [ ((Hat, Cash), [3])+ , ((Not, Cash), [7, 11, 7, 17])+ , ((Hat, CapitalStock), [3])+ , ((Not, CapitalStock), [7, 11, 7, 17])+ , ((Not, BranchCurrentAccount), [13])+ , ((Not, HeadOfficeCurrentAccount), [13])+ ]+ builtIn+ expectCombined "L2 reversed"+ [ ((Not, Rev HeadOfficeCurrentAccount), [13])+ , ((Not, Rev BranchCurrentAccount), [13])+ , ((Hat, Rev CapitalStock), [3])+ , ((Not, Rev CapitalStock), [7, 11, 7, 17])+ , ((Hat, Rev Cash), [3])+ , ((Not, Rev Cash), [7, 11, 7, 17])+ ]+ reversed+ assertEqual "L2 built-in source order" ("z-parent" :| ["a-branch"])+ (fmap _sourceId (validatedSources builtIn))+ assertEqual "L2 reversed source order" ("z-parent" :| ["a-branch"])+ (fmap _sourceId (validatedSources reversed))+ assertEqual "L2 built-in adjustment order" ["z-entry", "a-entry"]+ (map _adjustmentId (validatedAdjustments builtIn))+ assertEqual "L2 reversed adjustment order" ["z-entry", "a-entry"]+ (map _adjustmentId (validatedAdjustments reversed))++ expectRenamedErrors "L2 duplicate identifiers"+ (("entity", [(Not, Cash, 6), (Not, CapitalStock, 6)]) :|+ [("entity", [(Not, Cash, 8), (Not, CapitalStock, 8)])])+ [ ("entry", "entity" :| [], [(Not, Cash, 2), (Not, CapitalStock, 2)])+ , ("entry", "entity" :| [], [(Not, Cash, 4), (Not, CapitalStock, 4)])+ ]+ (\_ -> DuplicateSourceId "entity" :| [DuplicateAdjustmentId "entry"])+ expectRenamedErrors "L2 unbalanced source"+ (("entity", [(Not, Cash, 9), (Not, CapitalStock, 4)]) :| [])+ []+ (\_ -> UnbalancedSourceTrialBalance "entity" 9 4 :| [])+ expectRenamedErrors "L2 prohibited adjustment" sources+ [("engine", "z-parent" :| [], [(Not, NetIncome, 5), (Not, CapitalStock, 5)])]+ (\rename+ -> AdjustmentPostingNotAllowed "engine" (rename NetIncome) EngineGeneratedOnly :| [])+ expectRenamedErrors "L2 wildcard adjustment" sources+ [("wild", "z-parent" :| [], [(Not, AccountTitle, 5)])]+ (\_ -> WildcardAdjustmentAccount "wild" :| [])+ putStrLn "[PASS] L2 worksheet vocabulary renaming"+ where+ sources :: NonEmpty (String, [Row AccountTitles])+ sources =+ ("z-parent",+ [ (Not, Cash, 7)+ , (Not, CapitalStock, 7)+ , (Not, BranchCurrentAccount, 13)+ , (Not, HeadOfficeCurrentAccount, 13)+ ]) :| [("a-branch", [(Not, Cash, 11), (Not, CapitalStock, 11)])]++ adjustments :: [(String, NonEmpty String, [Row AccountTitles])]+ adjustments =+ [ ("z-entry", "z-parent" :| [], [(Not, Cash, 7), (Not, CapitalStock, 7)])+ , ("a-entry", "a-branch" :| [],+ [ (Hat, Cash, 3)+ , (Hat, CapitalStock, 3)+ , (Not, Cash, 17)+ , (Not, CapitalStock, 17)+ ])+ ]++-- | Nonzero raw source postings with debit-normal A and credit-normal B.+localSource :: NonEmpty (String, [Row (LocalTitle policy)])+localSource = ("entity", [(Not, A, 10), (Not, B, 10)]) :| []++-- | L3 treats absent capability as a prohibition only when posting an adjustment.+checkDefaultSemantics :: IO ()+checkDefaultSemantics = do+ accepted <- requireWorksheet "L3 historical source" $+ validateConsolidationWorksheet (worksheet NoSemantics sources [])+ expectCombined "L3 historical source"+ [((Not, NoSemantics Cash), [10]), ((Not, NoSemantics CapitalStock), [10])]+ accepted+ expectErrors "L3 each occurrence without posting semantics is rejected"+ (AdjustmentPostingNotAllowed "entry" (NoSemantics Cash) NotPostable :|+ [AdjustmentPostingNotAllowed "entry" (NoSemantics Cash) NotPostable])+ (validateConsolidationWorksheet (worksheet NoSemantics sources adjustments))+ putStrLn "[PASS] L3 omitted worksheet posting semantics"+ where+ sources :: NonEmpty (String, [Row AccountTitles])+ sources = ("entity", [(Not, Cash, 10), (Not, CapitalStock, 10)]) :| []++ adjustments :: [(String, NonEmpty String, [Row AccountTitles])]+ adjustments = [("entry", "entity" :| [], [(Not, Cash, 2), (Hat, Cash, 2)])]++-- | L4 evaluates five capabilities on the same A and B postings.+checkCapabilities :: IO ()+checkCapabilities = do+ checkCapability (Proxy :: Proxy ('WithCapability 'OrdinaryPosting)) "OrdinaryPosting" Nothing+ checkCapability (Proxy :: Proxy ('WithCapability 'ConsolidationOnly))+ "ConsolidationOnly" Nothing+ checkCapability (Proxy :: Proxy ('WithCapability 'ClosingOnly)) "ClosingOnly" (Just ClosingOnly)+ checkCapability (Proxy :: Proxy ('WithCapability 'EngineGeneratedOnly))+ "EngineGeneratedOnly" (Just EngineGeneratedOnly)+ checkCapability (Proxy :: Proxy ('WithCapability 'NotPostable))+ "NotPostable" (Just NotPostable)+ putStrLn "[PASS] L4 worksheet adjustment capability policy"++-- | A changes capability while B remains an ordinary posting in every case.+checkCapability+ :: forall policy. FixturePolicy policy+ => Proxy policy+ -> String+ -> Maybe PostingCapability+ -> IO ()+checkCapability _ label expected = case expected of+ Just capability -> expectErrors label+ (AdjustmentPostingNotAllowed "entry" A capability :| []) result+ Nothing -> do+ accepted <- requireWorksheet label result+ expectCombined label [((Not, A), [10, 2]), ((Not, B), [10, 2])] accepted+ assertEqual (label ++ " retained adjustment")+ [("entry", "entity" :| [], [(Not, A, 2), (Not, B, 2)])]+ (map adjustmentContents (validatedAdjustments accepted))+ where+ result :: Result (LocalTitle policy)+ result = validateConsolidationWorksheet (worksheet id localSource adjustments)++ adjustments :: [(String, NonEmpty String, [Row (LocalTitle policy)])]+ adjustments = [("entry", "entity" :| [], [(Not, A, 2), (Not, B, 2)])]++ adjustmentContents+ :: WorksheetAdjustmentOf (LocalTitle policy) String String Double+ -> (String, NonEmpty String, [Row (LocalTitle policy)])+ adjustmentContents adjustment =+ ( _adjustmentId adjustment+ , _adjustmentSourceIds adjustment+ , sort (postings (_adjustmentElement adjustment))+ )++-- | L5 identifies the custom wildcard separately at each validation boundary.+checkWildcard :: IO ()+checkWildcard = do+ expectErrors "L5 wildcard in a source"+ (WildcardSourceAccount "entity" :| [])+ (validateConsolidationWorksheet (worksheet asOrdinary wildcardSource []))+ expectErrors "L5 wildcard in an adjustment"+ (WildcardAdjustmentAccount "entry" :| [])+ (validateConsolidationWorksheet (worksheet asOrdinary localSource wildcardAdjustment))+ putStrLn "[PASS] L5 custom worksheet wildcard"+ where+ wildcardSource :: NonEmpty (String, [Row (LocalTitle policy)])+ wildcardSource = ("entity", [(Not, AnyAccount, 3)]) :| []++ wildcardAdjustment :: [(String, NonEmpty String, [Row (LocalTitle policy)])]+ wildcardAdjustment = [("entry", "entity" :| [], [(Hat, AnyAccount, 3)])]++-- | L6 fixes both Not directions and amounts while changing vocabulary classification.+checkBalance :: IO ()+checkBalance = do+ accepted <- requireWorksheet "L6 assets and equity" $+ validateConsolidationWorksheet (worksheet asOrdinary localSource [])+ expectCombined "L6 assets and equity" [((Not, A), [10]), ((Not, B), [10])] accepted++ -- Both non-contra assets and contra equity put B on the debit side with A.+ expectErrors "L6 both assets have two debits"+ (UnbalancedSourceTrialBalance "entity" 20 0 :| []) bothAssets+ expectErrors "L6 contra equity has two debits"+ (UnbalancedSourceTrialBalance "entity" 20 0 :| []) contraEquity+ putStrLn "[PASS] L6 worksheet balance uses vocabulary division and contra"+ where+ bothAssets :: Result (LocalTitle 'BothAssets)+ bothAssets = validateConsolidationWorksheet (worksheet id localSource [])++ contraEquity :: Result (LocalTitle 'ContraEquity)+ contraEquity = validateConsolidationWorksheet (worksheet id localSource [])++-- | Fix the default local vocabulary for tests that do not vary the capability.+asOrdinary+ :: LocalTitle ('WithCapability 'OrdinaryPosting)+ -> LocalTitle ('WithCapability 'OrdinaryPosting)+asOrdinary = id++-- | Run the worksheet laws in numerical order.+runTests :: IO ()+runTests = do+ checkRenaming+ checkDefaultSemantics+ checkCapabilities+ checkWildcard+ checkBalance
+ test/Accounting/JcciSpec.hs view
@@ -0,0 +1,175 @@+-- | Check the JCCI vocabulary against the full chart and the public pattern declarations.+module Accounting.JcciSpec (runTests) where++import qualified Data.Binary as Binary+import qualified Data.ByteString.Lazy as BL+import Data.Char (isSpace)+import Data.Either (isLeft)+import Data.Hashable (hash, hashWithSalt)+import Data.List (groupBy, isPrefixOf)+import Data.Maybe (mapMaybe)+import qualified Data.Set as Set+import ExchangeAlgebra.Accounting.Account (AccountTitles(..), AccountVocabulary(..))+import qualified ExchangeAlgebra.Accounting.Account.Jcci as J+import ExchangeAlgebra.Algebra.Base (Hat(..), HatBase(..), wildcard)+import ExchangeAlgebra.Algebra.Core (Alg, Redundant((.+)), (.@), mapBasePart, toList)+import ExchangeAlgebra.Algebra.Value (MoneyDecimal)+import Support (assertEqual, readFileStrict)++runTests :: IO ()+runTests = do+ testPatterns+ testNarrow+ testBinaryAndHash+ testVocabulary+ testNarrowAlg++-- | Enumerate the concrete titles accepted by the restricted vocabulary.+jcciTitles :: [J.JcciTitles]+jcciTitles = mapMaybe J.narrow [title | title <- [minBound .. maxBound], title /= AccountTitle]++-- | Pin the full chart's macroeconomic accounts independently of the row tags.+macroTitles :: [AccountTitles]+macroTitles =+ [ ReserveDepositReceivable+ , GovernmentService+ , ReserveForDepreciation+ , DepositPayable+ , ReserveDepositPayable+ , CentralBankNotePayable+ , ConsumptionExpenditure+ , SubsidyExpense+ , CentralBankPaymentExpense+ , ValueAdded+ , SubsidyIncome+ , WageEarned+ , TaxesRevenue+ , CentralBankPaymentIncome+ ]++-- | Compare the source declarations with the concrete titles in declaration order.+testPatterns :: IO ()+testPatterns = do+ source <- lines <$> readFileStrict "src/ExchangeAlgebra/Accounting/Account/Jcci.hs"+ definitions <- traverse patternName+ [block | block@(line : _) <- groupBy continues source, "pattern " `isPrefixOf` line]+ let exports = [name | [",", "pattern", name] <- map words source]+ complete = completeNames source+ expected = map (show . J.widen) jcciTitles ++ ["AnyJcci"]+ assertNames "JCCI pattern exports" expected exports+ assertNames "JCCI pattern definitions and constructor wiring" expected (concat definitions)+ assertNames "JCCI COMPLETE patterns" expected complete+ where+ continues _ line = case line of+ c : _ -> isSpace c+ [] -> False++-- | Compare both directions, then check declaration order and duplicates.+assertNames :: String -> [String] -> [String] -> IO ()+assertNames label expected actual = do+ let expectedSet = Set.fromList expected+ actualSet = Set.fromList actual+ assertEqual (label ++ " (missing, extra)") ([], [])+ ( Set.toAscList (expectedSet `Set.difference` actualSet)+ , Set.toAscList (actualSet `Set.difference` expectedSet)+ )+ assertEqual (label ++ " in declaration order") expected actual++-- | Read an account pattern and verify its exact constructor wiring.+patternName :: [String] -> IO [String]+patternName block = case (block, words (unwords block)) of+ (_, "pattern" : signature)+ | ("::" : ["JcciTitles"]) <- dropWhile (/= "::") signature+ , all (`notElem` signature) ["=", "<-"] -> pure []+ ([_], ["pattern", name, "=", "JcciTitles", target])+ | matches name target -> pure [name]+ ([header, body], ["pattern", name, "=", "JcciTitles", target])+ | words header == ["pattern", name, "="]+ , " JcciTitles " `isPrefixOf` body+ , matches name target -> pure [name]+ _ -> fail ("Malformed or miswired JCCI pattern: " ++ unwords block)+ where+ matches "AnyJcci" target = target == "T.AccountTitle"+ matches name target = target == "T." ++ name++-- | Read all names in the multiline completeness pragma.+completeNames :: [String] -> [String]+completeNames source = case dropWhile (not . isPrefixOf "{-# COMPLETE") source of+ [] -> []+ header : rest ->+ let pragma = unwords (header : takeWhile (not . isPrefixOf " #-}") rest)+ tokens = words [if c == ',' then ' ' else c | c <- pragma]+ in takeWhile (/= "::") (drop 2 tokens)++-- | Check that the embedding is inverse on every accepted title.+testNarrow :: IO ()+testNarrow = do+ let titles = [minBound .. maxBound]+ expected t+ | t `elem` macroTitles = Nothing+ | otherwise = Just t+ assertEqual "JCCI narrowing on the full chart"+ (map expected titles) (map (fmap J.widen . J.narrow) titles)+ assertEqual "JCCI wildcard" (Just J.AnyJcci) (J.narrow AccountTitle)+ assertEqual "JCCI Element wildcard" J.AnyJcci wildcard+ let accepted = jcciTitles ++ [J.AnyJcci]+ assertEqual "JCCI title spellings" (map (show . J.widen) accepted) (map show accepted)++-- | Check matching wire codes and hashes and reject codes outside the restricted chart.+testBinaryAndHash :: IO ()+testBinaryAndHash = do+ let titles = jcciTitles ++ [J.AnyJcci]+ fullTitles = map J.widen titles+ bytes = map Binary.encode fullTitles+ invalidBytes = BL.pack [0x80, 0x23] : map Binary.encode macroTitles+ assertEqual "JCCI Binary codes match AccountTitles" bytes (map Binary.encode titles)+ assertEqual "JCCI Binary round trips" (map Right titles) (map decodeTitle bytes)+ assertEqual "JCCI Binary rejects macroeconomic and retired codes"+ (replicate (length invalidBytes) True) (map (isLeft . decodeTitle) invalidBytes)+ assertEqual "JCCI hashes match AccountTitles" (map hash fullTitles) (map hash titles)+ assertEqual "JCCI salted hashes match AccountTitles"+ (map (hashWithSalt 42) fullTitles) (map (hashWithSalt 42) titles)+ where+ decodeTitle :: BL.ByteString -> Either String J.JcciTitles+ decodeTitle bytes = case Binary.decodeOrFail bytes of+ Left (_, _, message) -> Left message+ Right (_, _, title) -> Right title++-- | Compare title metadata and accounting checks supplied by the two instances.+testVocabulary :: IO ()+testVocabulary = do+ let fullTitles = map J.widen jcciTitles+ assertEqual "JCCI account specifications" (map vocabSpec fullTitles) (map vocabSpec jcciTitles)+ assertEqual "JCCI account semantics"+ (map vocabSemantics fullTitles) (map vocabSemantics jcciTitles)+ assertEqual "JCCI account divisions"+ (map vocabDivision fullTitles) (map vocabDivision jcciTitles)+ assertEqual "JCCI contra accounts" (map vocabContra fullTitles) (map vocabContra jcciTitles)+ assertEqual "JCCI impossible balance sides" vocabImpossibleBalanceSides+ [(J.widen title, side) | (title, side) <- vocabImpossibleBalanceSides]+ assertEqual "JCCI suspense titles" vocabSuspenseTitles (map J.widen vocabSuspenseTitles)+ assertEqual "JCCI additional closing residual titles" vocabAdditionalClosingResidualTitles+ (map J.widen vocabAdditionalClosingResidualTitles)+ assertEqual "JCCI reciprocal pairs" vocabReciprocalPairs+ [(J.widen left, J.widen right) | (left, right) <- vocabReciprocalPairs]+ assertEqual "JCCI closing target" closingTarget (J.widen closingTarget)++-- | Check rejection and ordered term preservation on both sides of a base.+testNarrowAlg :: IO ()+testNarrowAlg = do+ let ledger :: Alg MoneyDecimal (HatBase AccountTitles)+ ledger = 11 .@ Not :< Cash+ .+ 7 .@ Not :< Cash+ .+ 23 .@ Not :< Cash+ .+ 3 .@ Hat :< Cash+ .+ 5 .@ Hat :< Cash+ .+ 2 .@ Not :< AccountTitle+ mixed = ledger .+ 2 .@ Hat :< GovernmentService+ .+ 3 .@ Not :< ReserveDepositReceivable+ .+ 4 .@ Not :< GovernmentService+ assertEqual "narrowAlg rejects distinct macroeconomic titles in order"+ (Left [ReserveDepositReceivable, GovernmentService]) (J.narrowAlg mixed)+ narrowed <- either (fail . show) pure (J.narrowAlg ledger)+ assertEqual "narrowAlg retains every term" (length (toList ledger)) (length (toList narrowed))+ assertEqual "narrowAlg preserves term values, directions, and per-base order"+ ledger (mapBasePart J.widen narrowed)
+ test/Accounting/PresentationVocabularySpec.hs view
@@ -0,0 +1,288 @@+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE KindSignatures #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeFamilies #-}++-- | Presentation laws for empty defaults, reciprocal tables, and statement coverage.+module Accounting.PresentationVocabularySpec (runTests) where++import Control.Monad (forM_)+import Data.Hashable (Hashable)+import Data.Kind (Type)+import Data.List (nub)+import qualified Data.List.NonEmpty as NE+import Data.Proxy (Proxy(..))+import Data.Typeable (Typeable)+import GHC.Generics (Generic)++import ExchangeAlgebra.Accounting.Account+import ExchangeAlgebra.Accounting.Exchange (ExBaseClass(..), journalForSides)+import ExchangeAlgebra.Accounting.Statements.Presentation+import ExchangeAlgebra.Accounting.TrialBalance.Balance (AccountBalance(..))+import ExchangeAlgebra.Accounting.TrialBalance.Validation (TrialBalanceStage(..))+import ExchangeAlgebra.Algebra.Base (BaseClass, Element(..), HatBase(..))+import ExchangeAlgebra.Algebra.Core (Alg)+import Support (assertEqual)++-- | An ordinary vocabulary deliberately omitting the reciprocal-table method.+newtype DefaultTitle = DefaultTitle AccountTitles+ deriving (Eq, Ord, Show, Generic)++instance Hashable DefaultTitle+instance Element DefaultTitle where+ wildcard = DefaultTitle AccountTitle+instance BaseClass DefaultTitle++instance AccountVocabulary DefaultTitle where+ vocabSpec (DefaultTitle NetIncome) = accountSpec RetainedEarnings+ vocabSpec (DefaultTitle title) = accountSpec title+ vocabSemantics (DefaultTitle title) = case accountSemantics title of+ Just semantics | asemReportingEligibility semantics == DerivedPresentation ->+ accountSemantics RetainedEarnings+ other -> other+ closingTarget = DefaultTitle RetainedEarnings++instance ExBaseClass (HatBase DefaultTitle) where+ type TitleOf (HatBase DefaultTitle) = DefaultTitle+ getAccountTitle (_ :< title) = title+ setAccountTitle (side :< _) title = side :< title++-- | Independent metadata policies share only their coordinate representation.+class Typeable p => FixturePolicy p where+ fixturePairs :: Proxy p -> [(AccountTitles, AccountTitles)]+ fixturePairs _ = []+ fixtureSemantics :: Proxy p -> AccountTitles -> Maybe AccountSemantics+ fixtureSemantics _ = accountSemantics++newtype FixtureTitle (p :: Type) = FixtureTitle AccountTitles+ deriving (Eq, Ord, Show, Generic)++instance Hashable (FixtureTitle p)+instance Typeable p => Element (FixtureTitle p) where+ wildcard = FixtureTitle AccountTitle+instance Typeable p => BaseClass (FixtureTitle p)++instance FixturePolicy p => AccountVocabulary (FixtureTitle p) where+ vocabSpec (FixtureTitle title) = accountSpec title+ vocabSemantics (FixtureTitle title) = fixtureSemantics (Proxy :: Proxy p) title+ vocabReciprocalPairs =+ [(FixtureTitle left, FixtureTitle right) | (left, right) <- fixturePairs (Proxy :: Proxy p)]+ closingTarget = FixtureTitle RetainedEarnings++instance FixturePolicy p => ExBaseClass (HatBase (FixtureTitle p)) where+ type TitleOf (HatBase (FixtureTitle p)) = FixtureTitle p+ getAccountTitle (_ :< title) = title+ setAccountTitle (side :< _) title = side :< title++-- | The first pair is deliberately later in title order than the second pair.+data TwoPairs+instance FixturePolicy TwoPairs where+ fixturePairs _ = [(Deposits, AccountsPayable), (Cash, DepositsReceived)]+ fixtureSemantics _ title = fmap reciprocal (accountSemantics title)+ where+ reciprocal semantics+ | title `elem` [Deposits, AccountsPayable, Cash, DepositsReceived] =+ semantics { asemRoles = [ReciprocalAccount] }+ | otherwise = semantics++-- | Both roles are valid; only the Revenue endpoint violates the table law.+data NominalPair+instance FixturePolicy NominalPair where+ fixturePairs _ = [(Sales, AccountsPayable)]+ fixtureSemantics _ title = fmap reciprocal (accountSemantics title)+ where+ reciprocal semantics+ | title `elem` [Sales, AccountsPayable] =+ semantics { asemRoles = [ReciprocalAccount] }+ | otherwise = semantics++-- | Both statement divisions are valid; neither endpoint has the required role.+data RolelessPair+instance FixturePolicy RolelessPair where+ fixturePairs _ = [(Cash, AccountsPayable)]++data WildcardPair+instance FixturePolicy WildcardPair where+ fixturePairs _ = [(AccountTitle, AccountsPayable)]+ fixtureSemantics _ title = fmap reciprocal metadata+ where+ metadata = accountSemantics (if title == AccountTitle then Cash else title)+ reciprocal semantics = semantics { asemRoles = [ReciprocalAccount] }++-- | Eligibility alone cannot assign either balance to a statement section.+data NonStatement+instance FixturePolicy NonStatement where+ fixtureSemantics _ title = fmap nonStatement (accountSemantics title)+ where+ nonStatement semantics = case title of+ Cash -> semantics+ { asemReportingEligibility = StatementEligible+ , asemDivisionSemantics = DirectionEncoding Assets }+ AccountsPayable -> semantics+ { asemReportingEligibility = StatementEligible+ , asemDivisionSemantics = BookkeepingControlClass Liability }+ _ -> semantics++-- | A context with no implicit presentation instructions or label overrides.+context :: ReportingScope -> ReportingContextOf t Double+context scope = reportingContext JGAAP scope CanonicalEnglish++-- | Use the checked posting constructor with explicit debit/credit direction.+ledger+ :: ExBaseClass (HatBase t)+ => [(Side, t, Double)] -> Alg Double (HatBase t)+ledger = journalForSides++-- | Observe complete line identity, direction, and amount independently of labels.+lineBalances :: FinancialStatementsOf t Double -> [(t, Side, Double)]+lineBalances = map (\line -> (_lineAccount line, _lineSide line, _lineAmount line))+ . _statementLines++-- | Extract only reciprocal operations; mandatory metric events are separate.+reciprocalEvents :: FinancialStatementsOf t Double -> [PresentationAuditEventOf t Double]+reciprocalEvents = filter reciprocal . _presentationAudit+ where+ reciprocal (ReciprocalPairEliminated _ _ _ _) = True+ reciprocal _ = False++-- | Empty defaults retain branch-like coordinates and do not infer legacy metrics.+checkDefaults :: IO ()+checkDefaults = do+ assertEqual "L3 reciprocal table defaults to empty" []+ (vocabReciprocalPairs :: [(DefaultTitle, DefaultTitle)])+ let branch = DefaultTitle BranchCurrentAccount+ office = DefaultTitle HeadOfficeCurrentAccount+ source = ledger [(Debit, branch, 100), (Credit, office, 100)]+ forM_ [Standalone, Combined] $ \scope -> case present (context scope) BeforeClosing source of+ Left issues -> fail ("L3 default presentation failed: " ++ show issues)+ Right statements -> do+ assertEqual "L3 default table preserves both reciprocal-like lines"+ [(branch, Debit, 100), (office, Credit, 100)] (lineBalances statements)+ assertEqual "L3 empty table produces no reciprocal event" []+ (reciprocalEvents statements)+ assertEqual "L3 vocabulary has no derived-presentation metadata" []+ [title | title <- concreteAccountTitles,+ Just semantics <- [vocabSemantics (DefaultTitle title)],+ asemReportingEligibility semantics == DerivedPresentation]+ let resultTitle = DefaultTitle NetIncome+ cash = DefaultTitle Cash+ ordinaryResult = ledger [(Debit, cash, 7), (Credit, resultTitle, 7)]+ case present (context Standalone) BeforeClosing ordinaryResult of+ Left issues -> fail ("L3 ordinary legacy-equivalent title rejected: " ++ show issues)+ Right statements -> do+ assertEqual "L3 legacy-equivalent title remains a statement line" True+ (resultTitle `elem` map _lineAccount (_statementLines statements))+ assertEqual "L3 ordinary legacy-equivalent title has break-even metric"+ [NoBalance] (map _statementSubtotalBalance (_statementSubtotals statements))++-- | The declared table, rather than active-map position, identifies eliminated pairs.+checkTwoPairs :: IO ()+checkTwoPairs = do+ let aLeft = FixtureTitle Deposits :: FixtureTitle TwoPairs+ aRight = FixtureTitle AccountsPayable :: FixtureTitle TwoPairs+ bLeft = FixtureTitle Cash :: FixtureTitle TwoPairs+ bRight = FixtureTitle DepositsReceived :: FixtureTitle TwoPairs+ pairs = vocabReciprocalPairs :: [(FixtureTitle TwoPairs, FixtureTitle TwoPairs)]+ ends = concatMap (\(left, right) -> [left, right]) pairs+ source = ledger [(Debit, bLeft, 100), (Credit, bRight, 100)]+ expectedB = ReciprocalPairEliminated bLeft (DebitBalance 100)+ bRight (CreditBalance 100)+ assertEqual "L4 static reciprocal table preserves declared order"+ [(aLeft, aRight), (bLeft, bRight)] pairs+ assertEqual "L4 reciprocal endpoints are unique" (length ends) (length (nub ends))+ forM_ ends $ \title -> do+ assertEqual "L4 reciprocal endpoint is concrete" False (isWildcard title)+ assertEqual "L4 reciprocal endpoint has role and non-nominal division" True+ (case vocabSemantics title of+ Just semantics -> ReciprocalAccount `elem` asemRoles semantics+ && asemDivisionSemantics semantics `notElem`+ [StatementDivision Revenue, StatementDivision Cost]+ && asemReportingEligibility semantics == StatementEligible+ Nothing -> False)+ case present (context Standalone) BeforeClosing source of+ Left issues -> fail ("L4 standalone presentation failed: " ++ show issues)+ Right statements -> do+ assertEqual "L4 standalone retains pair B lines"+ [(bLeft, Debit, 100), (bRight, Credit, 100)] (lineBalances statements)+ assertEqual "L4 standalone has no reciprocal events" [] (reciprocalEvents statements)+ case present (context Combined) BeforeClosing source of+ Left issues -> fail ("L4 combined presentation failed: " ++ show issues)+ Right statements -> do+ assertEqual "L4 combined removes both pair B lines" [] (lineBalances statements)+ assertEqual "L4 absent A cannot misidentify active pair B" [expectedB]+ (reciprocalEvents statements)+ let both = ledger [(Debit, aLeft, 20), (Credit, aRight, 20),+ (Debit, bLeft, 100), (Credit, bRight, 100)]+ case present (context Combined) BeforeClosing both of+ Left issues -> fail ("L4 both-pair presentation failed: " ++ show issues)+ Right statements -> do+ assertEqual "L4 both pairs remove all four lines" [] (lineBalances statements)+ assertEqual "L4 reciprocal events follow table order"+ [ ReciprocalPairEliminated aLeft (DebitBalance 20) aRight (CreditBalance 20)+ , expectedB ] (reciprocalEvents statements)+ let instructed = (context Combined)+ { _presentationRelabels =+ [PresentationRelabel bLeft (FixtureTitle PettyCash) "explicit instruction"] }+ expectIssue "L4 pair endpoint conflicts with an instruction"+ (ConflictingPresentationInstruction bLeft) (present instructed BeforeClosing source)++-- | Each invalid fixture isolates one necessary validation condition.+checkInvalidPairs :: IO ()+checkInvalidPairs = do+ let nominal = FixtureTitle Sales :: FixtureTitle NominalPair+ nominalOther = FixtureTitle AccountsPayable :: FixtureTitle NominalPair+ nominalLedger = ledger [(Debit, nominal, 100), (Credit, nominalOther, 100)]+ expectIssue "L4 nominal endpoint rejected even with reciprocal role"+ (ConflictingPresentationInstruction nominal)+ (present (context Combined) BeforeClosing nominalLedger)+ let roleless = FixtureTitle Cash :: FixtureTitle RolelessPair+ rolelessOther = FixtureTitle AccountsPayable :: FixtureTitle RolelessPair+ rolelessLedger = ledger [(Debit, roleless, 100), (Credit, rolelessOther, 100)]+ rolelessResult = present (context Combined) AfterClosing rolelessLedger+ forM_ [roleless, rolelessOther] $ \title ->+ expectIssue "L4 non-nominal endpoint rejected without reciprocal role"+ (ConflictingPresentationInstruction title) rolelessResult+ let wildcardTitle = FixtureTitle AccountTitle :: FixtureTitle WildcardPair+ emptyLedger = mempty :: Alg Double (HatBase (FixtureTitle WildcardPair))+ expectIssue "L4 wildcard table endpoint rejected without wildcard postings"+ (ConflictingPresentationInstruction wildcardTitle)+ (present (context Combined) AfterClosing emptyLedger)++-- | Both balanced coordinates must be rejected when no statement division exists.+checkCoverage :: IO ()+checkCoverage = do+ let cash = FixtureTitle Cash :: FixtureTitle NonStatement+ payable = FixtureTitle AccountsPayable :: FixtureTitle NonStatement+ source = ledger [(Debit, cash, 100), (Credit, payable, 100)]+ result = present (context Standalone) BeforeClosing source+ expectIssue "L5 direction-only debit cannot be presented"+ (UnpresentableBalance cash (DebitBalance 100)) result+ expectIssue "L5 control-class credit cannot be presented"+ (UnpresentableBalance payable (CreditBalance 100)) result+ let targetContext = (context Standalone)+ { _presentationRelabels = [PresentationRelabel payable cash "control target"] }+ expectIssue "L5 non-statement target rejects relabeling"+ (ConflictingPresentationInstruction cash)+ (present targetContext BeforeClosing source)++-- | Require an exact issue while allowing independent additional diagnostics.+expectIssue+ :: (Eq t, Show t)+ => String+ -> PresentationIssueOf t Double+ -> Either (NE.NonEmpty (PresentationIssueOf t Double)) (FinancialStatementsOf t Double)+ -> IO ()+expectIssue label expected result = case result of+ Left issues -> assertEqual label True (expected `elem` NE.toList issues)+ Right statements -> fail (label ++ ": unexpected statement " ++ show statements)++-- | Register independent presentation-vocabulary laws.+runTests :: IO ()+runTests = do+ checkDefaults+ checkTwoPairs+ checkInvalidPairs+ checkCoverage
+ test/Accounting/ProcedureLawSpec.hs view
@@ -0,0 +1,294 @@+{-# LANGUAGE ScopedTypeVariables #-}++{- |+Random-input laws for two accounting procedures that are derived from the+journal: the closing entries ('closingEntries') and the consolidation+worksheet ('CW.validateConsolidationWorksheet' and 'CW.combinedWorksheet').++The observation is exact. For a complete base @b@, the net is the exact+'Rational' sum of its Not postings minus its Hat postings, which is the value+that @bar@ leaves on @b@ before rounding. Debit and credit totals are the exact+sums of @decL@ and @decR@. No tolerance is used for 'Double' or @MoneyDecimal@.++Closing laws (subject 'closingEntries'; @Right c = closingEntries x@):++* CL1 balance: the exact debit total of @c@ equals its exact credit total.+* CL2 closure: after @x .+ c@, every base whose account has a 'closingSide'+ has net zero.+* CL3 retention: every base whose account has no 'closingSide', other than+ 'RetainedEarnings', keeps its net, and @c@ has no posting on it.+* CL4 period result: for every unit, the change of the 'RetainedEarnings' net+ equals the sum of the nets of 'ClosingKeep' accounts (revenue and contra+ cost) minus the sum of the nets of 'ClosingFlip' accounts (cost and contra+ revenue), that is, the net income of the period.++Consolidation laws (sources and adjustments are generated independently of the+linkage columns, which are caller-supplied facts):++* CW1 balance: when every source trial balance and every adjustment is+ balanced, validation succeeds and the combined worksheet is balanced.+* CW2 sum: the combined worksheet has the same exact net on every base as+ the sum of the sources and adjustments added in reverse order, and it keeps+ every input posting (the posting multisets are equal; nothing is+ aggregated).+* CW3 rejection: adding one unbalanced adjustment, or replacing one source+ with an unbalanced trial balance, makes validation fail with an error that+ names that adjustment or source.+-}+module Accounting.ProcedureLawSpec (runTests) where++import Control.Monad (unless)+import Data.List (sort)+import qualified Data.List.NonEmpty as NE+import qualified Data.Map.Strict as Map+import Data.Maybe (isJust, isNothing)+import Data.Proxy (Proxy(..))+import System.Exit (exitFailure)+import Test.QuickCheck hiding (label)++import ExchangeAlgebra.Accounting.Account+ ( AccountTitles(..)+ , ProcessingContext(ConsolidationWorksheet)+ , Side(..)+ , postingAllowedIn+ , postingCapabilityFor+ )+import ExchangeAlgebra.Accounting.Closing+ ( ClosingSide(..)+ , closingEntries+ , closingSide+ )+import qualified ExchangeAlgebra.Accounting.Consolidation as CW+import ExchangeAlgebra.Accounting.Exchange+ ( ExBaseClass+ , decL+ , decR+ , getAccountTitle+ , journalForSides+ )+import qualified ExchangeAlgebra.Accounting.Statements.Metric as RM+import qualified ExchangeAlgebra.Accounting.TrialBalance.Balance as TBB+import ExchangeAlgebra.Algebra hiding (map, filter)+import ExchangeAlgebra.Algebra.Value (MoneyDecimal)++-- * Shared observation++-- | A unit axis before the account, using the library's two-axis instance.+type UnitBase = HatBase (CountUnit, AccountTitles)++-- | Exact Not-minus-Hat net per complete base, keyed by the Not base.+exactNets :: (HatVal v, HatBaseClass b, Ord b) => Alg v b -> Map.Map b Rational+exactNets = Map.mapMaybe exactAccum . foldEntries collect Map.empty+ where+ collect totals value source = Map.insertWith mergeAccum (toNot source) (signed value source) totals+ signed value source = case hat source of+ Hat -> negateAccum (addAccum value emptyAccum)+ _ -> addAccum value emptyAccum++-- | Exact sum of every posting value.+exactTotal :: (HatVal v, HatBaseClass b) => Alg v b -> Maybe Rational+exactTotal = exactAccum . foldEntries (\total value _ -> addAccum value total) emptyAccum++-- | Exact debit and credit totals agree.+exactlyBalanced :: (HatVal v, ExBaseClass b) => Alg v b -> Bool+exactlyBalanced entries = exactTotal (decL entries) == exactTotal (decR entries)++-- | Every posting as a base and value pair, in a canonical order.+postingList :: (HatVal v, HatBaseClass b, Ord v, Ord b) => Alg v b -> [(b, v)]+postingList = sort . foldEntries (\result value source -> (source, value) : result) []++-- | Concrete account titles; the wildcard 'AccountTitle' is excluded.+concreteTitles :: [AccountTitles]+concreteTitles = [title | title <- [minBound .. maxBound], title /= AccountTitle]++-- | Run 200 QuickCheck cases, reporting failures through the suite convention.+quickProperty :: Testable property => String -> property -> IO ()+quickProperty label proposition = do+ result <- quickCheckWithResult stdArgs { maxSuccess = 200, chatty = False } proposition+ unless (isSuccess result) $ do+ putStrLn ("[FAIL] " ++ label ++ ": " ++ output result)+ exitFailure+ putStrLn ("[PASS] " ++ label)++-- | Decimal fractions, integers and a large binary magnitude.+genValue :: HatVal v => Gen v+genValue = oneof+ [ fromInteger <$> chooseInteger (1, 1000000)+ , elements [0.1, 0.2, 0.3, 1.5, 2 ^ (53 :: Int)]+ ]++-- * Closing laws++-- | Accounts that 'closingEntries' closes.+closingTitles :: [AccountTitles]+closingTitles = filter (isJust . closingSide) concreteTitles++-- | Accounts that 'closingEntries' does not close, including 'RetainedEarnings'.+openTitles :: [AccountTitles]+openTitles = filter (isNothing . closingSide) concreteTitles++-- | A ledger over every closing and non-closing account, in two units.+genClosingLedger :: HatVal v => Gen (Alg v UnitBase)+genClosingLedger = do+ count <- chooseInt (0, 30)+ postings <- vectorOf count $ do+ value <- genValue+ side <- elements [Hat, Not]+ unit <- elements [Yen, Dollar]+ title <- frequency [(3, elements closingTitles), (2, elements openTitles)]+ pure (value .@ side :< (unit, title))+ pure (mconcat postings)++-- | CL1-CL4 for one generated ledger.+propClosingLaws :: forall v. HatVal v => Proxy v -> Property+propClosingLaws _ = forAll (genClosingLedger :: Gen (Alg v UnitBase)) $ \ledger ->+ case closingEntries ledger of+ Left failure -> counterexample (show failure) False+ Right entries ->+ let before = exactNets ledger+ after = exactNets (ledger .+ entries)+ netOf nets source = Map.findWithDefault 0 source nets+ allBases = Map.keys (Map.union before after)+ titleOf = getAccountTitle+ retainedChange unit =+ let source = Not :< (unit, RetainedEarnings)+ in netOf after source - netOf before source+ periodResult unit = sum+ [ sign * net+ | (source@(_ :< (sourceUnit, _)), net) <- Map.toList before+ , sourceUnit == unit+ , Just side <- [closingSide (titleOf source)]+ , let sign = case side of+ ClosingKeep -> 1+ ClosingFlip -> -1+ ]+ openBase source = isNothing (closingSide (titleOf source))+ && titleOf source /= RetainedEarnings+ in conjoin+ [ counterexample "CL1 balance" (exactlyBalanced entries)+ , counterexample "CL2 closure" $+ all (\source -> netOf after source == 0)+ [source | source <- allBases, isJust (closingSide (titleOf source))]+ , counterexample "CL3 retention" $+ all (\source -> netOf after source == netOf before source)+ (filter openBase allBases)+ && not (any openBase (postingBases entries))+ , counterexample "CL4 period result" $+ all (\unit -> retainedChange unit == periodResult unit) [Yen, Dollar]+ ]+ where+ postingBases :: Alg v UnitBase -> [UnitBase]+ postingBases = foldEntries (\result _ source -> source : result) []++-- * Consolidation laws++-- | Single-axis base used by the consolidation worksheet.+type TitleBase = HatBase AccountTitles++-- | Accounts admitted in a consolidation worksheet adjustment.+adjustmentTitles :: [AccountTitles]+adjustmentTitles =+ filter (postingAllowedIn ConsolidationWorksheet . postingCapabilityFor) concreteTitles++-- | A balanced element: each pair debits one account and credits another by+-- the same amount.+genBalanced :: HatVal v => [AccountTitles] -> Gen (Alg v TitleBase)+genBalanced titles = do+ count <- chooseInt (1, 6)+ pairs <- vectorOf count $ do+ value <- genValue+ debit <- elements titles+ credit <- elements titles+ pure [(Debit, debit, value), (Credit, credit, value)]+ pure (journalForSides (concat pairs))++-- | A linkage with no period result, dividends or balances. The linkage checks+-- caller-supplied statement columns and does not read the algebra:+-- @validateWorksheetLinkage@ in "ExchangeAlgebra.Accounting.Consolidation"+-- takes only the 'CW.WorksheetLinkage' value.+emptyLinkage :: HatVal v => CW.WorksheetLinkage v+emptyLinkage = CW.WorksheetLinkage+ RM.PeriodBreakEven RM.PeriodBreakEven RM.PeriodBreakEven+ TBB.NoBalance 0 TBB.NoBalance TBB.NoBalance+ TBB.NoBalance RM.PeriodBreakEven 0 TBB.NoBalance TBB.NoBalance++-- | Balanced sources with distinct identifiers and balanced adjustments that+-- reference distinct known sources.+genWorksheet :: HatVal v => Gen (CW.WorksheetInput Int Int v)+genWorksheet = do+ sourceCount <- chooseInt (1, 4)+ sources <- mapM (\sourceId -> CW.TrialBalanceSource sourceId <$> genBalanced concreteTitles)+ [0 .. sourceCount - 1]+ adjustmentCount <- chooseInt (0, 4)+ adjustments <- mapM (genAdjustment sourceCount) [0 .. adjustmentCount - 1]+ pure (CW.WorksheetInput (NE.fromList sources) adjustments emptyLinkage)+ where+ genAdjustment sourceCount adjustmentId = do+ first <- chooseInt (0, sourceCount - 1)+ others <- sublistOf [sourceId | sourceId <- [0 .. sourceCount - 1], sourceId /= first]+ element <- genBalanced adjustmentTitles+ pure (CW.WorksheetAdjustment adjustmentId (first NE.:| others) element)++-- | Sum of the inputs in reverse order, independent of 'CW.combinedWorksheet'.+reverseSum :: HatVal v => CW.WorksheetInput Int Int v -> Alg v TitleBase+reverseSum input = foldr (flip (.+)) mempty+ ( map CW._sourceTrialBalance (NE.toList (CW._worksheetSources input))+ ++ map CW._adjustmentElement (CW._worksheetAdjustments input) )++-- | CW1 and CW2 for one generated worksheet.+propWorksheetLaws :: forall v. (HatVal v, Ord v) => Proxy v -> Property+propWorksheetLaws _ = forAll (genWorksheet :: Gen (CW.WorksheetInput Int Int v)) $ \input ->+ case CW.validateConsolidationWorksheet input of+ Left failures -> counterexample ("CW1 validation " ++ show failures) False+ Right validated ->+ let combined = CW.combinedWorksheet validated+ oracle = reverseSum input+ in conjoin+ [ counterexample "CW1 balance" (exactlyBalanced combined)+ , counterexample "CW2 exact net" (exactNets combined == exactNets oracle)+ , counterexample "CW2 postings kept" (postingList combined == postingList oracle)+ ]++-- | CW3: one unbalanced adjustment or source is rejected by name.+propWorksheetRejection :: forall v. HatVal v => Proxy v -> Property+propWorksheetRejection _ =+ forAll (genWorksheet :: Gen (CW.WorksheetInput Int Int v)) $ \input ->+ forAll genValue $ \(value :: v) ->+ forAll (elements adjustmentTitles) $ \title ->+ forAll (chooseInt (0, NE.length (CW._worksheetSources input) - 1)) $ \target ->+ let unbalanced = journalForSides [(Debit, title, value), (Credit, title, value + value)]+ badId = length (CW._worksheetAdjustments input)+ badAdjustment = CW.WorksheetAdjustment badId (0 NE.:| []) unbalanced+ withAdjustment = input+ { CW._worksheetAdjustments = CW._worksheetAdjustments input ++ [badAdjustment] }+ replaceSource source+ | CW._sourceId source == target = source+ { CW._sourceTrialBalance = CW._sourceTrialBalance source .+ unbalanced }+ | otherwise = source+ withSource = input+ { CW._worksheetSources = NE.map replaceSource (CW._worksheetSources input) }+ names predicate result = case result of+ Left failures -> any predicate (NE.toList failures)+ Right _ -> False+ adjustmentNamed failure = case failure of+ CW.UnbalancedAdjustment adjustmentId _ _ -> adjustmentId == badId+ _ -> False+ sourceNamed failure = case failure of+ CW.UnbalancedSourceTrialBalance sourceId _ _ -> sourceId == target+ _ -> False+ in conjoin+ [ counterexample "CW3 unbalanced adjustment"+ (names adjustmentNamed (CW.validateConsolidationWorksheet withAdjustment))+ , counterexample "CW3 unbalanced source"+ (names sourceNamed (CW.validateConsolidationWorksheet withSource))+ ]++-- | Register the closing and consolidation laws in ExchangeAlgebra-test.+runTests :: IO ()+runTests = do+ quickProperty "CL1-CL4 Double" (propClosingLaws (Proxy :: Proxy Double))+ quickProperty "CL1-CL4 MoneyDecimal" (propClosingLaws (Proxy :: Proxy MoneyDecimal))+ quickProperty "CW1-CW2 Double" (propWorksheetLaws (Proxy :: Proxy Double))+ quickProperty "CW1-CW2 MoneyDecimal" (propWorksheetLaws (Proxy :: Proxy MoneyDecimal))+ quickProperty "CW3 Double" (propWorksheetRejection (Proxy :: Proxy Double))+ quickProperty "CW3 MoneyDecimal" (propWorksheetRejection (Proxy :: Proxy MoneyDecimal))
test/Accounting/RegistrySpec.hs view
@@ -14,6 +14,7 @@ import qualified ExchangeAlgebra.Accounting.Consolidation as CW import ExchangeAlgebra.Accounting.Closing (ClosingSide(..), closingSide) import qualified ExchangeAlgebra.Accounting.TrialBalance.Balance as TBB+import qualified ExchangeAlgebra.Accounting.Audit as Audit import qualified ExchangeAlgebra.Accounting.TrialBalance.Validation as TB import qualified ExchangeAlgebra.Accounting.Statements.Presentation as RP import qualified ExchangeAlgebra.Accounting.Statements.Metric as RM@@ -61,18 +62,27 @@ Left (_, _, message) -> Left message Right (_, _, title) -> Right title +-- | The wire fixture pins the bytes of each surviving title. Keep retired+-- codes reserved. Version 0.7.0.0 stopped pinning derived Enum ordinals+-- because removing a title shifts the ordinals of later constructors. testAccountTitlesBinary :: IO () testAccountTitlesBinary = do let titles = [minBound .. maxBound] :: [AccountTitles] roundTripped = L.map (Binary.decode . Binary.encode) titles codes = L.map (BinaryGet.runGet BinaryGet.getWord16be . Binary.encode) titles- invalidCodes = [0x0000, 0x0001, 0x00F2, 0x7FFF, 0x8000 + fromIntegral (length titles)]+ retiredCodes = [0x8023] -- Commutation+ invalidCodes = [0x0000, 0x0001, 0x00F2, 0x7FFF, 0x80F4] ++ retiredCodes assertEqual "AccountTitles Binary covers all 244 constructors" 244 (L.length titles) assertEqual "AccountTitles Binary Word16be roundtrip" titles roundTripped assertEqual "B4 AccountTitles codes are injective" 244 (Set.size (Set.fromList codes))+ assertEqual "B4 AccountTitles codes exclude retired codes"+ Set.empty (Set.intersection (Set.fromList retiredCodes) (Set.fromList codes)) assertEqual "B4 AccountTitles codes carry the version bit" True (all (>= 0x8000) codes)+ assertEqual "AccountTitles wildcard is maxBound" AccountTitle maxBound+ assertEqual "concreteAccountTitles covers all non-wildcard constructors"+ (L.filter (/= AccountTitle) titles) Registry.concreteAccountTitles assertEqual "B4 wildcard code is fixed" (BinaryPut.runPut (BinaryPut.putWord16be 0xFFFF)) (Binary.encode AccountTitle) forM_ invalidCodes $ \code ->@@ -81,6 +91,17 @@ Left _ -> True Right _ -> False) +-- | Check that each concrete account title has a distinct English name.+testUniqueEnglishAccountNames :: IO ()+testUniqueEnglishAccountNames = do+ let names = M.fromListWith (++)+ [ (Registry.asNameEn spec, [title])+ | title <- Registry.concreteAccountTitles+ , Just spec <- [Registry.accountSpec title]+ ]+ duplicates = M.toList (M.filter ((> 1) . L.length) names)+ assertEqual "concrete account titles have unique English names" [] duplicates+ -- | Check the appended allowances and the additional Japanese aliases. testAllowanceAccountTitles :: IO () testAllowanceAccountTitles = do@@ -151,7 +172,6 @@ , (AmortizationExpense, Cost, Debit, Other) , (SalesCost, Cost, Debit, Other) , (BusinessTrip, Cost, Debit, Other)- , (Commutation, Cost, Debit, Other) , (UtilitiesExpense, Cost, Debit, Other) , (RentExpense, Cost, Debit, Other) , (AdvertisingExpense, Cost, Debit, Other)@@ -369,6 +389,7 @@ , (GoodsInTransit, Assets, Debit, Current) , (SalesAllowances, Revenue, Debit, Other) , (PurchaseAllowances, Cost, Credit, Other)+ , (DirectorsCompensations, Cost, Debit, Other) ] testAccountTitleClassification :: IO ()@@ -428,76 +449,6 @@ div_ = classifyAccountDivision t contra = Registry.classifyAccountContra t --- ================================================================--- V-Land 2 scaffolding (語彙拡張の受理条件, レビュー非依存):--- pre-vland2 fixture (tools/DumpVocabGolden.hs で生成, commit 85d6a7f に pin)--- に対する Enum 挿入規律 pin と意味関数 closed-diff。--- ================================================================---- | 挿入規律 pin: 語彙拡張は「既存 concrete constructor の Enum 序数を 1 つも--- 動かさず, 新規は最大既存 concrete 序数と wildcard の間にのみ挿入し,--- wildcard ('AccountTitle') は maxBound のまま」でなければならない--- (Binary Word16 直列化互換と既存 fixture 世代の解釈可能性の要)。-testVocabOrdinalPin :: IO ()-testVocabOrdinalPin = do- fixture <- TIO.readFile "test/fixtures/pre-vland2/ordinals.tsv"- let parseOrd line = case T.splitOn (T.pack "\t") line of- [name, ordText] -> (name, read (T.unpack ordText) :: Int)- fields -> error ("invalid pre-vland2 ordinals row: " ++ show fields)- rows =- [ parseOrd line- | line <- T.lines fixture- , not (T.null line)- , not (T.isPrefixOf (T.pack "#") line)- ]- current = M.fromList- [ (T.pack (show t), fromEnum t)- | t <- [minBound .. maxBound] :: [AccountTitles] ]- wildcardName = T.pack (show (AccountTitle :: AccountTitles))- pinnedConcrete = [ r | r@(n, _) <- rows, n /= wildcardName ]- moved =- [ (n, o, M.lookup n current)- | (n, o) <- pinnedConcrete- , M.lookup n current /= Just o ]- assertEqual "vocab ordinal pin: fixture rows = 117 (116 concrete + wildcard)"- 117 (L.length rows)- assertEqual "vocab ordinal pin: no pinned concrete ordinal moved" [] moved- assertEqual "vocab ordinal pin: wildcard is maxBound"- (fromEnum (maxBound :: AccountTitles))- (fromEnum (AccountTitle :: AccountTitles))- let maxPinned = L.maximum [ o | (_, o) <- pinnedConcrete ]- pinnedNames = M.fromList [ (n, ()) | (n, _) <- rows ]- misplaced =- [ (n, o)- | (n, o) <- M.toList current- , not (M.member n pinnedNames)- , not (o > maxPinned && o < fromEnum (maxBound :: AccountTitles)) ]- assertEqual "vocab ordinal pin: new constructors sit between max pinned and wildcard"- [] misplaced- assertEqual "vocab ordinal pin: appended constructor ordinals and wildcard"- [232..243]- (L.map fromEnum- [ ConsumptionTaxRefundReceivable- , PropertyTaxPayable- , DepositsReceivedFromOfficers- , EntertainmentExpenses- , MeetingExpenses- , NewspaperBooksExpenses- , RawMaterials- , GoodsInTransit- , SalesAllowances- , PurchaseAllowances- , ReversalOfAllowanceForBonuses- , AccountTitle- ])- -- concreteAccountTitles は wildcard 以外の全 constructor を被覆すること。- -- 現行の hardcoded 上限 ([Cash .. ReversalOfAllowanceForDoubtfulAccounts]) は- -- 挿入後に新規科目が漏れるため, この assert が V-Land 2 に- -- filter (/= wildcard) [minBound ..] への導出化を強制する。- assertEqual "vocab ordinal pin: concreteAccountTitles covers all non-wildcard constructors"- (L.filter (/= (AccountTitle :: AccountTitles)) [minBound .. maxBound])- Registry.concreteAccountTitles- testAssistAllAccountInfos :: IO () testAssistAllAccountInfos = do assertEqual "Assist.allAccountInfos length" 243 (length Assist.allAccountInfos)@@ -673,10 +624,8 @@ testAccountSemanticsGolden :: IO () testAccountSemanticsGolden = do- metadata <- TIO.readFile "test/fixtures/account-semantics-050/metadata.tsv"- info <- TIO.readFile "test/fixtures/account-semantics-050/account-info.tsv"- suggest <- TIO.readFile "test/fixtures/account-semantics-050/suggest.tsv"- let expectedMetadata =+ let dir = "test/fixtures/account-semantics-050/"+ expectedMetadata = accountRegistryHeader (T.pack "registry (title, roles, posting, divisionSemantics, homeSideSemantics, reportingEligibility)") <> T.unlines (L.map accountRegistryRow Registry.concreteAccountTitles)@@ -684,12 +633,12 @@ accountRegistryHeader (T.pack "LLM AccountInfo (title, roles, posting, divisionSemantics, homeSideSemantics, reportingEligibility, nameEn, nameJa, description)") <> T.unlines (L.map accountRegistryInfoRow Assist.allAccountInfos)+ goldenCheck "metadata fixture" (dir ++ "metadata.tsv") expectedMetadata+ goldenCheck "LLM AccountInfo fixture" (dir ++ "account-info.tsv") expectedInfo+ goldenCheck "LLM suggestion fixture" (dir ++ "suggest.tsv") accountRegistrySuggestions+ metadata <- TIO.readFile (dir ++ "metadata.tsv") assertEqual "metadata fixture has 243 rows" 243 (L.length (L.drop 1 (T.lines metadata)))- assertEqual "metadata fixture" metadata expectedMetadata- assertEqual "LLM AccountInfo fixture" info expectedInfo- assertEqual "LLM suggestion fixture"- suggest accountRegistrySuggestions testAssistSuggestAccounts :: IO () testAssistSuggestAccounts = do@@ -811,14 +760,6 @@ Just spec -> T.words (Registry.asDescription spec) Nothing -> [] -postVocabOrdinalsGolden :: T.Text-postVocabOrdinalsGolden =- postVocabHeader (T.pack "Enum ordinals (constructor, fromEnum)")- <> T.unlines- [ goldenShow title <> T.pack "\t" <> goldenShow (fromEnum title)- | title <- [minBound .. maxBound] :: [AccountTitles]- ]- postVocabSemanticsGolden :: T.Text postVocabSemanticsGolden = postVocabHeader (T.pack "semantics (title, whatDiv, isContra, whichSide Not, whichSide Hat, whatPIMO, fixedCurrent, finalStockProbe)")@@ -840,15 +781,12 @@ testPostVocabGolden :: IO () testPostVocabGolden = do- ordinals <- TIO.readFile "test/fixtures/post-vocab/ordinals.tsv"- semantics <- TIO.readFile "test/fixtures/post-vocab/semantics.tsv"- info <- TIO.readFile "test/fixtures/post-vocab/account-info.tsv"- suggestions <- TIO.readFile "test/fixtures/post-vocab/suggest.tsv"- assertEqual "post-vocab ordinal fixture" ordinals postVocabOrdinalsGolden- assertEqual "post-vocab semantics fixture" semantics postVocabSemanticsGolden- assertEqual "post-vocab account-info fixture" info postVocabInfoGolden- assertEqual "post-vocab suggest fixture" suggestions postVocabSuggestionsGolden+ let dir = "test/fixtures/post-vocab/"+ goldenCheck "post-vocab semantics fixture" (dir ++ "semantics.tsv") postVocabSemanticsGolden+ goldenCheck "post-vocab account-info fixture" (dir ++ "account-info.tsv") postVocabInfoGolden+ goldenCheck "post-vocab suggest fixture" (dir ++ "suggest.tsv") postVocabSuggestionsGolden + -- ================================================================ -- Account behavior over every concrete title: closing, projection membership, -- and the one-posting statement rows.@@ -870,7 +808,7 @@ accountSemanticsSemanticsGolden :: T.Text accountSemanticsSemanticsGolden =- accountSemanticsHeader (T.pack "semantics (title, enum, binaryHex, division, closing, isContra, whichSide Not, whichSide Hat, whatPIMO, fixedCurrent, finalStockProbe)")+ accountSemanticsHeader (T.pack "semantics (title, binaryHex, division, closing, isContra, whichSide Not, whichSide Hat, whatPIMO, fixedCurrent, finalStockProbe)") <> T.unlines (L.map row accountSemanticsBaselineTitles) where row title =@@ -881,7 +819,6 @@ Nothing -> error ("missing AccountSpec for " ++ show title) in T.intercalate (T.pack "\t") [ goldenShow title- , goldenShow (fromEnum title) , accountSemanticsBinaryHex title , goldenShow (Registry.asDivision spec) , goldenShow (Registry.asClosing spec)@@ -913,7 +850,7 @@ , kept Exchange.projDeferredAssets value , kept Exchange.projCurrentLiability value , kept Exchange.projFixedLiability value- , kept Exchange.projCapitalStock value+ , kept Exchange.projNonContraCreditEquity value , kept Exchange.projContraAssets value , kept Exchange.projContra value ]@@ -1000,9 +937,12 @@ testAliasResolutionGolden :: IO () testAliasResolutionGolden = do let path = "test/fixtures/registry-aliases/alias-resolution.tsv"+ assertEqual "directors remuneration parses without changing wages or directors bonuses"+ (L.map Right [DirectorsCompensations, WageExpenditure, Bonuses])+ (L.map EC.parseAccountTitle [T.pack "役員報酬", T.pack "給料", T.pack "役員賞与"]) aliases <- TIO.readFile path assertEqual "alias resolution golden: query count"- 703 (L.length (L.filter (not . T.null) (L.drop 1 (T.lines aliases))))+ 699 (L.length (L.filter (not . T.null) (L.drop 1 (T.lines aliases)))) goldenCheck "alias resolution golden" path (goldenAliasResolution aliases) -- | JCCI 2022 A欄/B欄の全 distinct query は, 一意のRightかfixtureで候補を@@ -1051,8 +991,8 @@ assertEqual "JCCI distinct normalized A/B query count" 316 (L.length rows) assertEqual "JCCI fixture covers exactly the source A/B labels" sourceLabels fixtureLabels- assertEqual "JCCI unique resolutions" 295 (L.length (L.filter (== T.pack "right") outcomes))- assertEqual "JCCI policy ambiguities" 21 (L.length (L.filter (== T.pack "ambiguous") outcomes))+ assertEqual "JCCI unique resolutions" 296 (L.length (L.filter (== T.pack "right") outcomes))+ assertEqual "JCCI policy ambiguities" 20 (L.length (L.filter (== T.pack "ambiguous") outcomes)) forM_ rows $ \row -> case T.splitOn (T.pack "\t") row of [_, _, _, query, _, _, standardNames] -> assertEqual ("JCCI source provenance: " ++ T.unpack query)@@ -1086,11 +1026,8 @@ _ -> assertEqual "JCCI fixture row has seven columns" (7 :: Int) (L.length (T.splitOn (T.pack "\t") row)) --- | Match the generated aliases to the frozen fixture, preserving query order--- and removing duplicates. Additional aliases remain in the account registry.--- The expectation re-implements the rule of @tools/gen-jcci-aliases.py@--- (candidates split on @|@, queries in file order without duplicates); keep--- the two in step when either changes.+-- | Compare fixture and registry alias pairs in both directions, then check+-- that each title's aliases follow the order of first occurrence in the fixture. testJcciAliasesMatchFixture :: IO () testJcciAliasesMatchFixture = do fixture <- TIO.readFile "test/fixtures/jcci-2022/queries.tsv"@@ -1100,15 +1037,24 @@ | row <- rows , [_, _, _, query, _, candidates, _] <- [T.splitOn (T.pack "\t") row] ]+ titles = [minBound .. maxBound] :: [AccountTitles]+ fixturePairs = Set.fromList+ [(candidate, query) | (query, candidates) <- entries, candidate <- candidates]+ registryPairs = Set.fromList+ [(T.pack (show title), alias) | title <- titles, alias <- Registry.jcciAliases title]+ missingPairs = Set.toList (Set.difference fixturePairs registryPairs)+ extraPairs = Set.toList (Set.difference registryPairs fixturePairs) assertEqual "every JCCI fixture row has the seven expected columns" (L.length rows) (L.length entries)- forM_ ([minBound .. maxBound] :: [AccountTitles]) $ \title -> do+ assertEqual "JCCI 2022 alias pairs (missing from registry, extra in registry)"+ ([], []) (missingPairs, extraPairs)+ forM_ titles $ \title -> do let expected = L.nub [ query | (query, candidates) <- entries , T.pack (show title) `L.elem` candidates ]- assertEqual ("JCCI generated aliases: " ++ show title)+ assertEqual ("JCCI 2022 alias order: " ++ show title) expected (Registry.jcciAliases title) forM_ [ (DeliveryExpenses, "荷造運賃")@@ -1246,27 +1192,68 @@ -- isContra のTrue集合が既存評価勘定2件 + V-Land 2 P/L控除3件になること。 testIsContraSweepAcrossBaseInstances :: IO () testIsContraSweepAcrossBaseInstances = do- let day0 = fromGregorian 2026 1 1- tod0 = TimeOfDay 0 0 0+ let day0 = Exactly (fromGregorian 2026 1 1)+ tod0 = Exactly (TimeOfDay 0 0 0) nm = T.pack "spec" sweep :: ExBaseClass b => String -> (AccountTitles -> b) -> IO () sweep label mk = assertEqual ("isContra sweep: " ++ label) allContra [ t | t <- Registry.concreteAccountTitles, isContra (mk t) ] sweep "HatBase AccountTitles" (\t -> Not :< t :: HatBase AccountTitles)- sweep "HatBase (AccountTitles, Day)" (\t -> Not :< (t, day0))+ sweep "HatBase (AccountTitles, Wild Day)" (\t -> Not :< (t, day0)) sweep "HatBase (AccountTitles, Name)" (\t -> Not :< (t, nm)) sweep "HatBase (CountUnit, AccountTitles)" (\t -> Not :< (Yen, t)) sweep "HatBase (AccountTitles, Name, CountUnit)" (\t -> Not :< (t, nm, Yen)) sweep "HatBase (AccountTitles, Name, CountUnit, Subject)" (\t -> Not :< (t, nm, Yen, nm))- sweep "HatBase (AccountTitles, Name, CountUnit, Subject, Day)"+ sweep "HatBase (AccountTitles, Name, CountUnit, Subject, Wild Day)" (\t -> Not :< (t, nm, Yen, nm, day0))- sweep "HatBase (AccountTitles, Name, CountUnit, Subject, Day, TimeOfDay)"+ sweep "HatBase (AccountTitles, Name, CountUnit, Subject, Wild Day, Wild TimeOfDay)" (\t -> Not :< (t, nm, Yen, nm, day0, tod0)) sweep "SimHatBase2 (custom instance)" (\t -> Not :< (t, 1, 2, Yen) :: SimHatBase2) +-- | Check side selection across account-only and custom four-axis bases.+testConstructionForSides :: IO ()+testConstructionForSides = do+ forM_ Registry.concreteAccountTitles $ \title ->+ forM_ [Debit, Credit] $ \side -> do+ let key :: (AccountTitles, Int, Int, CountUnit)+ key = (title, 1, 2, Yen)+ marker :: Hat+ marker = hatForSide side key+ markedBase :: SimHatBase2+ markedBase = marker :< key+ caseLabel = "side construction " ++ show (title, side)+ assertEqual (caseLabel ++ " four-axis marker") (hatForSide side title) marker+ assertEqual (caseLabel ++ " account-only compatibility")+ (EC.markerForSide side title) (hatForSide side title)+ assertEqual (caseLabel ++ " requested side") side (whichSide markedBase)+ let key :: (AccountTitles, Int, Int, CountUnit)+ key = (Cash, 1, 2, Yen)+ otherKey :: (AccountTitles, Int, Int, CountUnit)+ otherKey = (Sales, 2, 1, Dollar)+ journal :: EA.Alg Double SimHatBase2+ journal = journalForSides+ [ (Debit, key, 10)+ , (Debit, key, 20)+ , (Credit, otherKey, 30)+ ]+ observed :: [(SimHatBase2, Double)]+ observed = L.sort [(EA._hatBase entry, EA._val entry) | entry <- EA.toList journal]+ expected :: [(SimHatBase2, Double)]+ expected = L.sort+ [ (Not :< key, 10)+ , (Not :< key, 20)+ , (Not :< otherKey, 30)+ ]+ assertEqual "journalForSides preserves axes and separate repeated postings" expected observed+ assertEqual "journalForSides empty input" (mempty :: EA.Alg Double SimHatBase2)+ (journalForSides [])+ assertEqual "hatForSide wildcard matches markerForSide"+ (EC.markerForSide Side Cash) (hatForSide Side Cash)++ -- | Check that allowance deductions preserve presentations without allowance activity. testPresentationGroupsWithoutAllowances :: IO () testPresentationGroupsWithoutAllowances = do@@ -1532,7 +1519,7 @@ , ("projDeferredAssets", Exchange.projDeferredAssets) , ("projCurrentLiability", Exchange.projCurrentLiability) , ("projFixedLiability", Exchange.projFixedLiability)- , ("projCapitalStock", Exchange.projCapitalStock)+ , ("projNonContraCreditEquity", Exchange.projNonContraCreditEquity) ] testStatementPresentationGolden :: IO ()@@ -1934,18 +1921,6 @@ "unbalanced-source" 10 0 NE.:| [])) (leftErrors (CW.validateConsolidationWorksheet unbalancedSourceInput)) -trialBalanceInput- :: CheckedAlgM- -> TB.TrialBalanceStage- -> TB.TrialBalanceInput MoneyDecimal-trialBalanceInput alg stage = TB.TrialBalanceInput- { TB._trialBalanceElement = alg- , TB._trialBalanceStage = stage- , TB._temporaryBalanceExplanations = M.empty- , TB._reclassificationRules = []- , TB._maturityEvidenceTitles = Set.empty- }- testSharedAccountBalancePrimitives :: IO () testSharedAccountBalancePrimitives = do let balances =@@ -1958,178 +1933,58 @@ assertEqual "account balance: structural sides" [Side, Debit, Credit] (fmap TBB.balanceSide balances) -testTrialBalanceValidation :: IO ()-testTrialBalanceValidation = do+-- | Present standalone reciprocal balances and a supplied maturity split.+testPresentationOfReciprocalAndMaturityBalances :: IO ()+testPresentationOfReciprocalAndMaturityBalances = do let reciprocalMismatch = EC.journalFromSides [ (Debit, BranchCurrentAccount, 40 :: MoneyDecimal) , (Credit, HeadOfficeCurrentAccount, 30) , (Credit, CapitalStock, 10) ] :: CheckedAlgM- reciprocalInput = trialBalanceInput reciprocalMismatch TB.BeforeClosing- expectedReciprocal = TB.ReciprocalMismatch- (TB.DebitBalance 40) (TB.CreditBalance 30)- assertEqual "trial balance: reciprocal mismatch independent of global balance"- (Just (expectedReciprocal NE.:| []))- (NE.nonEmpty (TB.trialBalanceFindings (reciprocalInput)))- let standaloneReciprocal = EC.journalFromSides+ standaloneReciprocal = EC.journalFromSides [ (Debit, BranchCurrentAccount, 40 :: MoneyDecimal) , (Credit, CapitalStock, 40) ] :: CheckedAlgM- standaloneInput = trialBalanceInput standaloneReciprocal TB.BeforeClosing- expectedStandalone = TB.StandaloneReciprocalBalance- BranchCurrentAccount (TB.DebitBalance 40)- assertEqual "trial balance: standalone reciprocal balance is a finding"- [expectedStandalone] (TB.trialBalanceFindings standaloneInput)-- let explainedSuspense = EC.journalFromSides- [ (Debit, SuspensePayments, 10 :: MoneyDecimal)- , (Credit, CapitalStock, 10)- ] :: CheckedAlgM- explanation = T.pack "invoice received after reporting date"- explainedInput = (trialBalanceInput explainedSuspense TB.BeforeClosing)- { TB._temporaryBalanceExplanations =- M.singleton SuspensePayments explanation }- expectedExplained = TB.ExplainedTemporaryBalance SuspensePayments- (TB.DebitBalance 10) explanation- assertEqual "trial balance: explained temporary balance retained"- [expectedExplained] (TB.trialBalanceFindings explainedInput)- let unresolvedInput = trialBalanceInput explainedSuspense TB.BeforeClosing- assertEqual "trial balance: unexplained temporary balance is a finding"- (Just (TB.UnresolvedTemporaryBalance SuspensePayments- (TB.DebitBalance 10) NE.:| []))- (NE.nonEmpty (TB.trialBalanceFindings (unresolvedInput)))- let blankInput = explainedInput- { TB._temporaryBalanceExplanations =- M.singleton SuspensePayments (T.pack " ") }- assertEqual "trial balance: blank explanation is a finding"- (Just (TB.BlankTemporaryExplanation SuspensePayments- (TB.DebitBalance 10) NE.:| []))- (NE.nonEmpty (TB.trialBalanceFindings (blankInput)))-- let closingResidual = EC.journalFromSides- [ (Debit, CashOverShort, 10 :: MoneyDecimal)- , (Credit, IncomeSummary, 10)- ] :: CheckedAlgM- closingInput = trialBalanceInput closingResidual TB.AfterClosing- assertEqual "trial balance: closing devices must be zero after closing"- (Just- ( TB.ClosingDeviceResidual CashOverShort (TB.DebitBalance 10)- NE.:|- [TB.ClosingDeviceResidual IncomeSummary (TB.CreditBalance 10)]- ))- (NE.nonEmpty (TB.trialBalanceFindings (closingInput)))- let unclosedNominal = EC.journalFromSides- [ (Debit, Cash, 10 :: MoneyDecimal)- , (Credit, Sales, 10)- ] :: CheckedAlgM- assertEqual "trial balance: nominal balances must close after closing"- (Just (TB.UnclosedNominalBalance Sales- (TB.CreditBalance 10) NE.:| []))- (NE.nonEmpty (TB.trialBalanceFindings ((trialBalanceInput unclosedNominal TB.AfterClosing))))-- let derivedResidual = EC.journalFromSides- [ (Debit, NetIncome, 10 :: MoneyDecimal)- , (Credit, CapitalStock, 10)- ] :: CheckedAlgM- assertEqual "trial balance: derived coordinates are residuals after closing"- (Just (TB.DerivedCoordinateResidual NetIncome- (TB.DebitBalance 10) NE.:| []))- (NE.nonEmpty (TB.trialBalanceFindings ((trialBalanceInput derivedResidual TB.AfterClosing))))-- let abnormalDeposit = EC.journalFromSides- [ (Debit, Cash, 10 :: MoneyDecimal)- , (Credit, CurrentDeposits, 10)- ] :: CheckedAlgM- abnormalInput = trialBalanceInput abnormalDeposit TB.BeforeClosing- oneRule = TB.SideReclassificationRule CurrentDeposits Credit- (ShortTermLoansPayable NE.:| [])- twoRules = TB.SideReclassificationRule CurrentDeposits Credit- (BankOverdraft NE.:| [ShortTermLoansPayable])- assertEqual "trial balance: unexplained abnormal side is explicit"- (Just (TB.UnexplainedAbnormalBalance CurrentDeposits Debit- (TB.CreditBalance 10) NE.:| []))- (NE.nonEmpty (TB.trialBalanceFindings (abnormalInput)))- assertEqual "trial balance: unique reclassification is an instruction"- (Just (TB.AbnormalBalanceWithReclassificationRule CurrentDeposits- (TB.CreditBalance 10) ShortTermLoansPayable NE.:| []))- (NE.nonEmpty (TB.trialBalanceFindings (abnormalInput { TB._reclassificationRules = [oneRule] })))- assertEqual "trial balance: ambiguous reclassification is never automatic"- (Just (TB.AmbiguousReclassification CurrentDeposits- (TB.CreditBalance 10)- (BankOverdraft NE.:| [ShortTermLoansPayable]) NE.:| []))- (NE.nonEmpty (TB.trialBalanceFindings (abnormalInput { TB._reclassificationRules = [twoRules] })))-- let recordedTransfer = EC.journalFromSides- [ (Debit, CurrentDeposits, 10 :: MoneyDecimal)- , (Credit, ShortTermLoansPayable, 10)- ] :: CheckedAlgM- transferred = abnormalDeposit .+ recordedTransfer- transferredInput = (trialBalanceInput transferred TB.BeforeClosing)- { TB._reclassificationRules = [oneRule] }- assertEqual "trial balance: recorded transfer clears abnormal finding"- [] (TB.trialBalanceFindings transferredInput)-- let invalidRule = TB.SideReclassificationRule CashOverShort Credit- (MiscellaneousIncome NE.:| [])- invalidRuleInput = (trialBalanceInput mempty TB.BeforeClosing)- { TB._reclassificationRules = [invalidRule] }- assertEqual "trial balance: inapplicable rules are explicit"- (Just (TB.InapplicableReclassificationRule invalidRule NE.:| []))- (NE.nonEmpty (TB.trialBalanceFindings (invalidRuleInput)))- let deadRule = TB.SideReclassificationRule CurrentDeposits Debit- (Cash NE.:| [])- deadRuleInput = (trialBalanceInput mempty TB.BeforeClosing)- { TB._reclassificationRules = [deadRule] }- assertEqual "trial balance: normal-side trigger is a dead rule"- (Just (TB.InapplicableReclassificationRule deadRule NE.:| []))- (NE.nonEmpty (TB.trialBalanceFindings (deadRuleInput)))-+ context = RP.jcciSecondGradeContext RP.Standalone+ forM_ [reciprocalMismatch, standaloneReciprocal] $ \ledger ->+ assertEqual "standalone presentation accepts reciprocal balances"+ True (case RP.present context TB.BeforeClosing ledger of+ Right _ -> True+ Left _ -> False) let maturityBalance = EC.journalFromSides [ (Debit, LoansReceivable, 25 :: MoneyDecimal) , (Credit, CapitalStock, 25) ] :: CheckedAlgM- maturityRule = TB.MaturityEvidenceRequired LoansReceivable- missingMaturity = (trialBalanceInput maturityBalance TB.BeforeClosing)- { TB._reclassificationRules = [maturityRule] }- suppliedMaturity = missingMaturity- { TB._maturityEvidenceTitles = Set.singleton LoansReceivable }- assertEqual "trial balance: maturity-sensitive title requires evidence"- (Just (TB.MissingMaturityEvidence LoansReceivable NE.:| []))- (NE.nonEmpty (TB.trialBalanceFindings (missingMaturity)))- assertEqual "trial balance: supplied maturity evidence clears finding"- [] (TB.trialBalanceFindings suppliedMaturity)-- let unbalanced = EC.journalFromSides- [(Debit, Cash, 10 :: MoneyDecimal)] :: CheckedAlgM- unbalancedInput = trialBalanceInput unbalanced TB.BeforeClosing- assertEqual "trial balance: exact global imbalance is a finding"- (Just (TB.UnbalancedTrialBalance 10 0 NE.:| []))- (NE.nonEmpty (TB.trialBalanceFindings (unbalancedInput)))-- let wildcard = 10 `Internal.Single` (HatNot :< Cash) :: CheckedAlgM- wildcardInput = trialBalanceInput wildcard TB.BeforeClosing- assertEqual "trial balance: wildcard side reports without whichSide crash"- (Just (TB.WildcardTrialBalanceSide NE.:| []))- (NE.nonEmpty (TB.trialBalanceFindings (wildcardInput)))-- forM_ [reciprocalInput, standaloneInput, unresolvedInput, blankInput,- explainedInput, abnormalInput,- abnormalInput { TB._reclassificationRules = [oneRule] },- abnormalInput { TB._reclassificationRules = [twoRules] }] $ \input ->- assertEqual "audit findings do not block a presentable trial balance"- True (case RP.present (RP.jcciSecondGradeContext RP.Standalone)- (TB._trialBalanceStage input) (TB._trialBalanceElement input) of- Right _ -> True- Left _ -> False)- let maturityContext = (RP.jcciSecondGradeContext RP.Standalone)+ maturityContext = context { RP._maturitySensitiveTitles = Set.singleton LoansReceivable , RP._presentationAllocations = [RP.PresentationAllocation LoansReceivable 10 15 (T.pack "schedule")] }- assertEqual "missing maturity audit evidence does not block supplied presentation split"+ assertEqual "presentation accepts a supplied maturity split" True (case RP.present maturityContext TB.BeforeClosing maturityBalance of Right _ -> True Left _ -> False) +-- | Observe an overdraft before and after recording a reclassification.+testAbnormalBalanceAfterReclassification :: IO ()+testAbnormalBalanceAfterReclassification = do+ let abnormalDeposit = EC.journalFromSides+ [ (Debit, Cash, 10)+ , (Credit, CurrentDeposits, 10)+ ] :: CheckedAlgM+ recordedTransfer = EC.journalFromSides+ [ (Debit, CurrentDeposits, 10)+ , (Credit, ShortTermLoansPayable, 10)+ ] :: CheckedAlgM+ assertEqual "audit: credit balance on current deposits is abnormal"+ (Audit.Warning (Audit.AbnormalBalance CurrentDeposits Debit+ (TB.CreditBalance 10) NE.:| []))+ (Audit.abnormalBalances abnormalDeposit)+ assertEqual "audit: recorded transfer clears abnormal finding"+ Audit.NoProblem (Audit.abnormalBalances (abnormalDeposit .+ recordedTransfer))++-- | Check the registry roles used for trial balance accounts.+testTrialBalanceAccountRoles :: IO ()+testTrialBalanceAccountRoles = do let titlesFor role = [ title | title <- Registry.concreteAccountTitles@@ -2224,7 +2079,7 @@ True (RP.MaterialityApplied IncomeTaxesRefundReceivable RP.PresentSeparately (TB.DebitBalance 5) rationale `elem` RP._presentationAudit standalone)- assertEqual "reporting: relabel never mutates validated bookkeeping coordinates"+ assertEqual "reporting: renaming never mutates validated bookkeeping coordinates" True (Purchases `elem` basesAccountTitles reportingBalance && SalesCost `notElem` basesAccountTitles reportingBalance)@@ -2237,20 +2092,17 @@ `elem` NE.toList issues Right _ -> False) - let explainedSuspense = EC.journalFromSides+ let suspenseBalance = EC.journalFromSides [ (Debit, SuspensePayments, 10 :: MoneyDecimal) , (Credit, CapitalStock, 10) ] :: CheckedAlgM- explainedInput = (trialBalanceInput explainedSuspense TB.BeforeClosing)- { TB._temporaryBalanceExplanations = M.singleton SuspensePayments- (T.pack "pending invoice") }- assertEqual "reporting: explained temporary finding is separate from presentation"- [TB.ExplainedTemporaryBalance SuspensePayments (TB.DebitBalance 10)- (T.pack "pending invoice")]- (TB.trialBalanceFindings explainedInput)- assertEqual "reporting: combined context presents an explained temporary balance"+ assertEqual "reporting: temporary balance is a separate audit finding"+ (Audit.Warning (Audit.TemporaryAccountBalance SuspensePayments+ (TB.DebitBalance 10) NE.:| []))+ (Audit.temporaryAccountBalances suspenseBalance)+ assertEqual "reporting: combined context presents a temporary balance" True (case RP.present (RP.jcciSecondGradeContext RP.Combined)- TB.BeforeClosing explainedSuspense of+ TB.BeforeClosing suspenseBalance of Left _ -> False Right _ -> True) @@ -2443,10 +2295,12 @@ suspense = EC.journalFromSides [(Debit, SuspensePayments, 10), (Credit, CapitalStock, 10)] :: CheckedAlgM unclosed = ledger 30 20 10 15- forM_ [(deficit, TB.BeforeClosing), (suspense, TB.BeforeClosing),- (unclosed, TB.AfterClosing)] $ \(alg, stage) -> do- assertEqual "D1 law 4: accounting finding remains observable" True- (not (null (TB.trialBalanceFindings (trialBalanceInput alg stage))))+ forM_+ [ (deficit, TB.BeforeClosing, Audit.abnormalBalances deficit /= Audit.NoProblem)+ , (suspense, TB.BeforeClosing, Audit.temporaryAccountBalances suspense /= Audit.NoProblem)+ , (unclosed, TB.AfterClosing, Audit.closingResiduals unclosed /= Audit.NoProblem)+ ] $ \(alg, stage, hasFinding) -> do+ assertEqual "D1 law 4: accounting finding remains observable" True hasFinding assertEqual "D1 law 4: accounting finding does not block presentation" True (case RP.present context stage alg of Right _ -> True; Left _ -> False) assertEqual "D1 law 5: deficit keeps equity section and actual debit side"@@ -2536,14 +2390,14 @@ testDerivedMetricsAndLegacyCoordinates :: IO () testDerivedMetricsAndLegacyCoordinates = do- assertEqual "legacy derived-coordinate ordinals and Binary bytes"- [ (NetIncome, 49, T.pack "8031")- , (GrossProfit, 54, T.pack "8036")- , (OrdinaryProfit, 55, T.pack "8037")- , (NetLoss, 64, T.pack "8040")- , (IncomeSummary, 216, T.pack "80d8")+ assertEqual "legacy derived-coordinate Binary bytes"+ [ (NetIncome, T.pack "8031")+ , (GrossProfit, T.pack "8036")+ , (OrdinaryProfit, T.pack "8037")+ , (NetLoss, T.pack "8040")+ , (IncomeSummary, T.pack "80d8") ]- [ (title, fromEnum title, accountSemanticsBinaryHex title)+ [ (title, accountSemanticsBinaryHex title) | title <- [NetIncome, GrossProfit, OrdinaryProfit, NetLoss, IncomeSummary] ] assertEqual "exactly four legacy coordinates map to typed metrics"@@ -2932,10 +2786,6 @@ (TBB.balanceFor Cash (TBB.accountBalances (rejected EA..+ (large EA..@ (Hat :< Cash))))) forM_ [(accepted, True), (rejected, False)] $ \(alg, expected) -> do- assertEqual "trial balance: exact balance findings in both directions" expected- $ null- $ TB.trialBalanceFindings- $ TB.TrialBalanceInput alg TB.BeforeClosing M.empty [] Set.empty assertEqual "consolidation source: exact acceptance in both directions" expected (isRight (worksheet alg [])) assertEqual "consolidation adjustment: exact acceptance in both directions"@@ -2945,9 +2795,6 @@ [(Debit, Cash, large), (Debit, Cash, 1), (Debit, AccountsReceivable, 1), (Credit, CapitalStock, large + 2)] :: EA.Alg Double (HatBase AccountTitles)- assertEqual "trial balance: exact reporting input has no findings" []- $ TB.trialBalanceFindings- $ TB.TrialBalanceInput reportingInput TB.BeforeClosing M.empty [] Set.empty case RP.present context TB.BeforeClosing reportingInput of Left issues -> fail (show issues) Right statements -> assertEqual@@ -2963,16 +2810,12 @@ case RP.present relabeled TB.BeforeClosing reportingInput of Left issues -> fail (show issues) Right statements -> do- assertEqual "presentation relabel rounds combined postings once"+ assertEqual "presentation renaming rounds combined postings once" [large + 2, large + 2] (L.map RP._lineAmount (RP._statementLines statements)) assertEqual "presentation subtotal retains exact transformed balance" [TBB.NoBalance, TBB.DebitBalance (large + 2)] (L.map RP._statementSubtotalBalance (RP._statementSubtotals statements))- assertEqual "trial balance: exact maturity input has no findings" []- $ TB.trialBalanceFindings- $ TB.TrialBalanceInput (entry [large, 1] [large, 1])- TB.BeforeClosing M.empty [] Set.empty forM_ [(1, True), (0, False)] $ \(remainder, expected) -> do let allocated = context { RP._maturitySensitiveTitles = Set.singleton Cash@@ -3012,29 +2855,10 @@ let omitted = EC.journalFromSides [(Debit, Cash, 100), (Credit, CapitalStock, 90), (Credit, CashOverShort, 10)] :: EA.Alg Double (HatBase AccountTitles)- assertEqual "trial balance: omitted balance retains only its explained finding"- [TB.ExplainedTemporaryBalance CashOverShort (TB.CreditBalance 10)- (T.pack "investigation pending")]- $ TB.trialBalanceFindings- $ TB.TrialBalanceInput omitted TB.BeforeClosing- (M.singleton CashOverShort (T.pack "investigation pending")) [] Set.empty assertEqual "presentation reconciles only the rendered balances" (Left (RP.UnpresentableBalance CashOverShort (TB.CreditBalance 10) NE.:| [RP.UnreconciledPresentation 100 90])) (fmap (const ()) (RP.present context TB.BeforeClosing omitted))- let reciprocal branchAmounts headAmounts = EC.journalFromSides- ([(Debit, BranchCurrentAccount, value) | value <- branchAmounts]- ++ [(Credit, HeadOfficeCurrentAccount, value) | value <- headAmounts])- :: EA.Alg Double (HatBase AccountTitles)- assertEqual "reciprocal comparison finds no mismatch for exact equal sums" []- $ TB.trialBalanceFindings- $ TB.TrialBalanceInput (reciprocal [large, 1, 1] [large + 2])- TB.BeforeClosing M.empty [] Set.empty- let mismatch = reciprocal [large, 1] [large]- EA..+ (1 EA..@ (Not :< CapitalStock))- assertEqual "reciprocal comparison rejects rounded equal sums"- True (any isReciprocal (TB.trialBalanceFindings- (TB.TrialBalanceInput mismatch TB.BeforeClosing M.empty [] Set.empty))) let offset = EC.journalFromSides [(Debit, Cash, large), (Debit, Cash, 1), (Credit, Cash, large)] :: EA.Alg Double (HatBase AccountTitles)@@ -3045,9 +2869,6 @@ assertEqual "post-closing trial balance keeps exact net one" [T.pack "1.0", T.pack "Cash", T.pack ""] (concat (take 1 (drop 1 (EW.postClosingTrialBalanceRows offset))))- where- isReciprocal TB.ReciprocalMismatch{} = True- isReciprocal _ = False -- | Keep the default BS groups independent of the closing transfer. testBalanceSheetGroupsStayUnclosed :: IO ()@@ -3081,10 +2902,10 @@ testBalanceSheetGroupsStayUnclosed testWriterNaNDirections testAccountTitlesBinary+ testUniqueEnglishAccountNames testAllowanceAccountTitles testAccountTitleClassification testFinalStockRuleReference- testVocabOrdinalPin testAssistAllAccountInfos testAccountSemanticsRegistryInvariants testAccountSemanticsGolden@@ -3104,6 +2925,7 @@ testPimoFlipInvolution testExchangeRelationProp538 testIsContraSweepAcrossBaseInstances+ testConstructionForSides testPresentationGroups testPresentationGroupsWithoutAllowances testStatementContraAssetsLiteral@@ -3111,7 +2933,9 @@ testWhichSideHatNotErrors testConsolidationWorksheet testSharedAccountBalancePrimitives- testTrialBalanceValidation+ testPresentationOfReciprocalAndMaturityBalances+ testAbnormalBalanceAfterReclassification+ testTrialBalanceAccountRoles testReportingPresentation testStatementLaws testDerivedMetricsAndLegacyCoordinates
+ test/Accounting/VocabularyLawSpec.hs view
@@ -0,0 +1,705 @@+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeFamilies #-}++-- | Exact observations under vocabulary renaming, including presentation order.+-- Reversing title order exposes accidental dependence on built-in account order.+module Accounting.VocabularyLawSpec (runTests) where++import qualified Accounting.PresentationVocabularySpec as PresentationVocabularySpec+import Control.Monad (forM_)+import Data.Bifunctor (first)+import Data.Maybe (isJust)+import Data.Hashable (Hashable)+import Data.List (sort, sortOn, (\\))+import Data.List.NonEmpty (NonEmpty(..))+import qualified Data.List.NonEmpty as NE+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set+import GHC.Generics (Generic)++import ExchangeAlgebra.Accounting.Account+import ExchangeAlgebra.Accounting.Audit+import ExchangeAlgebra.Accounting.Exchange (ExBaseClass(..))+import qualified ExchangeAlgebra.Accounting.Statements.Group as G+import qualified ExchangeAlgebra.Accounting.Statements.Presentation as P+import ExchangeAlgebra.Accounting.TrialBalance.Validation (TrialBalanceStage(..))+import qualified ExchangeAlgebra.Accounting.Statements.Metric as Metric+import ExchangeAlgebra.Accounting.Transfer+import ExchangeAlgebra.Accounting.TrialBalance.Balance+import ExchangeAlgebra.Algebra.Base+ ( HasElementKeys+ , BaseClass+ , CountUnit(..)+ , Element(..)+ , Hat(..)+ , HatBase(..)+ )+import ExchangeAlgebra.Algebra.Core (Alg, Redundant(..), (.@), foldEntries)+import qualified ExchangeAlgebra.Algebra.Internal as Internal+import ExchangeAlgebra.Algebra.Value+ ( HatVal+ , MoneyDecimal+ , Rounding(..)+ , ValueError(..)+ )+import qualified ExchangeAlgebra.Journal.Core as Journal+import Support (assertEqual, quickProp)+import Test.QuickCheck+ ( Gen+ , Property+ , chooseInt+ , conjoin+ , elements+ , forAll+ , vectorOf+ , (===)+ )++-- | An injective copy of the built-in vocabulary with the opposite total order.+newtype ReverseTitle = ReverseTitle AccountTitles+ deriving (Eq, Show, Generic)++instance Ord ReverseTitle where+ compare (ReverseTitle left) (ReverseTitle right) = compare right left++instance Hashable ReverseTitle+instance Element ReverseTitle where+ wildcard = ReverseTitle AccountTitle+instance BaseClass ReverseTitle++instance AccountVocabulary ReverseTitle where+ vocabSpec (ReverseTitle title) = vocabSpec title+ vocabSemantics (ReverseTitle title) = vocabSemantics title+ vocabReciprocalPairs = [(ReverseTitle l, ReverseTitle r) | (l, r) <- vocabReciprocalPairs]+ closingTarget = ReverseTitle (closingTarget :: AccountTitles)+ vocabImpossibleBalanceSides = map (first ReverseTitle)+ (vocabImpossibleBalanceSides :: [(AccountTitles, Side)])+ vocabSuspenseTitles = map ReverseTitle (vocabSuspenseTitles :: [AccountTitles])+ vocabAdditionalClosingResidualTitles = map ReverseTitle+ (vocabAdditionalClosingResidualTitles :: [AccountTitles])++instance ExBaseClass (HatBase ReverseTitle) where+ type TitleOf (HatBase ReverseTitle) = ReverseTitle+ getAccountTitle (_ :< title) = title+ setAccountTitle (side :< _) title = side :< title++-- | Two unit coordinates let one transfer row select multiple ordered bases.+instance ExBaseClass (HatBase (ReverseTitle, CountUnit)) where+ type TitleOf (HatBase (ReverseTitle, CountUnit)) = ReverseTitle+ getAccountTitle (_ :< (title, _)) = title+ setAccountTitle (side :< (_, unit)) title = side :< (title, unit)++-- | A complete vocabulary that intentionally omits all three audit tables.+newtype DefaultTitle = DefaultTitle AccountTitles+ deriving (Eq, Ord, Show, Generic)++instance Hashable DefaultTitle+instance Element DefaultTitle where+ wildcard = DefaultTitle AccountTitle+instance BaseClass DefaultTitle++instance AccountVocabulary DefaultTitle where+ vocabSpec (DefaultTitle title) = vocabSpec title+ vocabSemantics (DefaultTitle title) = vocabSemantics title+ closingTarget = DefaultTitle RetainedEarnings++instance ExBaseClass (HatBase DefaultTitle) where+ type TitleOf (HatBase DefaultTitle) = DefaultTitle+ getAccountTitle (_ :< title) = title+ setAccountTitle (side :< _) title = side :< title++-- | A dedicated residual account with a specification but no semantics.+newtype ExtraTitle = ExtraTitle AccountTitles+ deriving (Eq, Ord, Show, Generic)++instance Hashable ExtraTitle+instance Element ExtraTitle where+ wildcard = ExtraTitle AccountTitle+instance BaseClass ExtraTitle++instance AccountVocabulary ExtraTitle where+ vocabSpec (ExtraTitle title) = vocabSpec title+ closingTarget = ExtraTitle RetainedEarnings+ vocabAdditionalClosingResidualTitles = [ExtraTitle CashOverShort]++instance ExBaseClass (HatBase ExtraTitle) where+ type TitleOf (HatBase ExtraTitle) = ExtraTitle+ getAccountTitle (_ :< title) = title+ setAccountTitle (side :< _) title = side :< title++-- | Concrete titles only; wildcard fixtures are constructed separately.+concreteTitles :: [AccountTitles]+concreteTitles = filter (/= AccountTitle) [minBound .. maxBound]++-- | Rename a complete base while preserving its Hat/Not direction.+renameBase :: BaseClass b => (a -> b) -> HatBase a -> HatBase b+renameBase rename (side :< title) = side :< rename title++-- | Construct normal fixtures through the checked posting constructor.+validLedger :: (HatVal v, BaseClass t, HasElementKeys t) => [(v, Hat, t)] -> Alg v (HatBase t)+validLedger = mconcat . map (\(value, side, title) -> value .@ side :< title)++-- | Admit deliberately invalid fixtures from a shared raw posting list.+-- No renaming operation is allowed to validate, drop, or aggregate invalid terms.+rawLedger :: (HatVal v, BaseClass t, HasElementKeys t) => [(v, Hat, t)] -> Alg v (HatBase t)+rawLedger = mconcat . map (\(value, side, title) -> Internal.Single value (side :< title))++-- | Rename the raw coordinates before constructing the algebra.+renameRows :: (a -> b) -> [(v, Hat, a)] -> [(v, Hat, b)]+renameRows rename = map (\(value, side, title) -> (value, side, rename title))++-- | Multiset observation retaining values, full bases, sides, and duplicates.+postings :: (HatVal v, Ord v, BaseClass t, HasElementKeys t)+ => Alg v (HatBase t)+ -> [(HatBase t, v)]+postings = sort . foldEntries (\rows value source -> (source, value) : rows) []++-- | Reorder findings in the target vocabulary without changing severity or count.+mapAudit+ :: forall s s' f f'. (s -> s')+ -> (f -> f')+ -> (s' -> s' -> Ordering)+ -> (f' -> f' -> Ordering)+ -> AuditResult s f+ -> AuditResult s' f'+mapAudit structure finding compareStructure compareFinding result = case result of+ NoProblem -> NoProblem+ Warning findings -> Warning (NE.sortBy compareFinding (fmap finding findings))+ Error findings -> Error (NE.sortBy compareBoth (fmap rename findings))+ where+ rename :: Finding s f -> Finding s' f'+ rename (StructureFinding issue) = StructureFinding (structure issue)+ rename (AccountingFinding item) = AccountingFinding (finding item)+ compareBoth :: Finding s' f' -> Finding s' f' -> Ordering+ compareBoth (StructureFinding left) (StructureFinding right) = compareStructure left right+ compareBoth (AccountingFinding left) (AccountingFinding right) = compareFinding left right+ compareBoth (StructureFinding _) (AccountingFinding _) = LT+ compareBoth (AccountingFinding _) (StructureFinding _) = GT++-- | Rename each issue without collapsing repeated wildcard findings.+renameIssue+ :: BaseClass b+ => (a -> b)+ -> StructureIssue v (HatBase a)+ -> StructureIssue v (HatBase b)+renameIssue rename issue = case issue of+ InvalidValue value source -> InvalidValue value (renameBase rename source)+ WildcardAccount source -> WildcardAccount (renameBase rename source)+ WildcardSide source -> WildcardSide (renameBase rename source)++-- | The public structure order is kind, target base, and value.+issueKey :: StructureIssue Double (HatBase ReverseTitle) -> (Int, HatBase ReverseTitle, Double)+issueKey issue = case issue of+ InvalidValue value source -> (0, source, value)+ WildcardAccount source -> (1, source, 0)+ WildcardSide source -> (2, source, 0)++-- | Compare all four audits after sorting mapped findings in the target order.+checkAudits :: TrialBalance Double -> Alg Double (HatBase ReverseTitle) -> IO ()+checkAudits original renamed = do+ let structure :: TrialBalanceIssue Double -> StructureIssue Double (HatBase ReverseTitle)+ structure = renameIssue ReverseTitle+ issueOrder :: StructureIssue Double (HatBase ReverseTitle)+ -> StructureIssue Double (HatBase ReverseTitle)+ -> Ordering+ issueOrder left right = compare (issueKey left) (issueKey right)+ impossible :: ImpossibleBalance Double -> ImpossibleBalanceOf ReverseTitle Double+ impossible (ImpossibleBalance title balance) =+ ImpossibleBalance (ReverseTitle title) balance+ abnormal :: AbnormalBalance Double -> AbnormalBalanceOf ReverseTitle Double+ abnormal (AbnormalBalance title home balance) =+ AbnormalBalance (ReverseTitle title) home balance+ temporary :: TemporaryAccountBalance Double+ -> TemporaryAccountBalanceOf ReverseTitle Double+ temporary (TemporaryAccountBalance title balance) =+ TemporaryAccountBalance (ReverseTitle title) balance+ residual :: ClosingResidual Double -> ClosingResidualOf ReverseTitle Double+ residual (ClosingResidual title balance) = ClosingResidual (ReverseTitle title) balance+ titleOrder :: (f -> ReverseTitle) -> f -> f -> Ordering+ titleOrder project left right = compare (project left) (project right)+ assertEqual "L2 impossible balances, target order and multiplicity"+ (mapAudit structure impossible issueOrder (titleOrder _impossibleAccount)+ (impossibleBalances original)) (impossibleBalances renamed)+ assertEqual "L2 abnormal balances, target order and multiplicity"+ (mapAudit structure abnormal issueOrder (titleOrder _abnormalAccount)+ (abnormalBalances original)) (abnormalBalances renamed)+ assertEqual "L2 temporary balances, target order and multiplicity"+ (mapAudit structure temporary issueOrder (titleOrder _temporaryAccount)+ (temporaryAccountBalances original)) (temporaryAccountBalances renamed)+ assertEqual "L2 closing residuals, target order and multiplicity"+ (mapAudit structure residual issueOrder (titleOrder _residualAccount)+ (closingResiduals original)) (closingResiduals renamed)++-- | Registry premises for detecting derived coordinates and displaying balances.+checkStatementRegistry :: IO ()+checkStatementRegistry = do+ assertEqual "L1 derived coordinates equal legacy metric titles"+ (filter (isJust . Metric.metricForLegacyTitle) concreteAccountTitles)+ [title | title <- concreteAccountTitles, Just sem <- [accountSemantics title],+ asemReportingEligibility sem == DerivedPresentation]+ assertEqual "L1 all statement-eligible titles have a statement division" []+ [title | title <- concreteAccountTitles, Just sem <- [accountSemantics title],+ asemReportingEligibility sem == StatementEligible,+ case asemDivisionSemantics sem of+ StatementDivision _ -> False+ _ -> True]++-- | All metadata and side computations commute with the reversed bijection.+checkMetadata :: IO ()+checkMetadata = do+ assertEqual "L2 wildcard preserved" (ReverseTitle (wildcard :: AccountTitles)) wildcard+ let allTitles = [minBound .. maxBound] :: [AccountTitles]+ assertEqual "L2 specifications for all titles"+ [(title, vocabSpec title) | title <- allTitles]+ [(title, vocabSpec (ReverseTitle title)) | title <- allTitles]+ assertEqual "L2 semantics for all titles"+ [(title, vocabSemantics title) | title <- allTitles]+ [(title, vocabSemantics (ReverseTitle title)) | title <- allTitles]+ assertEqual "L2 divisions for all concrete titles"+ [(title, vocabDivision title) | title <- concreteTitles]+ [(title, vocabDivision (ReverseTitle title)) | title <- concreteTitles]+ assertEqual "L2 whichSide for all concrete titles and directions"+ [((title, side), whichSide (side :< title))+ | title <- concreteTitles, side <- [Hat, Not]]+ [((title, side), whichSide (side :< ReverseTitle title))+ | title <- concreteTitles, side <- [Hat, Not]]+ assertEqual "L2 impossible table" (map (first ReverseTitle)+ (vocabImpossibleBalanceSides :: [(AccountTitles, Side)])) vocabImpossibleBalanceSides+ assertEqual "L2 suspense table" (map ReverseTitle+ (vocabSuspenseTitles :: [AccountTitles])) vocabSuspenseTitles+ assertEqual "L2 additional closing table" (map ReverseTitle+ (vocabAdditionalClosingResidualTitles :: [AccountTitles]))+ vocabAdditionalClosingResidualTitles++-- | Small finite posting sequences include collisions and opposing directions.+genValidRows :: Gen [(Double, Hat, AccountTitles)]+genValidRows = do+ count <- chooseInt (0, 35)+ vectorOf count $ (,,) <$> elements [0.1, 0.2, 0.3, 1, 2 ^ (53 :: Int)]+ <*> elements [Hat, Not]+ <*> elements concreteTitles++-- | Generated ledgers commute under exact balance and metric observations.+propRenaming :: Property+propRenaming = forAll genValidRows $ \rows ->+ let original = validLedger rows+ renamed = validLedger (renameRows ReverseTitle rows)+ in conjoin+ [ Map.mapKeys ReverseTitle (accountBalances original) === accountBalances renamed+ , first renameMetricError (Metric.periodResultOfAlg original)+ === Metric.periodResultOfAlg renamed+ ]++-- | Exact balances commute on every account, with both directions and cancellation.+checkBalances :: IO ()+checkBalances = forM_ [Hat, Not] $ \side -> do+ let rows = [(value, side, title) | title <- concreteTitles, value <- [0.1, 0.2, 3]]+ ++ [(0.1, Not, Cash), (0.1, Hat, Cash)]+ original = validLedger rows :: TrialBalance Double+ renamed = validLedger (renameRows ReverseTitle rows)+ assertEqual "L2 account balances exact" (Map.mapKeys ReverseTitle (accountBalances original))+ (accountBalances renamed)+ checkAudits original renamed++-- | Transfer success preserves the entire posting multiset, before aggregation.+checkTransferSuccess :: IO ()+checkTransferSuccess = do+ let rows = [(0.1, Not, Cash), (0.1, Not, Cash), (0.3, Hat, Cash), (4, Not, Sales)]+ original = validLedger rows :: TrialBalance Double+ renamed = validLedger (renameRows ReverseTitle rows)+ table = mkTransferTable+ [Cash .-> Deposits |% Relabel, Deposits .-> RetainedEarnings |% Portion 1 2]+ renamedTable = mkTransferTable+ [ ReverseTitle Cash .-> ReverseTitle Deposits |% Relabel+ , ReverseTitle Deposits .-> ReverseTitle RetainedEarnings |% Portion 1 2+ ]+ case (table, renamedTable) of+ (Right source, Right target) -> case+ (transferEntries source original, transferEntries target renamed) of+ (Right before, Right after) -> do+ assertEqual "L2 transfer complete posting multiset"+ (sort [(renameBase ReverseTitle base, value)+ | (base, value) <- postings before])+ (postings after)+ assertEqual "L2 transfer explicit rounding agrees" (Right (postings after))+ (fmap postings (transferEntriesWith Nearest target renamed))+ other -> fail ("L2 transfer unexpectedly failed: " ++ show other)+ other -> fail ("L2 invalid test table: " ++ show other)++-- | Two sources create two identical destinations, which must remain two postings.+checkTransferDuplicates :: IO ()+checkTransferDuplicates = do+ let sourceRows = [Cash .-> RetainedEarnings |% Relabel,+ Sales .-> RetainedEarnings |% Relabel]+ targetRows = [ReverseTitle Cash .-> ReverseTitle RetainedEarnings |% Relabel,+ ReverseTitle Sales .-> ReverseTitle RetainedEarnings |% Relabel]+ rows = [(4, Not, Cash), (4, Hat, Sales)] :: [(Double, Hat, AccountTitles)]+ case (mkTransferTable sourceRows, mkTransferTable targetRows) of+ (Right source, Right target) -> case+ ( transferEntries source (validLedger rows)+ , transferEntries target (validLedger (renameRows ReverseTitle rows)) ) of+ (Right before, Right after) -> do+ let expected = sort [(renameBase ReverseTitle base, value)+ | (base, value) <- postings before]+ duplicatedDestination = (Hat :< ReverseTitle RetainedEarnings, 4)+ assertEqual "L2 exact duplicate-preserving transfer" expected (postings after)+ assertEqual "L2 two identical destination postings" 2+ (length (filter (== duplicatedDestination) (postings after)))+ other -> fail ("L2 duplicate transfer fixture failed: " ++ show other)+ other -> fail ("L2 invalid duplicate transfer table: " ++ show other)++-- | Invalid selection is ordered by the target base, not the source title order.+checkTransferFailures :: IO ()+checkTransferFailures = do+ let rows = [(-1, Not, Cash), (1 / 0, Not, Sales), (-2, Not, Deposits)]+ :: [(Double, Hat, AccountTitles)]+ sourceRows = [Cash .-> RetainedEarnings |% Relabel, Sales .-> RetainedEarnings |% Relabel]+ targetRows =+ [ ReverseTitle Cash .-> ReverseTitle RetainedEarnings |% Relabel+ , ReverseTitle Sales .-> ReverseTitle RetainedEarnings |% Relabel+ ]+ case (mkTransferTable sourceRows, mkTransferTable targetRows) of+ (Right source, Right target) -> do+ assertEqual "L2 transfer source failure order"+ (Left (InvalidPosting (Not :< Cash) NegativeValue))+ (transferEntries source (rawLedger rows))+ assertEqual "L2 transfer reverse order selects other candidate"+ (Left (InvalidPosting (Not :< ReverseTitle Sales) NonFiniteValue))+ (transferEntries target (rawLedger (renameRows ReverseTitle rows)))+ forM_ [rows, reverse rows] $ \permutation -> do+ assertEqual "L2 transfer candidate membership"+ True (case transferEntries target+ (rawLedger (renameRows ReverseTitle permutation)) of+ Left (InvalidPosting sourceBase failure) ->+ (sourceBase, failure) `elem`+ [(Not :< ReverseTitle Cash, NegativeValue),+ (Not :< ReverseTitle Sales, NonFiniteValue)]+ _ -> False)+ assertEqual "L2 transfer input permutation invariant"+ (Left (InvalidPosting (Not :< ReverseTitle Sales) NonFiniteValue))+ (transferEntries target (rawLedger (renameRows ReverseTitle permutation)))+ other -> fail ("L2 invalid failure table: " ++ show other)+ let firstRow = ReverseTitle Cash .-> ReverseTitle RetainedEarnings |% Portion 1 3+ secondRow = ReverseTitle Sales .-> ReverseTitle RetainedEarnings |% Portion 1 3+ decimalRows = [(1, Not, ReverseTitle Cash), (1, Not, ReverseTitle Sales)]+ forM_ [[firstRow, secondRow], [secondRow, firstRow]] $ \ordered ->+ case (ordered, mkTransferTable ordered) of+ (row : _, Right table) -> do+ let expectedBase = case ordered of+ first : _ | first == firstRow -> Not :< ReverseTitle Cash+ _ -> Not :< ReverseTitle Sales+ assertEqual "L2 unroundable failure follows table row order"+ (Left (UnroundableAmount row expectedBase))+ (transferEntries table (validLedger decimalRows+ :: Alg MoneyDecimal (HatBase ReverseTitle)))+ other -> fail ("L2 invalid portion fixture: " ++ show other)+ let unitRow = (ReverseTitle Cash, wildcard)+ .-> (ReverseTitle RetainedEarnings, wildcard) |% Portion 1 3+ unitLedger = 1 .@ Not :< (ReverseTitle Cash, Yen)+ .+ 1 .@ Not :< (ReverseTitle Cash, Dollar)+ :: Alg MoneyDecimal (HatBase (ReverseTitle, CountUnit))+ firstBase = min (Not :< (ReverseTitle Cash, Yen))+ (Not :< (ReverseTitle Cash, Dollar))+ case mkTransferTable [unitRow] of+ Right table -> assertEqual "L2 unroundable first base within one row"+ (Left (UnroundableAmount unitRow firstBase)) (transferEntries table unitLedger)+ Left failure -> fail ("L2 invalid unit table: " ++ show failure)++-- | Rename typed metric errors, retaining the documented candidate selection freedom.+renameMetricError :: Metric.MetricErrorOf AccountTitles -> Metric.MetricErrorOf ReverseTitle+renameMetricError issue = case issue of+ Metric.MetricNotAvailableAtStage stage -> Metric.MetricNotAvailableAtStage stage+ Metric.ResidualDerivedCoordinate title -> Metric.ResidualDerivedCoordinate (ReverseTitle title)+ Metric.WildcardMetricSide title -> Metric.WildcardMetricSide (ReverseTitle title)+ Metric.WildcardMetricAccount -> Metric.WildcardMetricAccount+ Metric.InvalidMetricValue title -> Metric.InvalidMetricValue (ReverseTitle title)++-- | Metrics commute exactly for unique outcomes; ambiguous failures retain kind and membership.+checkMetrics :: IO ()+checkMetrics = do+ let successFixtures =+ [ [(7, Not, Sales), (3, Not, SalesCost)]+ , [(7, Not, SalesCost), (3, Not, Sales)]+ , [(3, Not, Sales), (3, Not, SalesCost)]+ ]+ forM_ successFixtures $ \rows ->+ assertEqual "L2 period metric exact success or unique error"+ (first renameMetricError+ (Metric.periodResultOfAlg (validLedger rows :: TrialBalance Double)))+ (Metric.periodResultOfAlg (validLedger (renameRows ReverseTitle rows)))+ forM_ [[(1 / 0, Not, Cash)], [(2, HatNot, Sales)]] $ \rows ->+ assertEqual "L2 unique metric error"+ (first renameMetricError+ (Metric.periodResultOfAlg (rawLedger rows :: TrialBalance Double)))+ (Metric.periodResultOfAlg (rawLedger (renameRows ReverseTitle rows)))+ let rows = [(-1, Not, Cash), (1 / 0, Not, Sales)]+ result = Metric.periodResultOfAlg+ (rawLedger (renameRows ReverseTitle rows) :: Alg Double (HatBase ReverseTitle))+ sourceResult = Metric.periodResultOfAlg (rawLedger rows :: TrialBalance Double)+ sourceCandidates = map metricCandidate rows+ candidates = map renameMetricError sourceCandidates+ metricCandidate :: (Double, Hat, AccountTitles) -> Metric.MetricError+ metricCandidate (_, HatNot, title) = Metric.WildcardMetricSide title+ metricCandidate (_, _, title) = Metric.InvalidMetricValue title+ assertEqual "L2 source metric error kind and candidate membership" True+ (case sourceResult of+ Left issue -> issue `elem` sourceCandidates+ Right _ -> False)+ assertEqual "L2 period metric error kind and candidate membership" True+ (case result of+ Left issue -> issue `elem` candidates+ Right _ -> False)++-- | Empty table defaults add no built-in-title policy; semantics still closes nominal accounts.+checkDefaults :: IO ()+checkDefaults = do+ assertEqual "L3 impossible default table" []+ (vocabImpossibleBalanceSides :: [(DefaultTitle, Side)])+ assertEqual "L3 suspense default table" [] (vocabSuspenseTitles :: [DefaultTitle])+ assertEqual "L3 residual default table" []+ (vocabAdditionalClosingResidualTitles :: [DefaultTitle])+ forM_ [Hat, Not] $ \side -> do+ let ledger = validLedger [(2, side, DefaultTitle title) | title <- concreteTitles]+ :: Alg Double (HatBase DefaultTitle)+ expected =+ [ ClosingResidual (DefaultTitle title) balance+ | (DefaultTitle title, balance) <- Map.toAscList (accountBalances ledger)+ , semanticsCloses title+ ]+ assertEqual "L3 impossible ignores built-in table" NoProblem (impossibleBalances ledger)+ assertEqual "L3 temporary ignores built-in table" NoProblem+ (temporaryAccountBalances ledger)+ assertEqual "L3 closing uses only semantic role or division"+ (case expected of+ [] -> NoProblem+ finding : rest -> Error+ (AccountingFinding finding :| map AccountingFinding rest))+ (closingResiduals ledger)+ let wildcardLedger = rawLedger [(1, Not, DefaultTitle AccountTitle)]+ :: Alg Double (HatBase DefaultTitle)+ expected :: AuditResult (StructureIssue Double (HatBase DefaultTitle)) f+ expected = Error+ (StructureFinding (WildcardAccount (Not :< DefaultTitle AccountTitle)) :| [])+ assertEqual "L3 wildcard blocks impossible" expected (impossibleBalances wildcardLedger)+ assertEqual "L3 wildcard blocks abnormal" expected (abnormalBalances wildcardLedger)+ assertEqual "L3 wildcard blocks temporary" expected (temporaryAccountBalances wildcardLedger)+ assertEqual "L3 wildcard blocks closing" expected (closingResiduals wildcardLedger)++-- | Independent closing oracle for the semantic part, excluding the additional table.+semanticsCloses :: AccountTitles -> Bool+semanticsCloses title = case accountSemantics title of+ Nothing -> False+ Just semantics ->+ any (`elem` asemRoles semantics) [ClosingDevice, PeriodResult, ReportingSubtotal]+ || asemDivisionSemantics semantics `elem`+ [StatementDivision Revenue, StatementDivision Cost]++-- | Explicit residual policy is effective even when the account has no semantics.+checkAdditionalResidual :: IO ()+checkAdditionalResidual = do+ let title = ExtraTitle CashOverShort+ ledger = 5 .@ Not :< title :: Alg Double (HatBase ExtraTitle)+ assertEqual "L4 dedicated account has a specification" True+ (case vocabSpec title of Just _ -> True; Nothing -> False)+ assertEqual "L4 dedicated account lacks semantics" Nothing (vocabSemantics title)+ assertEqual "L2 period metric ignores an account without semantics"+ (Right Metric.PeriodBreakEven) (Metric.periodResultOfAlg ledger)+ assertEqual "L4 additional residual without semantics"+ (Error (AccountingFinding (ClosingResidual title (DebitBalance 5)) :| []))+ (closingResiduals ledger)++-- | Journal audits preserve every structure issue, including repeated wildcards.+checkJournalStructure :: IO ()+checkJournalStructure = do+ let rows = [(1 / 0, Not, Cash), (-1, Not, Sales),+ (1, Not, AccountTitle), (2, Not, AccountTitle)]+ journal = rawLedger (renameRows ReverseTitle rows) Journal..| (1 :: Int)+ issues = sortOn issueKey+ [ InvalidValue (1 / 0) (Not :< ReverseTitle Cash)+ , InvalidValue (-1) (Not :< ReverseTitle Sales)+ , WildcardAccount (Not :< ReverseTitle AccountTitle)+ , WildcardAccount (Not :< ReverseTitle AccountTitle)+ ]+ case issues of+ [] -> fail "L2 journal structure fixture must have findings"+ issue : rest -> do+ let expected :: AuditResult (JournalIssue Int Double (HatBase ReverseTitle)) f+ expected = Error (StructureFinding (1, issue)+ :| map (StructureFinding . (,) 1) rest)+ assertEqual "L2 duplicate audit target structure order and multiplicity"+ expected (duplicateTransactions journal)+ assertEqual "L2 contrary audit target structure order and multiplicity"+ expected (contraryNominalPostings journal)++-- | A wildcard side is tested as a singleton: Alg cannot combine HatNot with other terms.+checkJournalWildcardSide :: IO ()+checkJournalWildcardSide = do+ let source = HatNot :< ReverseTitle Cash+ journal = Internal.Single (1 :: Double) source Journal..| (1 :: Int)+ expected :: AuditResult (JournalIssue Int Double (HatBase ReverseTitle)) f+ expected = Error (StructureFinding (1, WildcardSide source) :| [])+ assertEqual "L2 duplicate audit wildcard side" expected (duplicateTransactions journal)+ assertEqual "L2 contrary audit wildcard side" expected (contraryNominalPostings journal)++-- | Map every title in the inputs, including instruction targets and label keys.+statementContext :: Ord t => (AccountTitles -> t) -> P.PresentationProfile+ -> P.ReportingContextOf t Double+statementContext f profile = (P.reportingContext P.JGAAP P.Combined profile)+ { P._maturitySensitiveTitles = Set.fromList (map f [NotesReceivable, LoansReceivable])+ , P._presentationAllocations =+ [P.PresentationAllocation (f NotesReceivable) 10 4 "notes",+ P.PresentationAllocation (f LoansReceivable) 20 10 "loans"]+ , P._presentationRelabels =+ [P.PresentationRelabel (f Purchases) (f SalesCost) "cost of sales",+ P.PresentationRelabel (f PettyCash) (f Deposits) "deposit"]+ , P._materialityDecisions =+ [P.MaterialityDecision (f IncomeTaxesRefundReceivable) P.PresentGross "tax",+ P.MaterialityDecision (f Cash) P.PresentSeparately "cash"]+ , P._contraPresentationRules =+ [P.NetContraAgainst (f SalesAllowances) (f Sales) "net",+ P.PresentContraSeparately (f SalesRebates) "separate"]+ , P._subtotalDefinitions =+ [P.SubtotalDefinition Metric.OrdinaryProfitMetric [f Sales]+ (map f [SalesCost, SalesRebates]) P.RequireAllTitlesPresent,+ P.SubtotalDefinition Metric.GrossProfitMetric [f Sales] [f SalesCost]+ P.RequireAllTitlesPresent]+ , P._labelOverrides = Map.mapKeys f $ Map.insert NotesReceivable "notes by maturity"+ (P._labelOverrides (P.jcciSecondGradeContext P.Combined))+ }++-- | Observe each stage in instruction order. Only labels use target-key order.+expectedEvents :: Ord t => (AccountTitles -> t) -> P.PresentationProfile+ -> [P.PresentationAuditEventOf t Double]+expectedEvents f profile =+ [ P.ReciprocalPairEliminated (f BranchCurrentAccount) (DebitBalance 9)+ (f HeadOfficeCurrentAccount) (CreditBalance 9)+ , P.AccountRelabeled (f Purchases) (f SalesCost) (DebitBalance 5) "cost of sales"+ , P.AccountRelabeled (f PettyCash) (f Deposits) (DebitBalance 3) "deposit"+ , P.MaterialityApplied (f IncomeTaxesRefundReceivable) P.PresentGross (DebitBalance 2) "tax"+ , P.MaterialityApplied (f Cash) P.PresentSeparately (DebitBalance 10) "cash"+ , P.ContraPresentationApplied (f SalesAllowances) (Just (f Sales)) (DebitBalance 4) "net"+ , P.ContraPresentationApplied (f SalesRebates) Nothing (DebitBalance 3) "separate"+ , P.BalanceAllocated (f NotesReceivable) 10 4 "notes"+ , P.BalanceAllocated (f LoansReceivable) 20 10 "loans"+ , P.SubtotalCalculated Metric.PeriodResultMetric (CreditBalance 38)+ , P.SubtotalCalculated Metric.OrdinaryProfitMetric (CreditBalance 38)+ , P.SubtotalCalculated Metric.GrossProfitMetric (CreditBalance 41)+ ] ++ [ P.LabelOverridden (f title) (P.presentationLabel P.CanonicalJapanese title) label+ | profile == P.JcciSecondGradeReport+ , (title, label) <- sortOn (f . fst)+ [(AdvancesReceived, "契約負債"), (NotesReceivable, "notes by maturity")] ]++-- | Compare complete rows after a stable target-order sort, including split rows.+checkStatementRenaming :: IO ()+checkStatementRenaming = do+ assertEqual "L2 reciprocal table preserves order and orientation"+ [(ReverseTitle l, ReverseTitle r) | (l,r) <- vocabReciprocalPairs]+ vocabReciprocalPairs+ let rows = [(30, Not, LoansReceivable), (14, Not, NotesReceivable),+ (5, Not, Purchases), (3, Not, PettyCash), (3, Not, SalesRebates),+ (4, Not, SalesAllowances), (10, Not, Cash), (2, Not, IncomeTaxesRefundReceivable),+ (9, Not, BranchCurrentAccount), (9, Not, HeadOfficeCurrentAccount),+ (50, Not, Sales), (15, Not, AdvancesReceived), (6, Not, CapitalStock)]+ forM_ [P.JcciSecondGradeReport, P.CanonicalJapanese] $ \profile -> do+ let context = statementContext id profile+ source <- either (fail . show) pure (P.present context BeforeClosing (validLedger rows))+ target <- either (fail . show) pure (P.present (statementContext ReverseTitle profile)+ BeforeClosing (validLedger (renameRows ReverseTitle rows)))+ let renameLine line = line { P._lineAccount = ReverseTitle (P._lineAccount line) }+ sourceLines = P._statementLines source+ notesLabel = case profile of+ P.JcciSecondGradeReport -> "notes by maturity"+ _ -> P.presentationLabel profile NotesReceivable+ assertEqual "L2 allocated labels, sections, and split order"+ [(notesLabel, P.CurrentAssetsSection, 10), (notesLabel, P.NoncurrentAssetsSection, 4)]+ [(P._lineLabel line, P._lineSection line, P._lineAmount line)+ | line <- sourceLines, P._lineAccount line == NotesReceivable]+ assertEqual "L2 allocated and ordinary lines in target order"+ (sortOn P._lineAccount (map renameLine sourceLines)) (P._statementLines target)+ assertEqual "L2 subtotals retain definition order and labels"+ (P._statementSubtotals source) (P._statementSubtotals target)+ assertEqual "L2 audit stages and source instruction order"+ (expectedEvents id profile) (P._presentationAudit source)+ assertEqual "L2 audit stages and target instruction order"+ (expectedEvents ReverseTitle profile) (P._presentationAudit target)++-- | Compare whole issue multisets, including repeated issues and their payloads.+checkStatementFailures :: IO ()+checkStatementFailures = do+ let check label ledger wanted =+ case P.present (P.reportingContext P.JGAAP P.Standalone P.CanonicalEnglish)+ BeforeClosing ledger of+ Right _ -> fail (label ++ ": expected presentation issues")+ Left issues -> assertEqual label ([], [])+ (wanted \\ NE.toList issues, NE.toList issues \\ wanted)+ malformed = [(-1, Not, Cash), (-2, Not, Sales), (1, Not, AccountTitle)]+ structural f = [P.InvalidStatementValue (f Cash), P.InvalidStatementValue (f Sales),+ P.WildcardStatementBase]+ zeroWildcard f = Internal.Single (0 :: Double) (HatNot :< f AccountTitle)+ derived = [(20, Not, NetIncome), (20, Not, OrdinaryProfit)]+ residual f = [P.UnpresentableBalance (f NetIncome) (DebitBalance 20),+ P.UnpresentableBalance (f OrdinaryProfit) (CreditBalance 20),+ P.PeriodResultUnavailable+ (Metric.ResidualDerivedCoordinate (min (f NetIncome) (f OrdinaryProfit)))]+ check "L2 structure issue multiset" (rawLedger malformed :: TrialBalance Double)+ (structural id)+ check "L2 renamed structure issue multiset" (rawLedger (renameRows ReverseTitle malformed)+ :: Alg Double (HatBase ReverseTitle)) (structural ReverseTitle)+ check "L2 singleton zero with two wildcard axes" (zeroWildcard id)+ [P.WildcardStatementBase, P.WildcardStatementBase]+ check "L2 renamed singleton zero with two wildcard axes" (zeroWildcard ReverseTitle)+ [P.WildcardStatementBase, P.WildcardStatementBase]+ check "L2 minimum derived coordinate and coverage issues"+ (validLedger derived :: TrialBalance Double) (residual id)+ check "L2 reversed minimum derived coordinate and coverage issues"+ (validLedger (renameRows ReverseTitle derived) :: Alg Double (HatBase ReverseTitle))+ (residual ReverseTitle)++-- | A deduction larger than the gross amount reverses the net row's direction.+checkCustomGroup :: IO ()+checkCustomGroup = do+ let gross = ReverseTitle Building+ deduction = ReverseTitle AccumulatedDepreciation+ key = G.DepreciableAssetsGroup+ def = G.PresentationGroupDef key Assets "Carrying amount" [gross] [deduction] Nothing+ grouped = G.presentGroups [def]+ (Map.fromList [(gross, (10, 0)), (deduction, (2, 16))])+ :: G.GroupedPresentationOf ReverseTitle Double+ assertEqual "group rows retain gross, deduction and below-zero net"+ [(def, [G.GroupRow (G.GrossRow gross) (G.RelativeAmount False 10),+ G.GroupRow (G.DeductionRow deduction) (G.RelativeAmount True 14),+ G.GroupRow (G.NetRow key) (G.RelativeAmount True 4)])] (G.gpBlocks grouped)+ assertEqual "group root retains both gross sides"+ (Map.singleton Assets (12, 16)) (G.gpRootTotals grouped)+ assertEqual "group consumes gross and deduction titles"+ (Set.fromList [gross, deduction]) (G.gpConsumed grouped)++-- | Register the vocabulary laws in the accounting test suite.+runTests :: IO ()+runTests = do+ checkStatementRegistry+ checkStatementRenaming+ checkStatementFailures+ checkCustomGroup+ PresentationVocabularySpec.runTests+ checkMetadata+ checkBalances+ quickProp "L2 generated exact balance and metric renaming" propRenaming+ checkTransferSuccess+ checkTransferDuplicates+ checkTransferFailures+ let malformed =+ [(1 / 0, Not, Cash), (-1, Not, Sales),+ (1, Not, AccountTitle), (2, Not, AccountTitle)]+ checkAudits (rawLedger malformed) (rawLedger (renameRows ReverseTitle malformed))+ checkAudits (Internal.Single 1 (HatNot :< Cash))+ (Internal.Single 1 (HatNot :< ReverseTitle Cash))+ checkJournalStructure+ checkJournalWildcardSide+ checkMetrics+ checkDefaults+ checkAdditionalResidual
test/Algebra/CoreSpec.hs view
@@ -10,6 +10,9 @@ import qualified ExchangeAlgebra.Algebra.Internal as EAI import qualified ExchangeAlgebra.Journal as EJ import ExchangeAlgebra.Algebra.Value (MoneyDecimal, bankersRound)+import qualified Data.HashMap.Strict as HM+import qualified Data.IntMap.Strict as IM+import qualified Data.IntSet as IS import qualified Data.Map.Strict as M import qualified Data.List as L import System.Exit (exitFailure)@@ -95,38 +98,24 @@ assertEqual "bases Not label count" 3 notCount --- | Characterization: the same-base 'Seq' order is __construction-path--- dependent__. The pairwise-union path ('EA.fromList' = 'mconcat') and the--- bulk-merge path ('EA.sigma' \/ 'EA.unionsMerge') produce the same /multiset/--- of postings but in different sequence orders, which 'Eq' \/ @Binary@ observe--- (and 'Double' observes through the last ULP of 'norm'\/'bar' association).--- This test pins the current orders so any change to either path is a--- conscious decision; unifying the paths is tracked in the 0.5.0.0 cleanup--- plan. For order-independent comparison use `MoneyDecimal` (exact) or compare--- after 'EA.compress'\/'EA.bar'.-testSameBaseSeqOrderPathDependence :: IO ()-testSameBaseSeqOrderPathDependence = do+testSameBaseSeqOrder :: IO ()+testSameBaseSeqOrder = do let f :: Int -> TestAlg f i = fromIntegral i .@ (Hat :< Yen)- xs = L.map f [1, 2, 3]- viaFromList = EA.fromList xs- viaSigma = EA.sigma [1, 2, 3] f- viaMerge = EA.unionsMerge xs- assertEqual "fromList same-base seq order (pairwise-union path)"- [3, 1, 2] (EA.vals viaFromList)- assertEqual "sigma same-base seq order (bulk-merge path)"- [3, 2, 1] (EA.vals viaSigma)- assertEqual "unionsMerge order matches sigma (same merge path)"- (EA.vals viaSigma) (EA.vals viaMerge)- -- same multiset, different order: Eq observes the redundancy order- assertEqual "fromList /= sigma under Eq (order is observable)"- False (viaFromList == viaSigma)- -- the algebraic content is nevertheless identical- assertNear "norm agrees across construction paths"- (norm viaFromList) (norm viaSigma)- assertEqual "bar agrees across construction paths"- (EA.bar viaFromList) (EA.bar viaSigma)-+ a = f 1+ b = f 2+ c = f 3+ xs = [a, b, c]+ paths = [ ("left-associated (.+)", (a .+ b) .+ c)+ , ("right-associated (.+)", a .+ (b .+ c))+ , ("fromList", EA.fromList xs)+ , ("sigma", EA.sigma [1, 2, 3] f)+ , ("unionsMerge", EA.unionsMerge xs)+ ]+ mapM_ (\(label, alg) -> assertEqual (label ++ " same-base sequence order")+ [1, 2, 3] (EA.vals alg)) paths+ assertEqual "same-base construction paths agree under Eq"+ True (all ((== (a .+ (b .+ c))) . snd) paths) -- | Regression for audit divergence C: scalar product (.*) must reject a -- negative / non-finite scalar instead of silently producing negative@@ -194,7 +183,122 @@ Right v -> do putStrLn ("[FAIL] wildcard projNetNorm did not use the index: " ++ show v); exitFailure _ -> do putStrLn "[FAIL] expected a Liner"; exitFailure +-- | Generate a multi-base algebra with small whole values and ledger wildcards.+genAlgebra :: Gen (EA.Alg Double SimHatBase2)+genAlgebra = do+ baseCount <- chooseInt (32, 96)+ EA.fromList <$> traverse genPosting [1 .. baseCount]+ where+ genPosting company = do+ side :< unit <- genBase+ counterparty <- frequency [(1, pure EA.wildcard), (4, chooseInt (1, 8))]+ ledgerUnit <- frequency [(1, pure EA.wildcard), (4, pure unit)]+ value <- chooseInt (1, 10)+ pure (fromIntegral value .@ (side :< (Cash, company, counterparty, ledgerUnit))) +-- | Exercise an index containing sets of 1,000 base IDs.+largeAlgebra :: EA.Alg Double SimHatBase2+largeAlgebra = EA.fromList+ [ 1 .@ (Not :< (Cash, company, 1, Yen))+ | company <- [1 .. 1000]+ ]++-- | Check all three wildcard index fields against IDs assigned in base key order.+testWildcardIndexIds :: IO ()+testWildcardIndexIds = do+ quickProp "wildcard index IDs follow base key order" $+ forAll genAlgebra (checkIndex 32)+ quickProp "wildcard index IDs follow base key order (1000 bases)" $+ once (checkIndex 1000 largeAlgebra)+ where+ checkIndex :: Int -> EA.Alg Double SimHatBase2 -> Property+ checkIndex minBases EAI.Liner+ { EAI._realg = m+ , EAI._idToBp = idToBp+ , EAI._allBpIds = allIds+ , EAI._axisPosting = axisPosting+ } =+ let numberedBases :: [(Int, EAI.BasePart SimHatBase2)]+ numberedBases = zip [0 ..] (HM.keys m)++ expectedPostings :: IM.IntMap (HM.HashMap EAI.ElementKey IS.IntSet)+ expectedPostings = IM.fromListWith (HM.unionWith IS.union)+ [ (axis, HM.singleton key (IS.singleton baseId))+ | (baseId, basePart) <- numberedBases+ , (axis, key) <- zip [0 ..] (EAI.toElementKeys basePart)+ ]+ in conjoin+ [ counterexample "too few distinct bases" (HM.size m >= minBases)+ , idToBp === IM.fromList numberedBases+ , allIds === IS.fromList [0 .. HM.size m - 1]+ , counterexample "component index differs" $+ IM.map (HM.map snd) axisPosting == expectedPostings+ ]+ checkIndex _ _ = counterexample "expected a Liner" False++-- | Check every cached cardinality against the corresponding set.+testWildcardIndexSizes :: IO ()+testWildcardIndexSizes = do+ quickProp "wildcard index sizes agree with IntSet.size" $+ forAll genAlgebra checkSizes+ quickProp "wildcard index sizes agree with IntSet.size (1000 bases)" $+ once (checkSizes largeAlgebra)+ where+ checkSizes :: EA.Alg Double SimHatBase2 -> Property+ checkSizes EAI.Liner { EAI._axisPosting = axisPosting } = conjoin+ [ counterexample ("component " ++ show position ++ ", key " ++ show key) $+ size === IS.size ids+ | (position, byKey) <- IM.toList axisPosting+ , (EAI.ElementKey key, (size, ids)) <- HM.toList byKey+ ]+ checkSizes _ = counterexample "expected a Liner" False++-- | Compare both projection APIs with a full scan using one-way matching.+testWildcardQueriesAgainstScan :: IO ()+testWildcardQueriesAgainstScan =+ quickProp "wildcard proj and projNetNorm agree with an entry scan" $+ forAll genAlgebra $ \alg -> conjoin (L.map (checkQuery alg) queries)+ where+ queries :: [SimHatBase2]+ queries =+ [ HatNot :< (Cash, (.#), 1, Yen)+ , Not :< (Cash, (.#), (.#), Yen)+ , Hat :< (Cash, 1, (.#), (.#))+ , HatNot :< (Cash, (.#), (.#), (.#))+ , Not :< (Products, (.#), 1, Yen)+ , HatNot :< ((.#), (.#), (.#), (.#))+ ]++ checkQuery alg query =+ let entries = EA.foldEntries (collectMatching query) [] alg+ projected = EA.foldEntries collectEntry [] (EA.proj [query] alg)+ expectedNet = norm $ EA.bar $ EA.fromList+ [value .@ (side :< components) | ((side, components), value) <- entries]+ in counterexample ("query " ++ show query) $ conjoin+ [ L.sortOn fst projected === L.sortOn fst entries+ , EA.projNetNorm [query] alg === expectedNet+ ]++ collectEntry entries value (side :< components) =+ ((side, components), value) : entries++ collectMatching query entries value entry+ | matchesBase query entry = collectEntry entries value entry+ | otherwise = entries++ matchesBase :: SimHatBase2 -> SimHatBase2 -> Bool+ matchesBase (querySide :< (title, company, counterparty, unit))+ (entrySide :< (title', company', counterparty', unit')) =+ matchesElement querySide entrySide+ && matchesElement title title'+ && matchesElement company company'+ && matchesElement counterparty counterparty'+ && matchesElement unit unit'++ matchesElement :: EA.Element a => a -> a -> Bool+ matchesElement query entry = EA.isWildcard query || query == entry++ -- | Regression tests for scale-aware numeric tolerance (WI-11/12/14). -- These exercise large magnitudes that the previous fixed @1e-13@ absolute -- tolerance handled incorrectly (retaining pure rounding noise as a residual);@@ -226,6 +330,137 @@ ps <- vectorOf k ((,) <$> genNNDouble <*> genBase) pure (EA.fromList [ v .@ b | (v, b) <- ps ]) +-- | Check all comparison triples across five generated representation shapes.+testAlgComparison :: IO ()+testAlgComparison = do+ let yen = Not :< Yen+ dollar = Hat :< Dollar+ first = 1 .@ yen :: TestAlg+ second = 2 .@ yen+ retained = 1 .@ dollar+ check :: String -> TestAlg -> TestAlg -> IO ()+ check description expected actual = do+ assertEqual (description ++ " produces a one-term Liner") True (isOneTermLiner actual)+ assertEqual (description ++ " compares equal to a Single")+ (True, True, EQ, EQ)+ (actual == expected, expected == actual,+ compare actual expected, compare expected actual)+ check "Alg bar" (3 .@ yen) (bar (first .+ second))+ check "Alg scaling underflow" (0.5 .@ yen) (0.5 .* (first .+ 5e-324 .@ yen))+ check "Alg subtraction" (3 .@ yen) ((.-) (first .+ second))+ check "Alg filter" retained (EA.filter (EA.isHat . EA._hatBase) (first .+ retained))+ shapes <- generate genShapes+ assertEqual "Alg order generator produces all five representation shapes"+ True (hasAllShapes shapes)++ quickProp "Alg compare returns EQ exactly when Eq holds" $+ forAll genShapes $ \left -> forAll genShapes $ \right ->+ conjoin [ (compare x y == EQ) === (x == y) | x <- left, y <- right ]+ quickProp "Alg compare is antisymmetric and transitive across five shapes" $+ forAll genShapes $ \left -> forAll genShapes $ \middle -> forAll genShapes $ \right ->+ conjoin+ [ conjoin [ compare x y === invert (compare y x)+ , property (not (x <= y && y <= z) || x <= z)+ ]+ | x <- left, y <- middle, z <- right+ ]+ quickProp "Alg Single order still compares hat base before value" $+ forAll positive $ \v1 -> forAll genBase $ \b1 ->+ forAll positive $ \v2 -> forAll genBase $ \b2 ->+ compare (v1 .@ b1 :: TestAlg) (v2 .@ b2) === oldSingleOrder v1 b1 v2 b2+ where+ positive :: Gen Double+ positive = genNNDouble `suchThat` (> 0)++ isOneTermLiner :: TestAlg -> Bool+ isOneTermLiner (EAI.Liner entries _ _ _ _ _) = case HM.elems entries of+ [EAI.HatOne _] -> True+ [EAI.NotOne _] -> True+ _ -> False+ isOneTermLiner _ = False++ hasAllShapes :: [TestAlg] -> Bool+ hasAllShapes+ [ EA.Zero+ , EAI.Single _ _+ , oneTerm+ , EAI.Liner repeated _ _ _ _ _+ , EAI.Liner distinct _ _ _ _ _+ ] = case (HM.elems repeated, HM.elems distinct) of+ ([EAI.PairSeq _ _], [_, _]) -> isOneTermLiner oneTerm+ _ -> False+ hasAllShapes _ = False++ genShapes :: Gen [TestAlg]+ genShapes = do+ v1 <- positive+ v2 <- positive+ b1 <- genBase+ b2 <- genBase `suchThat` (\b -> EA.base b /= EA.base b1)+ let single = v1 .@ b1+ repeated = single .+ v2 .@ b1+ distinct = single .+ v2 .@ b2+ singletonLiner = EA.filter ((== b1) . EA._hatBase) distinct+ pure [EA.Zero, single, singletonLiner, repeated, distinct]++ invert :: Ordering -> Ordering+ invert LT = GT+ invert EQ = EQ+ invert GT = LT++ oldSingleOrder :: Double+ -> HatBase CountUnit+ -> Double+ -> HatBase CountUnit+ -> Ordering+ oldSingleOrder v1 b1 v2 b2+ | b1 == b2 = compare v1 v2+ | b1 > b2 = GT+ | otherwise = LT++testAdditionOrderProperties :: IO ()+testAdditionOrderProperties = do+ quickProp "(.+) is associative under Eq for zero, single, and multiple terms" $+ forAll algShapes $ \xs -> forAll algShapes $ \ys -> forAll algShapes $ \zs ->+ conjoin [((x .+ y) .+ z) === (x .+ (y .+ z)) | x <- xs, y <- ys, z <- zs]++ quickProp "Alg addition paths retain input order on each base and side" $+ forAll genPostings $ \postings ->+ let xs = [v .@ b | (v, b) <- postings] :: [TestAlg]+ expected = EA.fromList xs+ paths = [ EA.sigma xs id+ , EA.unionsMerge xs+ , foldr (.+) EA.Zero xs+ , L.foldl' (.+) EA.Zero xs+ ]+ expectedValues = M.fromList+ [ (b, [v | (v, b') <- postings, b' == b])+ | (_, b) <- postings+ ]+ actualValues = fmap reverse $ EA.foldEntries+ (\acc v b -> M.insertWith (++) b [v] acc) M.empty expected+ in conjoin ((actualValues === expectedValues) : L.map (=== expected) paths)++ quickProp "norm and projNetNorm are equal for reversed Double terms" $+ forAll genPostings $ \postings ->+ let xs = [v .@ b | (v, b) <- postings] :: [TestAlg]+ original = EA.fromList xs+ reordered = EA.fromList (reverse xs)+ query = [HatNot :< Yen, HatNot :< Dollar]+ in conjoin [norm original === norm reordered,+ EA.projNetNorm query original === EA.projNetNorm query reordered]+ where+ positive = genNNDouble `suchThat` (> 0)+ algShapes = do+ single <- (.@) <$> positive <*> genBase+ multiple <- genAlgD `suchThat` ((> 1) . length . EA.vals)+ pure [EA.Zero, single, multiple]+ genPostings = do+ repeatedBase <- genBase+ repeated <- vectorOf 3 ((\v -> (v, repeatedBase)) <$> positive)+ others <- listOf ((,) <$> positive <*> genBase)+ shuffle (repeated ++ others)+ genAlgN :: Gen NNAlg genAlgN = sized $ \n -> do k <- choose (0, min 40 n)@@ -296,7 +531,7 @@ quickProp "lemma: (.+) associative" $ forAll genAlgD $ \x -> forAll genAlgD $ \y -> forAll genAlgD $ \z -> netByBase ((x .+ y) .+ z) == netByBase (x .+ (y .+ z))- -- regression: union must not relabel a value onto a zero posting's base+ -- regression: union must not move a value onto a zero posting's base -- (the 0.4.1.1 bug; raw (:@) so zero-valued singletons are exercised) quickProp "regression: union preserves per-base net (zero-base bug)" $ forAll genNNDouble $ \v1 -> forAll genBase $ \b1 ->@@ -319,7 +554,7 @@ forAll genAlgN $ \x -> netByBase (EA.mapBasePart id x :: NNAlg) == netByBase x quickProp "mapBasePart preserves norm under base collapse (MoneyDecimal)" $ forAll genAlgN $ \x -> norm (EA.mapBasePart (const Amount) x :: NNAlg) == norm x- -- S-4: functoriality of the base-relabel map pi_kappa (Prop 2.8(4)):+ -- S-4: functoriality of the base map pi_kappa (Prop 2.8(4)): -- mapBasePart (kappa' . kappa) x ~=_pi mapBasePart kappa' (mapBasePart kappa x) -- The two kappa are non-identity, non-injective relabelers on CountUnit so the -- composite collapses bases (Yen -> Dollar -> Amount), exercising the value@@ -398,27 +633,25 @@ forAll genAlgN $ \x -> EA.mapBasePart (const Amount) ((.^) x) == ((.^) (EA.mapBasePart (const Amount) x) :: NNAlg)- -- bar keeps the Liner constructor even when cancellation leaves one key- -- with one value; mapBasePart rebuilds that map as a singleton. Eq treats- -- the two constructors as distinct, although ℘ observes the same entry.+ -- bar leaves a one-term Liner and mapBasePart rebuilds it as a Single. let identitySource = (1 .@ (Not :< Yen)) .+ (1 .@ (Hat :< Yen)) .+ (2 .@ (Not :< Dollar)) :: NNAlg oneKeyLiner = bar identitySource identityMapped = EA.mapBasePart id oneKeyLiner :: NNAlg- assertEqual "mapBasePart: identity counterexample has equal multisets"+ assertEqual "mapBasePart: one-term identity preserves the multiset" (observe oneKeyLiner) (observe identityMapped)- assertEqual "mapBasePart: identity fails under raw Eq for one-key Liner"- False (identityMapped == oneKeyLiner)+ assertEqual "mapBasePart: identity holds under Eq for one-term Liner"+ True (identityMapped == oneKeyLiner) let sandwichLeft = bar (EA.mapBasePart (const Amount) oneKeyLiner :: NNAlg) sandwichRight = bar (EA.mapBasePart (const Amount) identitySource :: NNAlg)- assertEqual "mapBasePart: bar sandwich counterexample has equal multisets"+ assertEqual "mapBasePart: bar sandwich has equal multisets for this result" (observe sandwichLeft) (observe sandwichRight)- assertEqual "mapBasePart: bar sandwich can fail under raw Eq"- False (sandwichLeft == sandwichRight)+ assertEqual "mapBasePart: bar sandwich agrees for this one-term result"+ True (sandwichLeft == sandwichRight) -- Three distinct source keys are read back in whatever order the source -- HashMap traverses them (a representation detail, so it is observed at@@ -461,13 +694,13 @@ forAll (listOf ((,) <$> (realToFrac <$> genNNDouble) <*> genBase)) $ \ps -> let singles = [ v .@ b | (v, b) <- ps ] :: [NNAlg] pairwise = EA.fromList singles- bulk = EA.sigma ps (\(v, b) -> v .@ b :: NNAlg)+ bulk = EA.sigma (reverse ps) (\(v, b) -> v .@ b :: NNAlg) sumEntries = EA.foldEntries (\acc v _ -> acc + v) 0 in sumEntries pairwise == sumEntries bulk let entries = [1 .@ (Hat :< Yen), 2 .@ (Hat :< Yen), 3 .@ (Hat :< Yen)] :: [NNAlg] pairwise = EA.fromList entries- bulk = EA.sigma [1, 2, 3 :: Int]+ bulk = EA.sigma [3, 2, 1 :: Int] (\i -> fromIntegral i .@ (Hat :< Yen) :: NNAlg) collect = EA.foldEntries (\acc v _ -> acc ++ [v]) [] assertEqual "foldEntries: non-commutative list append observes Seq order"@@ -493,8 +726,8 @@ -- extendBy (0.5.1.0 A1): the free extension in the redundant layer. let dup :: MoneyDecimal -> HatBase CountUnit -> NNAlg dup v b = (v .@ b) .+ (v .@ b)- relabel :: (CountUnit -> CountUnit) -> MoneyDecimal -> HatBase CountUnit -> NNAlg- relabel f v b = v .@ EA.merge (EA.hat b) (f (EA.base b))+ mapTermBase :: (CountUnit -> CountUnit) -> MoneyDecimal -> HatBase CountUnit -> NNAlg+ mapTermBase f v b = v .@ EA.merge (EA.hat b) (f (EA.base b)) quickProp "extendBy: (.+) homomorphism holds through per-base multisets" $ forAll genAlgN $ \x -> forAll genAlgN $ \y -> observe (EA.extendBy dup (x .+ y) :: NNAlg)@@ -504,23 +737,22 @@ quickProp "extendBy: mapBasePart is the relabelling special case" $ forAll genAlgN $ \x -> observe (EA.mapBasePart (const Amount) x :: NNAlg)- == observe (EA.extendBy (relabel (const Amount)) x :: NNAlg)+ == observe (EA.extendBy (mapTermBase (const Amount)) x :: NNAlg) quickProp "extendBy: norm is the sum of the substituted norms" $ forAll genAlgN $ \x -> norm (EA.extendBy dup x :: NNAlg) == 2 * norm x quickProp "extendBy: substituting Zero everywhere yields Zero" $ forAll genAlgN $ \x -> EA.isZero (EA.extendBy (\_ _ -> EA.Zero) x :: NNAlg) - -- Raw counterexample for the unit law: a one-key Liner left by bar is- -- rebuilt as a singleton (:@), which Eq distinguishes although ℘ agrees.+ -- The unit rebuilds the one-term Liner left by bar as a Single. let unitSource = (1 .@ (Not :< Yen)) .+ (1 .@ (Hat :< Yen)) .+ (2 .@ (Not :< Dollar)) :: NNAlg unitOneKey = bar unitSource unitRebuilt = EA.extendBy (.@) unitOneKey :: NNAlg- assertEqual "extendBy: unit counterexample has equal multisets"+ assertEqual "extendBy: one-term unit preserves the multiset" (observe unitOneKey) (observe unitRebuilt)- assertEqual "extendBy: unit fails under raw Eq for one-key Liner"- False (unitRebuilt == unitOneKey)+ assertEqual "extendBy: unit holds under Eq for one-term Liner"+ True (unitRebuilt == unitOneKey) -- ================================================================ -- Quotient decomposition properties (Phase 1, feat/quotient-decomposition)@@ -634,9 +866,14 @@ testMapMaybePosting testBasesNotSideRegression testNumericToleranceScaleAware- testSameBaseSeqOrderPathDependence+ testSameBaseSeqOrder+ testAlgComparison+ testAdditionOrderProperties testScalarRejectsNegative testProjConcreteNoIndexForce+ testWildcardIndexIds+ testWildcardIndexSizes+ testWildcardQueriesAgainstScan axiomProperties functorialityLawProperties quotientProperties
test/Algebra/ExactReadoutSpec.hs view
@@ -10,6 +10,7 @@ import Control.Monad (forM_, unless) import qualified Data.Text as T import qualified Data.List as List+import qualified Data.Foldable as Foldable import qualified Data.Sequence as Seq import qualified Data.Map.Strict as Map import qualified Data.HashMap.Strict as HashMap@@ -18,6 +19,7 @@ import ExchangeAlgebra.Algebra import ExchangeAlgebra.Algebra.Value (MoneyDecimal, MoneyDouble)+import qualified ExchangeAlgebra.Algebra.Value as Value import qualified ExchangeAlgebra.Algebra as EA import qualified ExchangeAlgebra.Algebra.Internal as Internal import qualified ExchangeAlgebra.Journal as Journal@@ -363,10 +365,103 @@ check "W1 Journal difference golden" expectedDifference (diffRLWithin defaultTolerance (input Journal..| ("golden" :: String))) +-- | The old accounting folds consume two sequences at every complete base.+type AccountPairs = HashMap.HashMap (AccountTitles, T.Text) (Seq.Seq Double, Seq.Seq Double)++-- | Keep the old grouping of exact side states, including structural Side.+referenceAccountDifference :: AccountPairs -> (Bool, (Side, Double))+referenceAccountDifference pairs = (Value.signAccum state == Just EQ, difference)+ where+ state = HashMap.foldlWithKey' collect Value.emptyAccum pairs+ collect :: Value.Accum Double -> (AccountTitles, T.Text)+ -> (Seq.Seq Double, Seq.Seq Double) -> Value.Accum Double+ collect total bp (hs, ns) = Value.mergeAccum total+ (Value.mergeAccum (signed Hat hs) (signed Not ns))+ where+ signed :: Hat -> Seq.Seq Double -> Value.Accum Double+ signed side values = case whichSide (side :< bp) of+ Credit -> Foldable.foldl' (flip Value.addAccum) Value.emptyAccum values+ Debit -> Value.negateAccum+ (Foldable.foldl' (flip Value.addAccum) Value.emptyAccum values)+ Side -> Value.emptyAccum+ difference = case Value.signAccum state of+ Just EQ -> (Side, 0)+ Just GT -> (Credit, Value.roundAccum state)+ Just LT -> (Debit, Value.roundAccum (Value.negateAccum state))+ Nothing -> (Side, Value.roundAccum state)++-- | Filter sides and sum each sequence in the same order as the previous implementation.+referenceAccountWithin :: AccountPairs -> (Side, Double)+referenceAccountWithin pairs+ | not (Value.isErrorValue credit || Value.isErrorValue debit)+ && abs (credit - debit) <= absTol defaultTolerance+ + relTol defaultTolerance * max (abs credit) (abs debit) = (Side, 0)+ | credit > debit = (Credit, credit - debit)+ | otherwise = (Debit, debit - credit)+ where+ credit = total Credit+ debit = total Debit+ total :: Side -> Double+ total wanted = HashMap.foldlWithKey' collect 0 pairs+ where+ collect :: Double -> (AccountTitles, T.Text)+ -> (Seq.Seq Double, Seq.Seq Double) -> Double+ collect acc bp (hs, ns) = acc + sumSide Hat hs + sumSide Not ns+ where+ sumSide :: Hat -> Seq.Seq Double -> Double+ sumSide side values+ | whichSide (side :< bp) == wanted = Foldable.foldl' (+) 0 values+ | otherwise = 0++-- | Force every compact shape through exact and tolerance-based accounting readouts.+accountPairCases :: IO ()+accountPairCases = do+ let shapes = [([3], []), ([], [5]), ([3, 7], []), ([], [5, 11]),+ ([3], [5]), ([2^53, 1], [2^53]), ([0.1, 0.2], [0.3]),+ ([1/0], []), ([], [0/0]), ([1/0, 1], [1/0])]+ forM_ [Cash, Sales] $ \title ->+ forM_ shapes $ \(hs, ns) -> verify $ HashMap.singleton (title, T.pack "shape")+ (Seq.fromList hs, Seq.fromList ns)+ verify $ HashMap.fromList+ [ ((Cash, T.pack "hat"), (Seq.singleton 3, Seq.empty))+ , ((Sales, T.pack "not"), (Seq.empty, Seq.singleton 5))+ , ((Cash, T.pack "many"), (Seq.fromList [2^53, 1], Seq.fromList [2^53, 2]))+ ]+ -- The tolerance path sees pairs after decR/decL, so repeat each side separately.+ forM_ [(Seq.singleton 3, Seq.empty, "HatOne"),+ (Seq.empty, Seq.singleton 5, "NotOne"),+ (Seq.fromList [3, 7], Seq.empty, "PairSeq"),+ (Seq.empty, Seq.fromList [5, 11], "PairSeq")] $ \(hs, ns, expected) -> do+ let input = Internal.linerFromMap+ (HashMap.singleton (Cash, T.pack "shape") (Internal.Pair hs ns)) :: Alg Double Base+ selected = if Seq.null ns then decR input else decL input+ check "accounting input shape" [expected] (shapesOf input)+ check "accounting shape after side selection" [expected] (shapesOf selected)+ where+ verify :: AccountPairs -> IO ()+ verify pairs = do+ let input = Internal.linerFromMap (fmap (uncurry Internal.Pair) pairs) :: Alg Double Base+ (expectedBalance, expectedDifference) = referenceAccountDifference pairs+ expectedWithin = referenceAccountWithin pairs+ check "two-sequence balance" expectedBalance (balance input)+ check "two-sequence diffRL" (show expectedDifference) (show (diffRL input))+ check "two-sequence balanceWithin" (fst expectedWithin == Side)+ (balanceWithin defaultTolerance input)+ check "two-sequence diffRLWithin" (show expectedWithin)+ (show (diffRLWithin defaultTolerance input))+ shapesOf :: Alg Double Base -> [String]+ shapesOf (Internal.Liner pairs _ _ _ _ _) = List.map shape (HashMap.elems pairs)+ shapesOf _ = []+ shape :: Internal.Pair Double -> String+ shape (Internal.HatOne _) = "HatOne"+ shape (Internal.NotOne _) = "NotOne"+ shape (Internal.PairSeq _ _) = "PairSeq"+ -- | Run the requested properties and fixed migration cases without tolerances. runTests :: IO () runTests = do fixedCases+ accountPairCases forM_ [readoutProperty, journalProperty, pairOrderProperty] $ \propertyToRun -> do result <- quickCheckWithResult stdArgs {maxSuccess = 200} propertyToRun unless (isSuccess result) (fail "exact readout property failed")
+ test/Algebra/PairSpec.hs view
@@ -0,0 +1,500 @@+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE TypeFamilies #-}+-- | Compare compact pairs with a two-sequence reference, including invalid raw values.+module Algebra.PairSpec (runTests) where++import qualified ExchangeAlgebra.Algebra.Internal as E+import qualified ExchangeAlgebra.Algebra.Internal as PairImport (Pair(..))+import ExchangeAlgebra.Algebra.Base+import ExchangeAlgebra.Algebra.Value+import qualified ExchangeAlgebra.Algebra.Transfer as T+import qualified Data.Sequence as S+import qualified Data.HashMap.Strict as H+import qualified Data.Foldable as F+import qualified Data.List as L+import qualified Data.Binary as B+import qualified Data.Binary.Put as P+import qualified Data.ByteString.Lazy as BL+import Control.Exception (SomeException, evaluate, try)+import Control.Monad (forM_)+import Test.QuickCheck+import Support (assertEqual, quickProp)++type Base = HatBase CountUnit+type Algebra = E.Alg Double Base++-- | Distinguish the base-level predicate from the Hat predicate used by legacy map.+newtype CustomBase = CustomBase Base+ deriving (Eq, Ord, Show, Hashable)++instance Element CustomBase where+ wildcard = CustomBase wildcard++instance BaseClass CustomBase++instance HatBaseClass CustomBase where+ type BasePart CustomBase = CountUnit+ base (CustomBase b) = base b+ hat (CustomBase b) = hat b+ merge h bp = CustomBase (merge h bp)+ toHat (CustomBase b) = CustomBase (toHat b)+ toNot (CustomBase b) = CustomBase (toNot b)+ revHat (CustomBase b) = CustomBase (revHat b)+ isHat (CustomBase b) = not (isHat b)+ isNot (CustomBase b) = not (isNot b)++-- | The previous pair representation; no compact constructors or production helpers.+data RefPair = RefPair (S.Seq Double) (S.Seq Double)++-- | Preserve the observable singleton versus map distinction.+data Ref = Empty | One Double Base | Many (H.HashMap CountUnit RefPair)++-- | Concatenate both sides in left-to-right order.+append :: RefPair -> RefPair -> RefPair+append (RefPair hs ns) (RefPair ks ms) = RefPair (hs S.>< ks) (ns S.>< ms)++-- | Unchecked reference posting, for representation and invalid-value tests.+posting :: Double -> Base -> RefPair+posting v b+ | isHat b = RefPair (S.singleton v) S.empty+ | otherwise = RefPair S.empty (S.singleton v)++-- | Insert a nonzero term into a map, combining the new pair and the old pair.+insertRef :: (RefPair -> RefPair -> RefPair)+ -> Base -> Double -> H.HashMap CountUnit RefPair -> Ref+insertRef combine b v m+ | isZeroValue v = Many m+ | otherwise = Many (H.insertWith combine (base b) (posting v b) m)++-- | Combine operands in left-to-right order on each base and side.+unionRef :: Ref -> Ref -> Ref+unionRef Empty x = x+unionRef x Empty = x+unionRef (One v b) (One w c)+ | isZeroValue v = if isZeroValue w then Empty else One w c+ | isZeroValue w = One v b+ | otherwise = insertRef (flip append) c w (H.singleton (base b) (posting v b))+unionRef (Many m) (One v b) = insertRef (flip append) b v m+unionRef (One v b) (Many m) = insertRef append b v m+unionRef (Many m) (Many n) = Many (H.unionWith append m n)++-- | Construct only the expected representation, after computing it independently.+materialize :: Ref -> Algebra+materialize Empty = E.Zero+materialize (One v b) = E.Single v b+materialize (Many m) = E.linerFromMap (H.map pair m)+ where+ pair :: RefPair -> E.Pair Double+ pair (RefPair hs ns) = E.Pair hs ns++-- | Collapse a singleton map exactly where the old implementation did.+rebuild :: H.HashMap CountUnit RefPair -> Ref+rebuild m+ | H.null m = Empty+ | otherwise = case H.toList m of+ [(b, RefPair hs ns)] -> case (F.toList hs, F.toList ns) of+ ([v], []) -> One v (Hat :< b)+ ([], [v]) -> One v (Not :< b)+ _ -> Many m+ _ -> Many m++-- | Empty-map reduction used by filter, bar, and compress; retain nonempty maps.+keepMap :: H.HashMap CountUnit RefPair -> Ref+keepMap m = if H.null m then Empty else Many m++-- | Sequence traversal used by foldEntries and mapping, before zero filtering.+entries :: Ref -> [(Double, Base)]+entries Empty = []+entries (One v b) = [(v, b)]+entries (Many m) = concatMap perBase (H.toList m)+ where+ perBase :: (CountUnit, RefPair) -> [(Double, Base)]+ perBase (bp, RefPair hs ns) =+ [(v, Hat :< bp) | v <- F.toList hs] ++ [(v, Not :< bp) | v <- F.toList ns]++-- | Old toList reverses each side, visits Not before Hat, then prepends each base.+listRef :: Ref -> [Algebra]+listRef Empty = []+listRef (One v b) = [E.Single v b]+listRef (Many m) = H.foldlWithKey' step [] m+ where+ step :: [Algebra] -> CountUnit -> RefPair -> [Algebra]+ step xs bp (RefPair hs ns) =+ F.foldl' (add Hat bp) (F.foldl' (add Not bp) xs ns) hs+ add :: Hat -> CountUnit -> [Algebra] -> Double -> [Algebra]+ add h bp xs v = if isZeroValue v then xs else E.Single v (h :< bp) : xs++-- | Encode the previous tag, count, and two-sequence layout directly.+wireRef :: Ref -> BL.ByteString+wireRef = P.runPut . putRef+ where+ putRef :: Ref -> P.Put+ putRef Empty = B.put (0 :: Int)+ putRef (One v b) = B.put (1 :: Int) >> B.put v >> B.put b+ putRef (Many m) = do+ B.put (2 :: Int)+ B.put (H.size m)+ forM_ (H.toList m) $ \(bp, RefPair hs ns) -> do+ B.put bp+ B.put (S.length hs)+ mapM_ B.put hs+ B.put (S.length ns)+ mapM_ B.put ns++-- | A predicate restriction neither aggregates nor collapses singleton maps.+filterRef :: (Double -> Base -> Bool) -> Ref -> Ref+filterRef _ Empty = Empty+filterRef f x@(One v b) = if f v b then x else Empty+filterRef f (Many m) = keepMap (H.mapMaybeWithKey step m)+ where+ step :: CountUnit -> RefPair -> Maybe RefPair+ step bp (RefPair hs ns) = nonempty+ (S.filter (\v -> f v (Hat :< bp)) hs)+ (S.filter (\v -> f v (Not :< bp)) ns)++-- | Drop only empty pairs, retaining the original order otherwise.+nonempty :: S.Seq Double -> S.Seq Double -> Maybe RefPair+nonempty hs ns+ | S.null hs && S.null ns = Nothing+ | otherwise = Just (RefPair hs ns)++-- | Exact old side states, computed from sequences rather than compact pairs.+states :: RefPair -> (Accum Double, Accum Double)+states (RefPair hs ns) = (total hs, total ns)+ where+ total :: S.Seq Double -> Accum Double+ total = F.foldl' (flip addAccum) emptyAccum++-- | Old exact bar, including negative, nonfinite, and zero raw inputs.+barRef :: Ref -> Ref+barRef Empty = Empty+barRef x@(One v _) = if isZeroValue v then Empty else x+barRef (Many m) = keepMap (H.mapMaybe step m)+ where+ step :: RefPair -> Maybe RefPair+ step pair = case signAccum residual of+ Just EQ -> Nothing+ Just LT -> settle Hat (negateAccum residual)+ _ -> settle Not residual+ where+ (hs, ns) = states pair+ residual = mergeAccum ns (negateAccum hs)+ nonfinite = signAccum (mergeAccum residual (negateAccum residual)) /= Just EQ+ settle :: Hat -> Accum Double -> Maybe RefPair+ settle side magnitude+ | isErrorValue v && nonfinite = Just pair+ | isZeroValue v = Nothing+ | otherwise = Just (posting v (side :< Yen))+ where+ v = roundAccum magnitude++-- | Old compress rounds each side independently, even for invalid raw values.+compressRef :: Ref -> Ref+compressRef Empty = Empty+compressRef x@(One v _) = if isZeroValue v then Empty else x+compressRef (Many m) = keepMap (H.mapMaybe step m)+ where+ step :: RefPair -> Maybe RefPair+ step pair = let (hs, ns) = states pair in nonempty (side hs) (side ns)+ side :: Accum Double -> S.Seq Double+ side state = let v = roundAccum state in if isZeroValue v then S.empty else S.singleton v++-- | Old tolerance bar sums sequentially, with its existing singleton shortcut.+withinRef :: Ref -> Ref+withinRef Empty = Empty+withinRef x@(One _ _) = x+withinRef (Many m) = keepMap (H.mapMaybe step m)+ where+ step :: RefPair -> Maybe RefPair+ step p@(RefPair hs ns)+ | not (isErrorValue h || isErrorValue n)+ && abs (h - n) <= absTol tolerance + relTol tolerance * max (abs h) (abs n) = Nothing+ | S.length hs == 1 && S.null ns && h > n = Just p+ | S.null hs && S.length ns == 1 && n > h = Just p+ | compare h n == GT = Just (RefPair (S.singleton (h - n)) S.empty)+ | otherwise = Just (RefPair S.empty (S.singleton (n - h)))+ where+ h = F.foldl' (+) 0 hs+ n = F.foldl' (+) 0 ns+ tolerance = defaultTolerance++-- | Apply a side-preserving value transform without changing the representation.+scaleRef :: Double -> Ref -> Ref+scaleRef _ Empty = Empty+scaleRef 0 _ = Empty+scaleRef k (One v b) = if isZeroValue (k * v) then Empty else One (k * v) b+scaleRef k (Many m) = filterRef (\v _ -> not (isZeroValue v)) $ Many+ (H.map (\(RefPair hs ns) -> RefPair (fmap (k *) hs) (fmap (k *) ns)) m)++-- | Swap sides without aggregating or changing within-side order.+hatRef :: Ref -> Ref+hatRef Empty = Empty+hatRef (One v b) = One v (revHat b)+hatRef (Many m) = Many (H.map (\(RefPair hs ns) -> RefPair ns hs) m)++-- | Concrete or wildcard selection on the CountUnit axis.+projRef :: [Base] -> Ref -> Ref+projRef qs x = case x of+ Empty -> Empty+ One v b -> if any (`matches` b) qs then One v b else Empty+ Many m -> rebuild (H.mapMaybeWithKey choose m)+ where+ matches :: Base -> Base -> Bool+ matches (h :< bp) (k :< cp) = (h == HatNot || h == k) && (bp == CountUnit || bp == cp)+ choose :: CountUnit -> RefPair -> Maybe RefPair+ choose bp (RefPair hs ns) = nonempty+ (if any (`matches` (Hat :< bp)) qs then hs else S.empty)+ (if any (`matches` (Not :< bp)) qs then ns else S.empty)++-- | Independent ordered list interpretation of typed posting mapping.+mapRef :: (Double -> Base -> (Double, Base)) -> Ref -> Ref+mapRef _ Empty = Empty+mapRef f (One v b) = let (w, c) = f v b in if isZeroValue w then Empty else One w c+mapRef f x = rebuild (foldr add H.empty (map (uncurry f) (entries x)))+ where+ add :: (Double, Base) -> H.HashMap CountUnit RefPair -> H.HashMap CountUnit RefPair+ add (v, b) m+ | isZeroValue v = m+ | otherwise = H.insertWith append (base b) (posting v b) m++-- | Legacy map reverses unchanged entries on each side, before merging collisions.+legacyMapRef :: (Double -> Base -> (Double, Base)) -> Ref -> Ref+legacyMapRef f x@(One _ _) = mapRef f x+legacyMapRef _ Empty = Empty+legacyMapRef f (Many m) = rebuild (foldr add H.empty (concatMap perBase (H.toList m)))+ where+ perBase :: (CountUnit, RefPair) -> [(Double, Base)]+ perBase (bp, RefPair hs ns) = changedH ++ changedN ++ sameH ++ sameN+ where+ (changedH, sameH) = side (Hat :< bp) hs+ (changedN, sameN) = side (Not :< bp) ns+ side :: Base -> S.Seq Double -> ([(Double, Base)], [(Double, Base)])+ side b vs = (filter ((/= b) . snd) mapped, reverse (filter ((== b) . snd) mapped))+ where+ mapped = filter (not . isZeroValue . fst) [f v b | v <- F.toList vs]+ add :: (Double, Base) -> H.HashMap CountUnit RefPair -> H.HashMap CountUnit RefPair+ add (v, b) = H.insertWith append (base b) (posting v b)++-- | The old pair ordering: exact signed classification, then lexicographic sequences.+compareRef :: RefPair -> RefPair -> Ordering+compareRef x@(RefPair hs ns) y@(RefPair ks ms) =+ compare (key x) (key y) <> compare (hs, ns) (ks, ms)+ where+ key :: RefPair -> (Int, Rational)+ key pair = case exactAccum residual of+ Just value -> (1, value)+ Nothing -> case signAccum residual of+ Just LT -> (0, 0)+ Just GT -> (2, 0)+ _ -> (3, 0)+ where+ (h, n) = states pair+ residual = negateAccum (mergeAccum n (negateAccum h))++-- | Inspect every pair produced by the implementation.+normalized :: Algebra -> Bool+normalized (E.Liner m _ _ _ _ _) = all valid (H.elems m)+ where+ valid :: E.Pair Double -> Bool+ valid (E.HatOne _) = True+ valid (E.NotOne _) = True+ valid (E.PairSeq hs ns) = (S.length hs, S.length ns) `notElem` [(1, 0), (0, 1)]+normalized _ = True++-- | Compare observable order, shape, text, and bytes; string comparison handles NaN.+check :: String -> Ref -> Algebra -> IO ()+check label ref actual = do+ assertEqual (label ++ ": bytes") (wireRef ref) (B.encode actual)+ assertEqual (label ++ ": toList") (show (listRef ref)) (show (E.toList actual))+ assertEqual (label ++ ": vals") (show (map fst (entries ref))) (show (E.vals actual))+ let expectedBases = case ref of+ Many _ -> reverse (map snd (entries ref))+ _ -> map snd (entries ref)+ expectedShow = case L.sort (listRef ref) of+ [] -> "0"+ xs -> L.intercalate " .+ " (map show xs)+ assertEqual (label ++ ": bases") expectedBases (E.bases actual)+ assertEqual (label ++ ": show") expectedShow (show actual)+ assertEqual (label ++ ": canonical") True (normalized actual)+ assertEqual (label ++ ": foldEntries")+ (show (filter (not . isZeroValue . fst) (entries ref)))+ (show (E.foldEntries (\xs v b -> xs ++ [(v, b)]) [] actual))++-- | Exercise all value operations against the old two-sequence interpretation.+checkOperations :: Ref -> IO ()+checkOperations ref = do+ let x = materialize ref+ normRef = roundAccum (foldl (\a (v, _) -> addAccum v a) emptyAccum (entries ref))+ predicate :: Double -> Base -> Bool+ predicate v b = isHat b || v > 2+ check "input" ref x+ check "bar" (barRef ref) (E.bar x)+ check "minus" (barRef ref) ((E..-) x)+ check "compress" (compressRef ref) (E.compress x)+ check "barWithin" (withinRef ref) (E.barWithin defaultTolerance x)+ check "hat" (hatRef ref) ((E..^) x)+ check "scalar" (scaleRef 2 ref) (2 E..* x)+ check "filter" (filterRef predicate ref)+ (E.filter (\(v E.:@ b) -> predicate v b) x)+ assertEqual "norm" (show (normRef :: Double)) (show (E.norm x))+ forM_ [[Hat :< Yen], [HatNot :< CountUnit], [Not :< Dollar, HatNot :< Yen]] $ \qs ->+ check "proj" (projRef qs ref) (E.proj qs x)++-- | Each generated ledger contains singleton bases of both sides and a repeated base.+genMixedPostings :: Gen [(Double, Base)]+genMixedPostings = do+ h <- choose (1, 1000)+ n <- choose (1, 1000)+ hs <- chooseInt (2, 20) >>= \count -> vectorOf count (choose (1, 1000))+ ns <- chooseInt (2, 20) >>= \count -> vectorOf count (choose (1, 1000))+ shuffle $ [(h, Hat :< Yen), (n, Not :< Dollar)]+ ++ [(v, Hat :< Euro) | v <- hs] ++ [(v, Not :< Euro) | v <- ns]++-- | Decode independently written length/value streams, including an empty map entry.+binaryTests :: IO ()+binaryTests = do+ quickProp "Pair: mixed shapes round-trip through Binary" $+ forAll genMixedPostings $ \ps -> ioProperty $ do+ let ref = foldl unionRef Empty [One v b | (v, b) <- ps]+ actual = E.fromList [v E..@ b | (v, b) <- ps]+ decoded = B.decode (B.encode actual) :: Algebra+ mixed = case actual of+ E.Liner m _ _ _ _ _ -> case (H.lookup Yen m, H.lookup Dollar m,+ H.lookup Euro m) of+ (Just (E.HatOne _), Just (E.NotOne _), Just (E.PairSeq hs ns)) ->+ S.length hs >= 2 && S.length ns >= 2+ _ -> False+ _ -> False+ assertEqual "generator includes all three shapes on every trial" True mixed+ assertEqual "Alg Binary round-trip equality" actual decoded+ check "mixed Binary reference" ref decoded+ pure True+ forM_ [([2], [3]), ([2, 5], []), ([], [3, 7]), ([], [])] $ \(hs, ns) -> do+ let pair = RefPair (S.fromList hs) (S.fromList ns)+ bytes = wireRef (Many (H.singleton Yen pair))+ expected = if null hs && null ns then Empty else Many (H.singleton Yen pair)+ decoded = B.decode bytes :: Algebra+ assertEqual "handwritten Alg bytes decode to reference" (materialize expected) decoded+ check ("handwritten Binary lengths " ++ show (length hs, length ns)) expected decoded++-- | Legacy map must not substitute a custom base predicate for the Hat predicate.+customMapTests :: IO ()+customMapTests =+ forM_ [(S.singleton 3, S.empty), (S.empty, S.singleton 5),+ (S.fromList [3, 7], S.fromList [5, 11])] $ \(hs, ns) ->+ forM_ [\v b -> (v, b), \v b -> (v, hat b :< Dollar),+ \v b -> (v, revHat b), \v _ -> (v, Hat :< Dollar),+ \_ b -> (0, b)] $ \rewrite -> do+ let ref = Many (H.singleton Yen (RefPair hs ns))+ input = E.linerFromMap (H.singleton Yen (E.Pair hs ns))+ :: E.Alg Double CustomBase+ callback :: E.Alg Double CustomBase -> E.Alg Double CustomBase+ callback (v E.:@ CustomBase b) =+ let (w, c) = rewrite v b in E.Single w (CustomBase c)+ callback E.Zero = E.Zero+ callback _ = error "customMapTests: expected one posting"+ unwrap :: E.Alg Double CustomBase -> Algebra+ unwrap E.Zero = E.Zero+ unwrap (v E.:@ CustomBase b) = E.Single v b+ unwrap (E.Liner m _ _ _ _ _) = E.linerFromMap m+ check "custom HatBaseClass legacy map" (legacyMapRef rewrite ref)+ (unwrap (E.map callback input))+ check "custom HatBaseClass dropping map" Empty (unwrap (E.map (const E.Zero) input))++-- | Constructors, selectors, and record updates work for all three shapes.+patternTests :: IO ()+patternTests = do+ forM_ [([], []), ([1], []), ([], [2]), ([1, 2], [3]), ([1], [2])] $ \(hs, ns) -> do+ let p = PairImport.Pair (S.fromList hs) (S.fromList ns) :: E.Pair Double+ E.Pair actualH actualN = p+ q = p {E._hatSide = S.singleton 7}+ r = p {E._notSide = S.empty}+ assertEqual "pattern match hat" hs (F.toList actualH)+ assertEqual "pattern match not" ns (F.toList actualN)+ assertEqual "selector hat" hs (F.toList (E._hatSide p))+ assertEqual "selector not" ns (F.toList (E._notSide p))+ assertEqual "record update hat" ([7], ns)+ (F.toList (E._hatSide q), F.toList (E._notSide q))+ assertEqual "record update not" (hs, [])+ (F.toList (E._hatSide r), F.toList (E._notSide r))+ assertEqual "Pair decoder canonical" True $ case (B.decode (B.encode p) :: E.Pair Double) of+ E.PairSeq h n -> (S.length h, S.length n) `notElem` [(1, 0), (0, 1)]+ E.HatOne _ -> True+ E.NotOne _ -> True+ let lazyValue = error "lazy payload" :: Double+ lazyPairs = [E.Pair (S.singleton lazyValue) S.empty,+ E.Pair S.empty (S.singleton lazyValue),+ E.Pair (S.singleton lazyValue) (S.singleton lazyValue)]+ forM_ lazyPairs $ \pair -> do+ result <- try (evaluate pair) :: IO (Either SomeException (E.Pair Double))+ assertEqual "pair payload remains lazy" True (either (const False) (const True) result)+ _ <- evaluate (S.length (PairImport._hatSide pair))+ _ <- evaluate (pair {PairImport._notSide = S.singleton lazyValue})+ pure ()+ let oldNegativeCount = P.runPut (B.put (-1 :: Int) >> B.put (1 :: Int) >> B.put (2 :: Double))+ decoded = B.decode oldNegativeCount :: E.Pair Double+ assertEqual "Pair decoder preserves negative-count behavior" True (E.NotOne 2 == decoded)+++-- | A generated input includes both singleton bases and repeated sides.+runTests :: IO ()+runTests = do+ patternTests+ binaryTests+ customMapTests+ quickProp "Pair: arbitrary posting lists preserve addition order and wire layout" $+ forAll (listOf ((,) <$> choose (0, 1000) <*> elements+ [Hat :< Yen, Not :< Yen, Hat :< Dollar, Not :< Euro, Not :< CountUnit])) $ \ps ->+ ioProperty $ do+ let ref = foldl unionRef Empty [One v b | (v, b) <- ps]+ actual = E.fromList [E.Single v b | (v, b) <- ps]+ check "fromList" ref actual+ checkOperations ref+ let mapped :: Double -> Base -> (Double, Base)+ mapped v b = (v + 1, if base b == Dollar then Not :< Yen else b)+ check "mapPosting" (mapRef mapped ref) (E.mapPosting mapped actual)+ check "legacy map" (legacyMapRef mapped ref)+ (E.map (\a -> let (v, b) = mapped (E._val a) (E._hatBase a)+ in E.Single v b) actual)+ check "mapMaybePosting" (mapRef (\v b -> (if v > 2 then v else 0, b)) ref)+ (E.mapMaybePosting (\v b -> if v > 2 then Just (v, b) else Nothing) actual)+ let bulk = rebuild $ foldl+ (\m (v, b) -> if isZeroValue v then m+ else H.insertWith (flip append) (base b) (posting v b) m) H.empty ps+ check "unionsMerge" bulk (E.unionsMerge [E.Single v b | (v, b) <- ps])+ check "append liners" (unionRef ref ref) (actual E..+ actual)+ forM_ (E.decBy (Just . isHat) actual) $ \part ->+ assertEqual "decBy canonical" True (normalized part)+ assertEqual "Alg decoder canonical" True (normalized (B.decode (B.encode actual)))+ pure True+ forM_ [0, -0, -1, 1e-12, 1, 0/0, 1/0, -1/0, 1e308] $ \v ->+ forM_ [RefPair (S.singleton v) S.empty, RefPair S.empty (S.singleton v),+ RefPair (S.fromList [v, 2]) (S.singleton 3)] $ \pair -> do+ checkOperations (Many (H.singleton Yen pair))+ checkOperations (One v (Hat :< Yen))+ let pairShapes = [(S.empty, S.empty)] +++ [(S.singleton v, S.empty) | v <- [0, -1, 1, 0/0, 1/0]] +++ [(S.empty, S.singleton v) | v <- [0, -1, 1, 0/0, 1/0]] +++ [(S.fromList [1, 2], S.singleton 3), (S.singleton (0/0), S.singleton 1)]+ forM_ pairShapes $ \(hs, ns) -> forM_ pairShapes $ \(ks, ms) ->+ assertEqual "Pair Ord" (compareRef (RefPair hs ns) (RefPair ks ms))+ (compare (E.Pair hs ns) (E.Pair ks ms))+ forM_ [-1, 0/0, 1/0, -1/0] $ \v -> do+ let x = materialize (Many (H.singleton Yen (RefPair (S.singleton v) S.empty)))+ rejected <- try (evaluate (E.mapPosting (\w b -> (w, b)) x))+ :: IO (Either SomeException Algebra)+ assertEqual "mapPosting rejects invalid raw values" True+ (either (const True) (const False) rejected)+ let rules = T.mkTransferRules+ [T.TransferRule (Not :< Yen) (Not :< Euro) T.Relabel,+ T.TransferRule (Hat :< Dollar) (Hat :< Euro) T.Relabel]+ ref = Many (H.fromList [(Yen, RefPair S.empty (S.fromList [1, 2])),+ (Dollar, RefPair (S.singleton 3) S.empty)])+ moved = foldl unionRef Empty+ [unionRef (One v (revHat b)) (One v (hat b :< Euro)) | (v, b) <- entries ref]+ case rules of+ Left err -> error (show err)+ Right rs -> case T.transferEntries rs (materialize ref) of+ Left err -> error (show err)+ Right result -> check "transferEntries" moved result
test/Algebra/ProjWildcardSpec.hs view
@@ -266,7 +266,7 @@ get = FixtureId <$> Binary.get -- | Compare exact coordinates, sides, and amounts independently of posting order.-observeWild :: forall coordinates. (BaseClass coordinates, AxisDecompose coordinates)+observeWild :: forall coordinates. (BaseClass coordinates, HasElementKeys coordinates) => Alg MoneyDecimal (HatBase coordinates) -> [(Hat, coordinates, MoneyDecimal)] observeWild = List.sort . foldEntries collect []@@ -322,16 +322,16 @@ type WildCoordinates = (AccountTitles, Wild TimeOfDay, Wild Text) -- | Flat tuples expose each axis key. A nested tuple stays one key at its outer position.-testWildAxisKeys :: IO ()-testWildAxisKeys = do+testWildElementKeys :: IO ()+testWildElementKeys = do assertTest "Wild flat tuple has one wildcard at the time axis" $ haveWildcard flat && not (haveWildcard (Cash, time, identifier)) assertTest "Wild nested tuple has an inner wildcard" $ haveWildcard nested && not (haveWildcard (Cash, (time, identifier))) assertTest "Wild flat tuple exposes three axis keys in coordinate order" $- toAxisKeys flat == [AxisKey Cash, AxisKey noTime, AxisKey identifier]+ toElementKeys flat == [ElementKey Cash, ElementKey noTime, ElementKey identifier] assertTest "Wild nested tuple exposes two outer keys with the pair in position two" $- toAxisKeys nested == [AxisKey Cash, AxisKey (noTime, identifier)]+ toElementKeys nested == [ElementKey Cash, ElementKey (noTime, identifier)] where noTime :: Wild TimeOfDay noTime = Wild@@ -349,7 +349,7 @@ nested = (Cash, (noTime, identifier)) -- | Exercise single and indexed projections against the same per-axis oracle.-testWildProjection :: forall coordinates. (BaseClass coordinates, AxisDecompose coordinates)+testWildProjection :: forall coordinates. (BaseClass coordinates, HasElementKeys coordinates) => String -> (WildCoordinates -> coordinates) -> IO ()@@ -410,31 +410,43 @@ (observeWild selected) (observeWild (Journal.toAlg (Journal.projWithNote [note] journal))) --- | Check source matching and target retention with both stored time coordinates.+-- | Check source matching and transfer targets for concrete and wildcard times. testWildTransfer :: IO () testWildTransfer = do assertTest "Wild concrete transfer source skips the stored Wild" $- agrees (Exactly midnight) (4 .@ Hat :< (Cash, Exactly midnight)- .+ 4 .@ Not :< (Deposits, Exactly midnight))+ agrees ledger (Exactly midnight) Wild+ (4 .@ Hat :< (Cash, Exactly midnight)+ .+ 4 .@ Not :< (Deposits, Exactly midnight)) assertTest "Wild transfer target retains both stored time coordinates" $- agrees Wild (7 .@ Hat :< (Cash, Wild)- .+ 7 .@ Not :< (Deposits, Wild)- .+ 4 .@ Hat :< (Cash, Exactly midnight)- .+ 4 .@ Not :< (Deposits, Exactly midnight))+ agrees ledger Wild Wild+ (7 .@ Hat :< (Cash, Wild)+ .+ 7 .@ Not :< (Deposits, Wild)+ .+ 4 .@ Hat :< (Cash, Exactly midnight)+ .+ 4 .@ Not :< (Deposits, Exactly midnight))+ assertTest "Exactly midnight sets the transfer target time to 00:00" $+ agrees (5 .@ Not :< (Cash, morning)) morning (Exactly midnight)+ (5 .@ Hat :< (Cash, morning)+ .+ 5 .@ Not :< (Deposits, Exactly midnight)) where ledger :: Alg MoneyDecimal (HatBase (AccountTitles, Wild TimeOfDay)) ledger = 7 .@ Not :< (Cash, Wild) .+ 4 .@ Not :< (Cash, Exactly midnight) - agrees :: Wild TimeOfDay -> Alg MoneyDecimal (HatBase (AccountTitles, Wild TimeOfDay)) -> Bool- agrees source expected =+ morning = Exactly (TimeOfDay 9 0 0)++ agrees :: Alg MoneyDecimal (HatBase (AccountTitles, Wild TimeOfDay))+ -> Wild TimeOfDay+ -> Wild TimeOfDay+ -> Alg MoneyDecimal (HatBase (AccountTitles, Wild TimeOfDay))+ -> Bool+ agrees input source target expected = case Transfer.mkTransferRules [rule] of Left _ -> False- Right rules -> case Transfer.transferEntries rules ledger of+ Right rules -> case Transfer.transferEntries rules input of Left _ -> False Right postings -> observeWild postings == observeWild expected where- rule = Transfer.TransferRule (Not :< (Cash, source)) (Not :< (Deposits, Wild))+ rule = Transfer.TransferRule (Not :< (Cash, source)) (Not :< (Deposits, target)) Transfer.Relabel -- | Replacing an account title preserves the Hat/Not side and every other coordinate.@@ -479,18 +491,16 @@ empty = Exactly "" :: Wild Text first = Exactly (FixtureId 1) second = Exactly (FixtureId 2)- firstKey = AxisKey first- secondKey = AxisKey second+ firstKey = ElementKey first+ secondKey = ElementKey second --- | Midnight stays concrete on the wrapped axis and remains a wildcard on the legacy axis.+-- | Check that midnight and 1858-11-17 can be selected as ordinary elements. testWildCalendarRegression :: IO () testWildCalendarRegression = do assertEqual "Wild TimeOfDay: midnight selects only the midnight posting" 100 (norm (proj [Not :< (Cash, Exactly midnight)] receipts)) assertEqual "Wild TimeOfDay: Wild selects all three postings" 600 (norm (proj [Not :< (Cash, Wild)] receipts))- assertEqual "legacy TimeOfDay: midnight selects all three postings" 600- (norm (proj [Not :< (Cash, midnight)] receiptsOld)) assertEqual "Wild Day: 1858-11-17 selects only that day's posting" 500 (norm (proj [Not :< (Cash, Exactly (ModifiedJulianDay 0))] dated)) assertEqual "Wild Day: sale totals 500 on both debit and credit" (500, 500)@@ -501,11 +511,6 @@ .+ 200 .@ Not :< (Cash, Exactly (TimeOfDay 9 0 0)) .+ 300 .@ Not :< (Cash, Wild) - receiptsOld :: Alg MoneyDecimal (HatBase (AccountTitles, TimeOfDay))- receiptsOld = 100 .@ Not :< (Cash, midnight)- .+ 200 .@ Not :< (Cash, TimeOfDay 9 0 0)- .+ 300 .@ Not :< (Cash, midnight)- sale :: Alg MoneyDecimal (HatBase (AccountTitles, Wild Day)) sale = 500 .@ Not :< (Cash, Exactly (fromGregorian 2026 1 10)) .+ 500 .@ Not :< (Sales, Exactly (fromGregorian 2026 1 10))@@ -537,7 +542,7 @@ (forAll genConcreteCase propConcreteRegression) testWildAxis "Wild TimeOfDay" [midnight, TimeOfDay 9 0 0] testWildAxis "Wild Day" [ModifiedJulianDay (-1), ModifiedJulianDay 0, ModifiedJulianDay 1]- testWildAxisKeys+ testWildElementKeys testWildProjection "flat tuple" id testWildProjection "nested tuple" (\(title, time, identifier) -> (title, (time, identifier))) testWildTransfer
test/Golden/ReadoutBaseline.hs view
@@ -13,7 +13,6 @@ import qualified Data.List as L import qualified Data.Map.Strict as M import qualified Data.Sequence as Seq-import qualified Data.Set as S import Data.Text (Text) import qualified Data.Text as T import GHC.Float (castDoubleToWord64)@@ -28,7 +27,6 @@ import qualified ExchangeAlgebra.Journal.Transfer.Rule as JR import qualified ExchangeAlgebra.Accounting.Statements.Metric as Metric import qualified ExchangeAlgebra.Accounting.TrialBalance.Balance as TB-import qualified ExchangeAlgebra.Accounting.TrialBalance.Validation as Validation import ExchangeAlgebra.Algebra.Value (MoneyDecimal) -- | Account-only bases for the main readout series.@@ -102,6 +100,22 @@ errorName :: Show e => e -> Text errorName = T.takeWhile (\character -> character /= ' ' && character /= '{') . T.pack . show +-- | A closing failure shown by its cause. The baseline fixtures name the+-- transfer failure, recorded before 'Closing.ClosingError' wrapped it.+newtype ClosingCause = ClosingCause String++instance Show ClosingCause where+ show (ClosingCause cause) = cause++-- | Replace a closing failure with its cause: the transfer failure inside+-- 'Closing.ClosingTransferError', or the whole failure otherwise.+closingCause :: Show v+ => Either (Closing.ClosingError v ReadoutBase) a -> Either ClosingCause a+closingCause = either (Left . ClosingCause . cause) Right+ where+ cause (Closing.ClosingTransferError failure) = show failure+ cause failure = show failure+ -- | Render a checked algebra result and its sorted postings. algEitherRows :: (Show e, GoldenValue v)@@ -259,11 +273,8 @@ (compare (pair Cash [1]) (pair Cash [2, 3])) ++ shownRow "Pair.compare" "Sales notes=1,2 vs Sales note=3" (compare (pair Sales [1, 2]) (pair Sales [3]))- ++ algEitherRows "closingEntries" "Alg" (Closing.closingEntries input)+ ++ algEitherRows "closingEntries" "Alg" (closingCause (Closing.closingEntries input)) ++ balanceRows (TB.accountBalances input)- ++ shownRow "trialBalanceFindings" "BeforeClosing" (Validation.trialBalanceFindings tbInput)- ++ scalarRow "trialBalanceFindings.debitTotal" "BeforeClosing" (norm (decL input))- ++ scalarRow "trialBalanceFindings.creditTotal" "BeforeClosing" (norm (decR input)) ++ checkedRows ++ metricRows (Metric.periodResultOfAlg input) where@@ -278,7 +289,6 @@ , title == account, note `elem` selectedNotes]) (Seq.fromList [value | Posting value Not title note <- postings , title == account, note `elem` selectedNotes])- tbInput = Validation.TrialBalanceInput input Validation.BeforeClosing M.empty [] S.empty checkedRows | name == "f-dec2" = checkedBoundaryRows (norm input) | otherwise = []@@ -297,7 +307,7 @@ ++ scalarRow "projWithNoteBaseNetNorm" "notes=1,2,Sales" (EJ.projWithNoteBaseNetNorm [1, 2] [Not :< Sales] input) ++ postingJournalRows "compress" "all" (compress input)- ++ algEitherRows "closingEntries" "Journal" (Closing.closingEntries (EJ.toAlg input))+ ++ algEitherRows "closingEntries" "Journal" (closingCause (Closing.closingEntries (EJ.toAlg input))) where input = journal postings
test/Golden/WireFormat.hs view
@@ -29,7 +29,7 @@ import ExchangeAlgebra.Algebra.Base import qualified ExchangeAlgebra.Algebra.Internal as EA-import qualified ExchangeAlgebra.Algebra.Transfer.Rule as Rule+import qualified ExchangeAlgebra.Algebra.Transfer as Rule import qualified ExchangeAlgebra.Accounting.Closing as Closing import qualified ExchangeAlgebra.Journal as Journal import qualified ExchangeAlgebra.Journal.Core as JournalCore@@ -82,16 +82,10 @@ , eq "Alg" "Zero" (EA.Zero :: EA.Alg Double WireBase) , eq "Alg" "singleton" (1 `EA.Single` (Hat :< Cash) :: EA.Alg Double WireBase) , eq "Alg" "repeated base on both sides"- (EA.fromList [1 `EA.Single` (Hat :< Cash), 2 `EA.Single` (Hat :< Cash)- , 3 `EA.Single` (Not :< Cash), 4 `EA.Single` (Not :< Sales)]- :: EA.Alg Double WireBase)+ repeatedBaseAlg , eq "TransferScale" "Relabel" (Rule.Relabel :: Rule.TransferScale Double)- , eq "TransferScale" "MulBy" (Rule.MulBy 2 :: Rule.TransferScale Double)- , eq "TransferScale" "DivBy" (Rule.DivBy 0.5 :: Rule.TransferScale Double)- , eq "TransferRule" "relabel" (Rule.relabel (Hat :< Cash) (Not :< Sales)+ , eq "TransferRule" "Relabel" (Rule.TransferRule (Hat :< Cash) (Not :< Sales) Rule.Relabel :: Rule.TransferRule Double WireBase)- , eq "TransferRule" "multiply" (Rule.TransferRule (Not :< Sales)- (Hat :< Cash) (Rule.MulBy 2) :: Rule.TransferRule Double WireBase) , eq "TransferRules" "empty" (validated [] :: Rule.TransferRules Double WireBase) , eq "TransferRules" "one" (validated [ruleA])@@ -119,8 +113,8 @@ repeated = EA.fromList [1 `EA.Single` (Hat :< Cash), 2 `EA.Single` (Hat :< Cash) , 3 `EA.Single` (Not :< Cash)] singleton = EA.fromList [4 `EA.Single` (Not :< Sales)]- ruleA = Rule.relabel (Hat :< Cash) (Hat :< Sales)- ruleB = Rule.relabel (Not :< Cash) (Not :< Sales)+ ruleA = Rule.TransferRule (Hat :< Cash) (Hat :< Sales) Rule.Relabel+ ruleB = Rule.TransferRule (Not :< Cash) (Not :< Sales) Rule.Relabel validated :: [Rule.TransferRule Double WireBase] -> Rule.TransferRules Double WireBase validated rules = case Rule.mkTransferRules rules of Right value -> value@@ -130,6 +124,15 @@ Right result -> result Left _ -> error "wire fixture: expected valid Posted" +-- | Repeated terms on both sides and more than one base.+repeatedBaseAlg :: EA.Alg Double WireBase+repeatedBaseAlg = EA.fromList+ [ 1 `EA.Single` (Hat :< Cash)+ , 2 `EA.Single` (Hat :< Cash)+ , 3 `EA.Single` (Not :< Cash)+ , 4 `EA.Single` (Not :< Sales)+ ]+ eq :: (Eq a, Binary.Binary a) => Text -> Text -> a -> WireCase eq name description value = WireCase name description value (==) @@ -170,7 +173,7 @@ checkFixture = do let path = fixtureDir ++ "/wire-format.tsv" boundaryPath = fixtureDir ++ "/decode-boundaries.tsv"- unless (length cases == 287 && length rejected == 23 && length accepted == 1)+ unless (length cases == 284 && length rejected == 23 && length accepted == 1) (fail "wire-format-p2: case count differs") regen <- lookupEnv "EA_REGEN_GOLDEN" case regen of@@ -188,23 +191,48 @@ (fail "wire-format-p2: decode boundary bytes differ") forM_ rejected checkRejected forM_ accepted checkAccepted+ checkLegacyRepeatedBase checkWireLaws checkRow :: (WireCase, Text) -> IO () checkRow (WireCase name description expected same, row) = case T.splitOn "\t" row of [rowName, rowDescription, bytesText]- | rowName == name && rowDescription == description ->- case unhex bytesText of- Nothing -> fail "wire-format-p2: invalid hex"- Just bytes -> case Binary.decodeOrFail bytes of- Left (_, _, message) -> fail ("wire-format-p2: decode failed: " ++ message)- Right (rest, _, actual) -> do- unless (BL.null rest) (fail "wire-format-p2: trailing bytes")- unless (same expected actual)- (fail "wire-format-p2: decoded value differs")+ | rowName == name && rowDescription == description -> do+ actual <- decodeFixtureValue bytesText+ unless (same expected actual)+ (fail "wire-format-p2: decoded value differs") _ -> fail "wire-format-p2: invalid row" +-- | Decode a fixture value and require the decoder to consume all bytes.+decodeFixtureValue :: Binary.Binary a => Text -> IO a+decodeFixtureValue bytesText = case unhex bytesText of+ Nothing -> fail "wire-format-p2: invalid hex"+ Just bytes -> case Binary.decodeOrFail bytes of+ Left (_, _, message) -> fail ("wire-format-p2: decode failed: " ++ message)+ Right (rest, _, value) -> do+ unless (BL.null rest) (fail "wire-format-p2: trailing bytes")+ pure value++-- | Check that the exact 0.6 bytes preserve the original term sequences.+-- The 0.7 fixture uses the current encoding of the same algebra.+checkLegacyRepeatedBase :: IO ()+checkLegacyRepeatedBase = do+ legacy <- decodeFixtureValue legacyHex+ current <- decodeFixtureValue (hex (Binary.encode repeatedBaseAlg))+ assertEqual "Alg 0.6 bytes decode to the original repeated-base value"+ repeatedBaseAlg legacy+ assertEqual "Alg 0.6 and 0.7 bytes decode to the same repeated-base value"+ legacy current+ where+ legacyHex = T.concat+ [ "0000000000000002000000000000000280000000000000000002010100000000"+ , "0000000700000000000010ffffffffffffffcc01010000000000000007000000"+ , "00000010ffffffffffffffcd0000000000000001010100000000000000070000"+ , "0000000018ffffffffffffffcd803e0000000000000000000000000000000101"+ , "01000000000000000700000000000010ffffffffffffffce"+ ]+ data DecodeCase = forall a. Binary.Binary a => DecodeCase String BL.ByteString (Proxy a) renderBoundaries :: Text@@ -224,16 +252,14 @@ , DecodeCase "Posted infinity" (Binary.encode (1 / 0 :: Double)) (Proxy :: Proxy (Posted Double)) , DecodeCase "Posted above bound" (Binary.encode (2 ^ (901 :: Int) :: Double)) (Proxy :: Proxy (Posted Double))- , DecodeCase "TransferRules zero coefficient"- (Binary.encode [Rule.TransferRule (Hat :< Cash) (Hat :< Sales)- (Rule.MulBy (0 :: Double))])- (Proxy :: Proxy (Rule.TransferRules Double WireBase))+ , DecodeCase "TransferScale removed operation" (BL.singleton 1)+ (Proxy :: Proxy (Rule.TransferScale Double)) , DecodeCase "TransferRules overlap"- (Binary.encode ([ Rule.relabel (Hat :< Cash) (Hat :< Sales)- , Rule.relabel (Hat :< Cash) (Hat :< Sales)]+ (Binary.encode ([ Rule.TransferRule (Hat :< Cash) (Hat :< Sales) Rule.Relabel+ , Rule.TransferRule (Hat :< Cash) (Hat :< Sales) Rule.Relabel] :: [Rule.TransferRule Double WireBase]) :: BL.ByteString) (Proxy :: Proxy (Rule.TransferRules Double WireBase))- , DecodeCase "AccountTitles unused code" (Put.runPut (Put.putWord16be 0x80F3))+ , DecodeCase "AccountTitles unused code" (Put.runPut (Put.putWord16be 0x80F4)) (Proxy :: Proxy AccountTitles) , DecodeCase "AccountTitles old code" (Put.runPut (Put.putWord16be 0x0000)) (Proxy :: Proxy AccountTitles)@@ -356,10 +382,10 @@ assertEqual "HatNot standalone base roundtrip" (HatNot :< Cash) (Binary.decode (Binary.encode (HatNot :< Cash))) let note = ("buy" :: String, 7 :: Int)- oldTerm :: JournalCore.HasTermAxis n => n -> JournalCore.TermOf n- oldTerm = Policy.termOf- assertEqual "HasTermAxis old and new paths share the same instance"- (JournalCore.termOf note) (oldTerm note)+ oldTerm :: JournalCore.HasNotePeriod n => n -> JournalCore.PeriodOf n+ oldTerm = Policy.periodOf+ assertEqual "HasNotePeriod old and new paths share the same instance"+ (JournalCore.periodOf note) (oldTerm note) where law :: ( EA.HatVal v, HatBaseClass b, Binary.Binary v , Binary.Binary b, Binary.Binary (BasePart b)) => [(Int, EA.Alg v b)] -> Bool
test/Golden/WriteRows.hs view
@@ -27,7 +27,10 @@ type MinBase = HatBase AccountTitles type MinTransaction = Alg MoneyDecimal MinBase-type ADBase = HatBase (AccountTitles, Day)++-- | Hat base for dated correction fixtures.+type ADBase = HatBase (AccountTitles, Wild Day)+ type ADTransaction = Alg MoneyDecimal ADBase writeRowsFixtureDir :: FilePath@@ -282,11 +285,15 @@ ex8Mk :: MkBase MinBase ex8Mk = (:<) +-- | Extract the date for the journal and account ledger rows.+-- Invariant: Every correction fixture entry is constructed with 'Exactly'. ex8GetDay :: ADBase -> Day-ex8GetDay (_ :< (_, day)) = day+ex8GetDay (_ :< (_, Exactly day)) = day+ex8GetDay (_ :< (_, Wild)) = error "correction fixture requires a date on every entry" -ex8D :: Integer -> Int -> Int -> Day-ex8D = fromGregorian+-- | Build a concrete date element for a correction fixture entry.+ex8D :: Integer -> Int -> Int -> Wild Day+ex8D year month day = Exactly (fromGregorian year month day) ex8WrongEntry, ex8CancelEntry, ex8CorrectEntry :: ADTransaction ex8WrongEntry =
+ test/IO/AccountNamesSpec.hs view
@@ -0,0 +1,334 @@+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeFamilies #-}++-- | Name-table laws and user-vocabulary input boundary regressions.+module IO.AccountNamesSpec (runTests) where++import Control.Monad (forM_)+import Data.Hashable (Hashable)+import Data.List (delete, nub)+import Data.List.NonEmpty (NonEmpty(..))+import Data.Text (Text)+import qualified Data.Text as T+import GHC.Generics (Generic)+import Test.QuickCheck (Gen, chooseInt, elements, forAll, listOf, vectorOf)++import ExchangeAlgebra.Accounting.Account+import ExchangeAlgebra.Accounting.Exchange (ExBaseClass(..), journalForSides)+import ExchangeAlgebra.Algebra.Base (BaseClass, Element(..), Hat(..), HatBase((:<)))+import ExchangeAlgebra.Algebra.Core (Alg, (.@), Redundant((.+)))+import ExchangeAlgebra.Algebra.Value (MoneyDecimal)+import qualified ExchangeAlgebra.IO.Input as Input+import qualified ExchangeAlgebra.IO.Input.Csv as Csv+import Support (assertEqual, quickProp)++-- | Own all instances locally, including the exchange base, to avoid orphans.+data FirmTitle+ = Std AccountTitles+ | SubscriptionRevenue+ | Suspense+ deriving (Eq, Ord, Show, Generic)++instance Hashable FirmTitle++instance Element FirmTitle where+ wildcard = Std AccountTitle++instance BaseClass FirmTitle++instance ExBaseClass (HatBase FirmTitle) where+ type TitleOf (HatBase FirmTitle) = FirmTitle+ getAccountTitle (_ :< title) = title+ setAccountTitle (direction :< _) title = direction :< title++instance AccountVocabulary FirmTitle where+ vocabSpec (Std title) = accountSpec title+ vocabSpec SubscriptionRevenue =+ renamed "Subscription revenue" "定期便売上" ["subscriptions", "売上"]+ vocabSpec Suspense = renamed "Suspense" "仮勘定" []+ vocabSemantics (Std title) = accountSemantics title+ vocabSemantics SubscriptionRevenue = accountSemantics Sales+ vocabSemantics Suspense = Nothing+ closingTarget = Std RetainedEarnings++-- | Keep the revenue classification and replace its external names.+renamed :: Text -> Text -> [Text] -> Maybe AccountSpec+renamed english label aliases = fmap+ (\spec -> spec { asNameEn = english, asNameJa = label+ , asLabelJa = label, asAliases = aliases })+ (accountSpec Sales)++-- | Represent an entry in the test chart with exact decimal amounts.+type FirmEntry = Alg MoneyDecimal (HatBase FirmTitle)++-- | Include the wildcard in the input list to exercise its exclusion.+firmNames :: Input.AccountNameTable FirmTitle+firmNames = Input.vocabularyNames+ [Std AccountTitle, Std Cash, Std Sales, SubscriptionRevenue, Suspense]++-- | Look up names in the test chart.+resolve :: Input.AccountResolver FirmTitle+resolve = Input.resolveWith firmNames++-- | Deliberately list-based reference: preserve first occurrence of each candidate.+reference :: Eq a => (Text -> Text) -> [(Text, a)] -> Input.AccountResolver a+reference normalize pairs query = case nub+ [title | (name, title) <- pairs, normalize name == normalize query] of+ [] -> Left (Input.UnknownAccount query)+ [title] -> Right title+ titles -> Left (Input.AmbiguousAccount query titles)++-- | Draw from a small alphabet with normalization collisions.+smallName :: Gen Text+smallName = elements ["", "a", "A", "b", "B", " a ", "xA", "売上", "shared"]++-- | Generate repeated names and repeated candidates independently.+namePairs :: Gen [(Text, Int)]+namePairs = listOf ((,) <$> smallName <*> chooseInt (0, 3))++-- | Exercise exact, case-insensitive, and non-idempotent normalization.+normalizers :: [(String, Text -> Text)]+normalizers = [("exact", id), ("lower", T.toLower), ("prefix", ("x" <>))]++-- | Compare construction and extension against ordered input pairs.+nameTableLaws :: IO ()+nameTableLaws = forM_ normalizers $ \(label, normalize) -> do+ quickProp ("T1 ordered unique candidates: " ++ label) $+ forAll namePairs $ \pairs -> forAll smallName $ \query ->+ let queries = query : map fst pairs+ actual = Input.resolveWith (Input.accountNameTable normalize pairs)+ in all (\q -> actual q == reference normalize pairs q) queries+ quickProp ("T2 extension equals append: " ++ label) $+ forAll namePairs $ \old -> forAll namePairs $ \new ->+ forAll smallName $ \query ->+ let extended = Input.resolveWith+ (Input.extendAccountNames new (Input.accountNameTable normalize old))+ appended = Input.resolveWith (Input.accountNameTable normalize (old ++ new))+ in all (\q -> extended q == appended q) (query : map fst (old ++ new))++-- | Reconstruct the historical candidate order for all built-in names.+legacyLaws :: IO ()+legacyLaws = do+ let titles = concreteAccountTitles+ aliasOrder = CommunicationExpenses : delete CommunicationExpenses titles+ pairs = [(T.pack (show title), title) | title <- titles]+ ++ [(alias, title) | title <- aliasOrder, alias <- accountAliases title]+ queries = "AccountTitle" : map fst pairs+ expected = reference Input.normalizeTitle pairs+ expectedAll = [(query, expected query) | query <- queries]+ assertEqual "T3 legacy parseAccountTitle, all known names" expectedAll+ [(query, Input.parseAccountTitle query) | query <- queries]+ assertEqual "T3 default table matches legacy reference, all known names" expectedAll+ [(query, Input.resolveWith Input.defaultAccountNames query) | query <- queries]+ quickProp "T3 legacy reference on generated and known queries" $+ forAll (elements queries) $ \known -> forAll smallName $ \randomQuery ->+ all (\q -> Input.parseAccountTitle q == expected q+ && Input.resolveWith Input.defaultAccountNames q == expected q)+ [known, randomQuery, " " <> T.toUpper known <> " "]++-- | Check the names exposed by each listed title and its specification.+vocabularyLaws :: IO ()+vocabularyLaws = do+ let titles = [Std Cash, Std Sales, SubscriptionRevenue, Suspense]+ names title = T.pack (show title) : case vocabSpec title of+ Just spec -> asNameEn spec : asLabelJa spec : asAliases spec+ Nothing -> []+ entries = [(name, title) | title <- titles, name <- names title]+ forM_ entries $ \(name, _) ->+ assertEqual "T4 every listed title's show, English name, Japanese label and aliases"+ (reference Input.normalizeTitle entries name) (resolve name)+ forM_ ["SubscriptionRevenue", "Subscription revenue", "定期便売上", "subscriptions"] $+ \name -> assertEqual "T4 vocabulary names" (Right SubscriptionRevenue) (resolve name)+ assertEqual "T4 wrapped built-in show" (Right (Std Cash)) (resolve "Std Cash")+ assertEqual "T4 wrapped English name" (Right (Std Cash)) (resolve "Cash")+ assertEqual "T4 wrapped Japanese label" (Right (Std Cash)) (resolve "現金")+ assertEqual "T4 wildcard excluded" (Left (Input.UnknownAccount "Std AccountTitle"))+ (resolve "Std AccountTitle")+ assertEqual "T4 vocabulary specs share a label in list order"+ (Left (Input.AmbiguousAccount "売上" [Std Sales, SubscriptionRevenue])) (resolve "売上")++-- | Resolve renamed English labels against the complete built-in vocabulary.+builtInEnglishNames :: IO ()+builtInEnglishNames = do+ let resolveBuiltIn = Input.resolveWith (Input.vocabularyNames concreteAccountTitles)+ forM_ [ ("Supplies on hand", SuppliesOnHand)+ , ("Supplies expense", SuppliesExpenses)+ , ("Buildings", Building)+ ] $ \(name, title) ->+ assertEqual ("built-in English name " ++ T.unpack name)+ (Right title) (resolveBuiltIn name)+ forM_ ["Supplies", "real estate"] $ \name ->+ assertEqual ("retired English name " ++ T.unpack name)+ (Left (Input.UnknownAccount name)) (resolveBuiltIn name)++-- | Compare CSV rows with their algebra projection and check parser errors.+csvLaws :: IO ()+csvLaws = do+ quickProp "T5 CSV term is the projection of noted rows, preserving repetition" $+ forAll (chooseInt (0, 12)) $ \count ->+ forAll (vectorOf count ((,) <$> elements [Debit, Credit] <*> chooseInt (0, 100))) $+ \rows ->+ let triples = [(side, Std Cash, fromIntegral amount :: MoneyDecimal)+ | (side, amount) <- rows]+ csv = T.unlines ("side,account,amount,note" :+ [T.intercalate "," [sideText side, "Cash", T.pack (show amount), "note"]+ | (side, amount) <- rows])+ expected = Right (journalForSides triples :: FirmEntry)+ in Csv.parseJournalCsvBy resolve Csv.scientificAmount csv == expected+ && fmap (journalForSides . map dropNote)+ (Csv.parseNotedJournalCsvBy resolve Csv.scientificAmount csv) == expected+ && (Csv.parseJournalCsvBy Input.parseAccountTitle Csv.scientificAmount csv+ == (Csv.parseJournalCsvWith Csv.scientificAmount csv+ :: Either Input.ConvError (Alg MoneyDecimal (HatBase AccountTitles))))+ && (Csv.parseNotedJournalCsvBy Input.parseAccountTitle Csv.scientificAmount csv+ == (Csv.parseNotedJournalCsv Csv.scientificAmount csv+ :: Either Input.ConvError [(Side, AccountTitles, MoneyDecimal, Text)]))+ let row name = "side,account,amount,note\ndebit," <> name <> ",0,zero\n"+ wildcardResolver _ = Right (Std AccountTitle)+ assertEqual "T5 wildcard CSV field is trimmed"+ (Left (Input.UnknownAccount "wild"))+ (Csv.parseJournalCsvBy wildcardResolver Csv.scientificAmount (row " wild ")+ :: Either (Input.ConvErrorOf FirmTitle) FirmEntry)+ assertEqual "T5 wildcard noted CSV field is trimmed"+ (Left (Input.UnknownAccount "wild"))+ (Csv.parseNotedJournalCsvBy wildcardResolver Csv.scientificAmount (row " wild ")+ :: Either (Input.ConvErrorOf FirmTitle) [(Side, FirmTitle, MoneyDecimal, Text)])+ forM_ [-1, 1 / 0 :: Double] $ \bad -> do+ let amount _ = Right bad+ csv = "side,account,amount\ndebit,Cash, raw \n"+ expected = Left (Input.BadAmount "raw")+ assertEqual "T5 custom invalid amount in term CSV" expected+ (Csv.parseJournalCsvBy resolve amount csv)+ assertEqual "T5 custom invalid amount in noted CSV" expected+ (Csv.parseNotedJournalCsvBy resolve amount csv)+ assertEqual "T5 zero row retains note"+ (Right [(Debit, Std Cash, 0 :: MoneyDecimal, "zero")])+ (Csv.parseNotedJournalCsvBy resolve Csv.scientificAmount (row "Cash"))+ assertEqual "T5 zero row contributes no posting" (Right (mempty :: FirmEntry))+ (Csv.parseJournalCsvBy resolve Csv.scientificAmount (row "Cash"))+ where+ dropNote (side, title, amount, _) = (side, title, amount)+ sideText Debit = "debit"+ sideText Credit = "credit"+ sideText Side = "Side"++-- | Check row diagnostics and balance using the test chart.+checkedLaws :: IO ()+checkedLaws = do+ let check = Input.checkedEntryTextBy resolve OrdinaryJournal+ wildcardResolve = Input.resolveWith+ (Input.extendAccountNames [("wild", Std AccountTitle)] firmNames)+ expected = 100 .@ Not :< Std Cash .+ 100 .@ Not :< SubscriptionRevenue :: FirmEntry+ assertEqual "T6 own vocabulary accepted" (Right expected)+ (check [("debit", "Cash", 100), ("credit", "subscriptions", 100)])+ assertEqual "T6 missing semantics follows amount error"+ (Left (Input.NonPositiveAmount 0 Suspense 0 :|+ [ Input.MissingPostingSemantics 0 Suspense+ , Input.NonPositiveAmount 1 Suspense 0+ , Input.MissingPostingSemantics 1 Suspense ]))+ (check [("debit", "Suspense", 0), ("credit", "Suspense", 0)])+ assertEqual "T6 resolved wildcard is structural"+ (Left (Input.WildcardAccount 0 :| []))+ (Input.checkedEntryTextBy wildcardResolve OrdinaryJournal+ [("debit", "wild", 100), ("credit", "Cash", 100 :: MoneyDecimal)])+ assertEqual "T6 unresolved amounts still enter balance"+ (Left (Input.EntryParse 1 (Input.UnknownAccount "unknown") :| [Input.Imbalanced 100 90]))+ (check [("debit", "Cash", 100), ("credit", "unknown", 90)])+ let invalid = [("invalid", "Suspense", 0 :: MoneyDecimal)]+ assertEqual "T6 invalid side suppresses checked structural checks"+ (Left (Input.EntryParse 0 (Input.UnknownSide "invalid") :| [])) (check invalid)+ assertEqual "T6 certification checks a row even with invalid side"+ (Input.Rejected (Input.EntryErrors ("invalid" :: Text)+ (Input.EntryParse 0 (Input.UnknownSide "invalid") :|+ [ Input.NonPositiveAmount 0 Suspense 0+ , Input.MissingPostingSemantics 0 Suspense ]) :| []))+ (Input.certifyJournalTextBy resolve OrdinaryJournal [("invalid", invalid)])++-- | Distinguish vocabulary gaps from structural and per-entry balance errors.+certificationLaws :: IO ()+certificationLaws = do+ let shared = Input.resolveWith+ (Input.extendAccountNames [("shared", Std Cash), ("shared", SubscriptionRevenue)]+ firmNames)+ certify = Input.certifyJournalTextBy shared OrdinaryJournal+ batch =+ [ ("z", [("debit", "unknown", 10), ("credit", "shared", 10)])+ , ("a", [("debit", "Cash", 20), ("credit", "subscriptions", 20)])+ , ("m", [("debit", "Cash", 30), ("credit", "other", 30)])+ ] :: [(Text, [(Text, Text, MoneyDecimal)])]+ assertEqual "T7 unresolved groups keep transaction and row order; omit empty groups"+ (Input.BalancedUnresolved+ [("a", [(Debit, Std Cash, 20), (Credit, SubscriptionRevenue, 20)])+ ,("m", [(Debit, Std Cash, 30)])]+ [("z", [(0, "unknown", Input.UnknownAccount "unknown")+ ,(1, "shared", Input.AmbiguousAccount "shared"+ [Std Cash, SubscriptionRevenue])])+ ,("m", [(1, "other", Input.UnknownAccount "other")])]+ 60 60)+ (certify batch)+ let wildcardResolve = Input.resolveWith+ (Input.extendAccountNames [("wild", Std AccountTitle)] firmNames)+ assertEqual "T7 wildcard is rejected rather than unresolved"+ (Input.Rejected (Input.EntryErrors ("wild" :: Text)+ (Input.WildcardAccount 0 :| []) :| []))+ (Input.certifyJournalTextBy wildcardResolve OrdinaryJournal+ [("wild", [("debit", "wild", 10), ("credit", "Cash", 10 :: MoneyDecimal)])])+ let badResolver _ = Left (Input.BadAmount "resolver")+ row = [("debit", "anything", 10 :: MoneyDecimal)]+ assertEqual "T7 non-vocabulary resolver failure is EntryParse"+ (Left (Input.EntryParse 0 (Input.BadAmount "resolver") :| [Input.Imbalanced 10 0]))+ (Input.checkedEntryTextBy badResolver OrdinaryJournal row+ :: Either (NonEmpty (Input.EntryErrorOf FirmTitle MoneyDecimal)) FirmEntry)+ assertEqual "T7 non-vocabulary resolver failure rejects certification"+ (Input.Rejected (Input.EntryErrors ("bad" :: Text)+ (Input.EntryParse 0 (Input.BadAmount "resolver") :| []) :| []))+ (Input.certifyJournalTextBy (badResolver :: Input.AccountResolver FirmTitle)+ OrdinaryJournal [("bad", row)])+ assertEqual "T7 literal Side is wildcard side"+ (Input.Rejected (Input.EntryErrors ("side" :: Text)+ (Input.WildcardSide 0 :| []) :| []))+ (certify [("side", [("Side", "Cash", 10 :: MoneyDecimal)])])+ assertEqual "T7 separate transaction imbalances cannot cancel"+ (Input.Rejected+ (Input.EntryErrors ("debit" :: Text) (Input.Imbalanced 10 0 :| []) :|+ [Input.EntryErrors "credit" (Input.Imbalanced 0 10 :| [])]))+ (certify [("debit", [("debit", "unknown", 10 :: MoneyDecimal)])+ ,("credit", [("credit", "unknown", 10)])])++-- | Check each concrete title in every posting context against the registry.+postingPolicyLaw :: IO ()+postingPolicyLaw =+ assertEqual "T8 checked capability, all concrete titles and contexts" [] failures+ where+ failures =+ [ (title, context, expected, actual)+ | title <- concreteAccountTitles+ , context <- [OrdinaryJournal, ClosingProcess, ConsolidationWorksheet, EngineComputation]+ , let capability = postingCapabilityFor title+ name = T.pack (show title)+ rows = [("debit", name, 1), ("credit", name, 1)]+ expected+ | postingAllowedIn context capability = Right+ (journalForSides [(Debit, title, 1), (Credit, title, 1)])+ | otherwise = Left+ (Input.PostingNotAllowed 0 title capability context :|+ [Input.PostingNotAllowed 1 title capability context])+ actual = Input.checkedEntryTextBy Input.parseAccountTitle context rows+ :: Either (NonEmpty (Input.EntryError MoneyDecimal))+ (Alg MoneyDecimal (HatBase AccountTitles))+ , expected /= actual+ ]++-- | Run generated lookup laws before input and posting-policy regressions.+runTests :: IO ()+runTests = do+ nameTableLaws+ legacyLaws+ vocabularyLaws+ builtInEnglishNames+ csvLaws+ checkedLaws+ certificationLaws+ postingPolicyLaw
test/IO/InputOutputSpec.hs view
@@ -125,11 +125,15 @@ testWriteJournalPinned :: IO () testWriteJournalPinned = withTestTemporaryFile $ \path -> do- let d1 = fromGregorian 2024 4 1- d2 = fromGregorian 2024 4 2- d3 = fromGregorian 2024 4 3- getDay' :: HatBase (AccountTitles, Day) -> Day- getDay' (_ :< (_, d)) = d+ let d1 = Exactly (fromGregorian 2024 4 1)+ d2 = Exactly (fromGregorian 2024 4 2)+ d3 = Exactly (fromGregorian 2024 4 3)++ -- Invariant: Every entry in alg has a date.+ getDay' :: HatBase (AccountTitles, Wild Day) -> Day+ getDay' (_ :< (_, Exactly day)) = day+ getDay' (_ :< (_, Wild)) = error "writeJournal fixture requires a date on every entry"+ alg = (100 .@ Not :< (Cash, d1)) .+ (100 .@ Not :< (CapitalStock, d1)) .+ (50 .@ Not :< (Cash, d2))@@ -137,7 +141,7 @@ .+ (30 .@ Not :< (Cash, d3)) .+ (10 .@ Not :< (AccountsReceivable, d3)) .+ (40 .@ Not :< (Sales, d3))- :: EA.Alg Double (HatBase (AccountTitles, Day))+ :: EA.Alg Double (HatBase (AccountTitles, Wild Day)) EW.writeJournal path alg getDay' raw <- readFileStrict path let lns = lines raw@@ -148,10 +152,11 @@ "\"2024-04-01\",\"Cash\",\"100.0\",\"CapitalStock\",\"100.0\"" (lns !! 1) assertEqual "writeJournal pinned: day2" "\"2024-04-02\",\"Cash\",\"50.0\",\"Sales\",\"50.0\"" (lns !! 2)- assertEqual "writeJournal pinned: day3 line1 (2 debits vs 1 credit -> toSameLength padding)"- "\"2024-04-03\",\"AccountsReceivable\",\"10.0\",\"Sales\",\"40.0\"" (lns !! 3)- assertEqual "writeJournal pinned: day3 line2 (padded Day/Credit cells empty)"- "\"\",\"Cash\",\"30.0\",\"\",\"\"" (lns !! 4)+ assertEqual "writeJournal pinned: day3 debit order, credit, and padding"+ [ "\"2024-04-03\",\"Cash\",\"30.0\",\"Sales\",\"40.0\""+ , "\"\",\"AccountsReceivable\",\"10.0\",\"\",\"\""+ ]+ (drop 3 lns) -- ================================================================ -- ExchangeAlgebra.IO.Input.Csv: generic journal CSV reader.@@ -478,7 +483,7 @@ [ Just (PP.postingCapabilityFor title) | title <- Registry.concreteAccountTitles ]- assertEqual "posting gate: all 243 titles follow the closed matrix"+ assertEqual "posting gate: all concrete titles follow the closed matrix" [ (context, title, PP.postingAllowedIn context capability) | context <- contexts , title <- Registry.concreteAccountTitles
test/Journal/JournalSpec.hs view
@@ -12,6 +12,9 @@ import qualified Data.HashMap.Strict as HM import qualified Data.Map.Strict as M import qualified Data.List as L+import qualified Data.Binary as Binary+import Data.Binary.Put (runPut)+import Control.DeepSeq (rnf) import Control.Monad (forM_) import Test.QuickCheck hiding (Fixed) import Support (TestComparison(..)@@ -29,6 +32,54 @@ type TestJournal = EJ.Journal String Double (HatBase CountUnit) type AxisJournal = EJ.Journal (String, Int) Double (HatBase CountUnit) +-- | Compare whole-note filtering with filtering the materialized note map.+testFilterWithNote :: IO ()+testFilterWithNote = do+ let first = 1 .@ Not :< Yen :: TestAlg+ second = 2 .@ Not :< Yen+ layered = EJ.fromMap (HM.singleton "shared" first) .+ (second .| "shared")+ filtered = EJ.filterWithNote (\_ algebra -> norm algebra >= 2) layered+ assertEqual "filterWithNote keeps both terms of an accepted shared note"+ (Just [1, 2]) (EA.vals <$> HM.lookup "shared" (EJ.toMap filtered))++ quickProp "filterWithNote matches toMap filtering for value and note predicates" $+ forAll genCase $ \(baseOnly, deltaOnly, threshold) ->+ let layeredJournal = baseOnly .+ deltaOnly+ agrees :: TestJournal -> (String -> TestAlg -> Bool) -> Property+ agrees journal predicate =+ EJ.toMap (EJ.filterWithNote predicate journal)+ === HM.filterWithKey predicate (EJ.toMap journal)+ in conjoin+ [ agrees journal predicate+ | journal <- [baseOnly, deltaOnly, layeredJournal]+ , predicate <- predicates threshold+ ]+ quickProp "filterWithNote agrees for a materialized and a two-layer journal" $+ forAll genCase $ \(baseOnly, deltaOnly, threshold) ->+ let layeredJournal = baseOnly .+ deltaOnly+ materialized = EJ.fromMap (EJ.toMap layeredJournal)+ agrees :: (String -> TestAlg -> Bool) -> Property+ agrees predicate =+ EJ.toMap (EJ.filterWithNote predicate layeredJournal)+ === EJ.toMap (EJ.filterWithNote predicate materialized)+ in conjoin (L.map agrees (predicates threshold))+ where+ genCase :: Gen (TestJournal, TestJournal, Double)+ genCase = do+ baseAmount <- choose (1, 10)+ deltaAmount <- choose (1, 10)+ threshold <- choose (1, 21)+ let term :: Double -> TestAlg+ term value = value .@ Not :< Yen+ baseOnly = EJ.fromMap (HM.fromList+ [ ("shared", term baseAmount), ("base", term deltaAmount) ])+ deltaOnly = (term deltaAmount .| "shared")+ .+ (term baseAmount .| "delta")+ pure (baseOnly, deltaOnly, threshold)++ predicates :: Double -> [String -> TestAlg -> Bool]+ predicates threshold = [\_ algebra -> norm algebra >= threshold, \note _ -> note /= "base"]+ algSample :: TestAlg algSample = (1 .@ (Hat :< Yen))@@ -414,9 +465,9 @@ forM_ cases runTestComparison --- | Check axis filtering, type mismatch, and index updates after append.-testFilterByAxisCases :: IO ()-testFilterByAxisCases = do+-- | Check note field filtering, type mismatch, and index updates after append.+testFilterByNoteFieldCases :: IO ()+testFilterByNoteFieldCases = do let cases = concat [ let ledger :: AxisJournal@@ -426,13 +477,13 @@ , (30 .@ (Hat :< Yen)) .| ("A", 2) ] expected = EJ.filterWithNote (\(_, t') _ -> t' == 1) ledger- actual = EJ.filterByAxis 1 (EJ.NoteAxisKey (1 :: Int)) ledger- mismatch = EJ.filterByAxis 1 (EJ.NoteAxisKey ("1" :: String)) ledger+ actual = EJ.filterByNoteField 1 (EJ.NoteFieldKey (1 :: Int)) ledger+ mismatch = EJ.filterByNoteField 1 (EJ.NoteFieldKey ("1" :: String)) ledger in- [ EqualComparison "Journal.filterByAxis matches filterWithNote on axis=1"+ [ EqualComparison "Journal.filterByNoteField matches filterWithNote on field 1" (EJ.toMap expected) (EJ.toMap actual)- , EqualComparison "Journal.filterByAxis type mismatch returns empty"+ , EqualComparison "Journal.filterByNoteField type mismatch returns empty" (EJ.toMap (EJ.Zero :: AxisJournal)) (EJ.toMap mismatch) ]@@ -449,9 +500,9 @@ ] ledger = base .+ rhs expected = EJ.filterWithNote (\(_, t') _ -> t' == 1) ledger- actual = EJ.filterByAxis 1 (EJ.NoteAxisKey (1 :: Int)) ledger+ actual = EJ.filterByNoteField 1 (EJ.NoteFieldKey (1 :: Int)) ledger in- [ EqualComparison "Journal.filterByAxis works after append updates"+ [ EqualComparison "Journal.filterByNoteField works after append updates" (EJ.toMap expected) (EJ.toMap actual) ]@@ -499,12 +550,82 @@ assertEqual "Journal closing records additions under the settlement note" (Just entries) (HM.lookup "closing" (EJ.toMap closed)) +-- | Preserve axis queries and legacy bytes across construction and compaction.+-- Distinct notes can be reordered; repeated notes keep their posting order.+-- All values and notes are total; arbitrary bottoms are outside this contract.+testLazyDeltaAxisCompatibility :: IO ()+testLazyDeltaAxisCompatibility = forM_ [0, 1, 127, 128, 129, 260] $ \count -> do+ let posting :: Int -> EA.Alg Double (HatBase CountUnit)+ posting amount = fromIntegral amount .@ (Not :< Yen)++ note :: Int -> (String, Int)+ note index = ("event", index)++ entries = [(note index, posting 1 .+ posting 2) | index <- [1 .. count]]+ expectedMap = HM.fromList entries+ singletons :: Int -> [AxisJournal]+ singletons amount = [posting amount .| note index | index <- [1 .. count]]++ forward = foldl (<>) mempty (singletons 1 ++ singletons 2)+ reordered = foldl (<>) mempty (reverse (singletons 1) ++ reverse (singletons 2))+ fromMap = EJ.fromMap expectedMap+ splitLayers = EJ.mkJournal+ (HM.fromList [(note index, posting 1) | index <- [1 .. count]])+ (HM.fromList [(note index, posting 2) | index <- [1 .. count]])+ legacyBytes = runPut $ do+ Binary.put (HM.size expectedMap :: Int)+ HM.foldrWithKey+ (\key algebra rest -> Binary.put key >> Binary.put algebra >> rest)+ (pure ()) expectedMap++ forM_ [forward, reordered, fromMap, splitLayers] $ \journal -> do+ assertEqual "lazy delta: note map" expectedMap (EJ.toMap journal)+ assertEqual "lazy delta: legacy Binary bytes" legacyBytes (Binary.encode journal)+ rnf journal `seq` pure ()+ forM_ [0, 1, count, count + 1] $ \index -> do+ let expected = HM.filterWithKey (\(_, term) _ -> term == index) expectedMap+ selected = EJ.filterByNoteField 1 (EJ.NoteFieldKey index) journal+ assertEqual "lazy delta: axis query after NFData" expected (EJ.toMap selected)+ assertEqual "lazy delta: repeated axis query" expected+ (EJ.toMap (EJ.filterByNoteField 1 (EJ.NoteFieldKey index) journal))+ -- Querying a shared predecessor must not leave a stale index on append.+ let extended = journal <> (posting 3 .| note (count + 1))+ assertEqual "lazy delta: append after query" (HM.singleton (note (count + 1)) (posting 3))+ (EJ.toMap (EJ.filterByNoteField 1 (EJ.NoteFieldKey (count + 1)) extended))++testJournalAdditionOrder :: IO ()+testJournalAdditionOrder = do+ let posting v = v .@ (Hat :< Yen) :: TestAlg+ on note v = posting v .| note :: EJ.Journal Int Double (HatBase CountUnit)+ -- Adding 128 other notes crosses the delta compaction threshold.+ -- They share the target note's Hat base, so their position matters to toAlg.+ fillers = [on n (fromIntegral n + 10) | n <- [1 .. 128]]+ early = L.foldl' (.+) mempty ([on 0 1] ++ fillers ++ [on 0 2, on 0 3])+ late = L.foldl' (.+) mempty ([on 0 1, on 0 2, on 0 3] ++ fillers)+ assertEqual "Journal.toMap preserves same-note order across compaction"+ (EJ.toMap late) (EJ.toMap early)+ assertEqual "Journal.toAlg preserves order across compaction on shared bases"+ (EJ.toAlg late) (EJ.toAlg early)+ assertEqual "Journal compaction retains the note's input order"+ (Just [1, 2, 3]) (EA.vals <$> HM.lookup 0 (EJ.toMap early))++ let base = EJ.fromMap (HM.singleton 0 (posting 2))+ layered = base .+ on 0 3+ entries = [on 0 1, layered, on 1 4, on 0 5]+ folded = L.foldl' (.+) mempty entries+ bulk = EJ.sigma entries id+ assertEqual "Journal.sigma agrees with (.+) on repeated and layered notes"+ (EJ.toMap folded) (EJ.toMap bulk)+ -- | Run this domain in its original relative test order. runTests :: IO () runTests = do testFinalStockTransferEquivalence- testFilterByAxisCases+ testFilterByNoteFieldCases+ testFilterWithNote testSigmaReferences+ testJournalAdditionOrder testJournalProjectionNorms testReplaceNotes journalProperties+ testLazyDeltaAxisCompatibility
test/Journal/NormalFormSpec.hs view
@@ -94,7 +94,7 @@ , EA.compress input , Journal.projWithNote notes input , Journal.filterWithNote (\n _ -> n == first) input- , Journal.filterByAxis 0 (Journal.NoteAxisKey first) input+ , Journal.filterByNoteField 0 (Journal.NoteFieldKey first) input , Journal.replaceNotes input (positive Journal..| second) , Journal.fromList [input, input] , Journal.sigma [input, input] id
test/Posting/PostingSpec.hs view
@@ -242,7 +242,7 @@ assertTest "base component NFData instances" $ rnf (Cash :: AccountTitles) `seq` rnf (Yen :: CountUnit) `seq`- rnf (AxisKey Cash) `seq`+ rnf (ElementKey Cash) `seq` rnf (Hat :: Hat) `seq` rnf (BaseForSingleHat :: BaseForSingleHat) `seq` rnf (PS :: PIMO) `seq`@@ -266,7 +266,7 @@ assertTest "PostSide excludes HatNot" $ all ((/= HatNot) . sideHat) [minBound .. maxBound] --- | Three equal-base entries expose structural ordering without breaking the multiset law.+-- | Both groupings of three equal-base entries preserve the same sequence. testAssociativityRegression :: IO () testAssociativityRegression = case traverse posted [1, 2, 3] of Left failure -> do@@ -279,7 +279,7 @@ z = entry HatSide third part :: Posting Double TestBase left = postingAlg ((x <> y) <> z) right = postingAlg (x <> (y <> z))- assertTest "equal-base grouping changes structural order" (left /= right)+ assertTest "equal-base grouping preserves structural order" (left == right) assertTest "equal-base grouping preserves the multiset" (sameMultiset left right) Right _ -> assertTest "three checked fixture values" False
test/Simulate/SimulateSpec.hs view
@@ -320,12 +320,12 @@ o i j = M.findWithDefault 0 (i, j) shortageMap return $ sigma simCompanies $ \i -> sigma (simCompanies L.\\ [i]) $ \j- -> (o i j) .@ Not :<(Products, j, i, Amount)+ -> ( (o i j) .@ Not :<(Products, j, i, Amount) .+ (o i j) .@ Hat :<(Cash, (.#), i, Yen) .+ (o i j) .@ Not :<(Purchases, (.#), i, Yen) .+ (o i j) .@ Not :<(Cash, (.#), j, Yen) .+ (o i j) .@ Not :<(Sales, (.#), j, Yen)- .+ (o i j) .@ Hat :<(Products, j, j, Amount)+ .+ (o i j) .@ Hat :<(Products, j, j, Amount) ) .| (SimSalesPurchase, t) instance StateSpace SimTerm SimInitVar SimEvent SimWorld s where@@ -775,12 +775,13 @@ assertEqual "Policy bridge: restore (spill + remainder) == whole ledger (lossless)" (toMap whole) (toMap restored) --- Test 7 (HasTermAxis): termOf returns the LAST Note component for pair/triple.-testPolicyHasTermAxis :: IO ()-testPolicyHasTermAxis = do- assertEqual "Policy HasTermAxis: pair termOf = snd" (7 :: Int) (Policy.termOf ("e", 7 :: Int))- assertEqual "Policy HasTermAxis: triple termOf = 3rd" (9 :: Int)- (Policy.termOf ("e1", "e2", 9 :: Int))+-- Test 7 (HasNotePeriod): periodOf returns the LAST Note component for pair/triple.+testPolicyHasNotePeriod :: IO ()+testPolicyHasNotePeriod = do+ assertEqual "Policy HasNotePeriod: pair periodOf = snd" (7 :: Int)+ (Policy.periodOf ("e", 7 :: Int))+ assertEqual "Policy HasNotePeriod: triple periodOf = 3rd" (9 :: Int)+ (Policy.periodOf ("e1", "e2", 9 :: Int)) -- ================================================================ -- MarketModel equivalence tests (Phase 5, feat/market-scale-experiments)@@ -912,7 +913,7 @@ -- positive surplus into (MktCarryover, t+1). Mirrors MarketModel.carryoverStage. mktCarryover :: (HatVal v, Real v) => Stage (MktW v) Int MktNote v MktBase mktCarryover = stage (T.pack "closing") $ \w t ->- let termAlg = EJ.toAlg (EJ.filterByAxis 1 (NoteAxisKey (t :: Int)) (mkLedger w))+ let termAlg = EJ.toAlg (EJ.filterByNoteField 1 (NoteFieldKey (t :: Int)) (mkLedger w)) netMap = EA.balanceMapBy mktOwnerOfProduct termAlg perFirm (j, v) = if v <= 0 then mempty@@ -1345,7 +1346,7 @@ testPolicyDeleteOnly testPolicyDeterminism testPolicyClassicBridge- testPolicyHasTermAxis+ testPolicyHasNotePeriod testMarketSimpleTunedEqual testMarketSeqParEqual testMarketShortagePositive
test/Simulation/NetworkSpec.hs view
@@ -4,7 +4,7 @@ module Simulation.NetworkSpec (runTests) where import ExchangeAlgebra.Accounting.Account-import ExchangeAlgebra.Journal+import ExchangeAlgebra.Journal hiding (map) import qualified ExchangeAlgebra.Journal as EJ import ExchangeAlgebra.Algebra.Value (MoneyDecimal) import ExchangeAlgebra.Simulation.Network (TradeNetwork@@ -46,11 +46,12 @@ import ExchangeAlgebra.Simulation.Network.Csv (parseEdgeCsv, parseCoefCsv) import ExchangeAlgebra.Simulation.Network.Journal (sigmaEdges) import qualified Data.Map.Strict as M+import Data.List (foldl') import qualified Data.List as L-import qualified Data.Set as Set+import qualified Data.Set as S import qualified Data.Text as T import Control.Monad (forM_, when)-import System.Random (mkStdGen)+import System.Random (StdGen, mkStdGen, randomR) import Control.Exception (try, evaluate, SomeException) import Control.DeepSeq (force) import Support (TestComparison(..), assertEqual, runTestComparison)@@ -285,7 +286,7 @@ (M.elems (ieSize economy))) when dag $ do assertEqual "Industrial network: no duplicate edges"- (length networkEdges) (Set.size (Set.fromList networkEdges))+ (length networkEdges) (S.size (S.fromList networkEdges)) assertEqual "Industrial network: sector order and intra-sector id DAG" True (all valid networkEdges) when increasing $ do@@ -293,11 +294,140 @@ assertEqual "Industrial network: K=1 edges are increasing ids" True (all (uncurry (<)) networkEdges) +-- Copy of the 2026-11-24 implementation for checking output compatibility.+kRegularReference :: Ord k => StdGen -> [k] -> Int -> TradeNetwork k+kRegularReference gen ks k =+ buildNetwork nodeSet (concat (snd (foldl' pick (gen, []) xs)))+ where+ nodeSet = S.fromList ks+ xs = S.toAscList nodeSet+ deg = max 0 (min k (length xs - 1))+ pick (g0, acc) j =+ let candidates = filter (/= j) xs+ (chosen, g1) = sampleWithoutReference g0 deg candidates+ in (g1, [ (i, j) | i <- chosen ] : acc)++scaleFreeReference :: Ord k => StdGen -> [k] -> Int -> TradeNetwork k+scaleFreeReference gen ks m0 =+ buildNetwork nodeSet builtEdges+ where+ nodeSet = S.fromList ks+ xs = S.toAscList nodeSet+ m = max 1 m0+ -- State threads the generator, the edge accumulator and an incremental+ -- degree table (@node ↦ current degree@). The degree table replaces the+ -- O(E) rescan that the naive @degree i = length (filter …) acc@ performed+ -- for every candidate at every node: each added edge bumps both endpoints'+ -- degrees in O(log N), so the per-node weight list is built without ever+ -- touching @acc@. The weights produced are bit-for-bit identical to the+ -- rescan version, so the generated network is unchanged.+ (_, builtEdges0, _) = foldl' addNode (gen, [], M.empty) (zip [0 ..] xs)+ builtEdges = reverse builtEdges0++ -- addNode :: (StdGen, [(k,k)], Map k Int)+ -- -> (Int, k) -> (StdGen, [(k,k)], Map k Int)+ addNode st@(g0, acc, deg) (ix, j)+ | ix == 0 = st -- first node: nothing to attach to+ | ix <= m = -- seed phase: attach to all earlier nodes+ let suppliers = take ix xs+ newEdges = [ (i, j) | i <- suppliers ]+ in (g0, newEdges ++ acc, bumpEdges newEdges deg)+ | otherwise = -- preferential attachment+ let present = take ix xs -- nodes already added+ degree i = M.findWithDefault 0 i deg+ weighted = [ (i, fromIntegral (1 + degree i) :: Double) | i <- present ]+ (chosen, g1) = sampleWeightedWithoutReference g0 m weighted+ newEdges = [ (i, j) | i <- chosen ]+ in (g1, newEdges ++ acc, bumpEdges newEdges deg)++ -- Increment both endpoints' degree counts for each newly added edge.+ bumpEdges es d = foldl' (\d' (i, t) -> bump i (bump t d')) d es+ bump k = M.insertWith (+) k 1++sampleWithoutReference :: StdGen -> Int -> [a] -> ([a], StdGen)+sampleWithoutReference g0 n xs0 = go g0 (max 0 n) xs0 []+ where+ go g _ [] acc = (reverse acc, g)+ go g k xs acc+ | k <= 0 = (reverse acc, g)+ | otherwise =+ let (ix, g1) = randomR (0, length xs - 1) g+ (chosen, rest) = pick ix xs+ in go g1 (k - 1) rest (chosen : acc)+ pick i ys = case splitAt i ys of+ (pre, y : post) -> (y, pre ++ post)+ (pre, []) -> (last pre, init pre) -- unreachable (ix in range)++sampleWeightedWithoutReference :: StdGen -> Int -> [(a, Double)] -> ([a], StdGen)+sampleWeightedWithoutReference g0 n xs0 = go g0 (max 0 n) xs0 []+ where+ go g _ [] acc = (reverse acc, g)+ go g k ws acc+ | k <= 0 = (reverse acc, g)+ | otherwise =+ let total = sum (map snd ws)+ (u, g1) = randomR (0, total) g :: (Double, StdGen)+ (chosen, rest) = drawAt u ws+ in go g1 (k - 1) rest (chosen : acc)+ drawAt u ws = walk u ws []+ where+ walk _ [] seen = case reverse seen of+ ((a, _) : _) -> (a, []) -- exhausted (shouldn't happen)+ [] -> error "sampleWeightedWithout: empty"+ walk acc ((a, w) : rest) seen+ | acc <= w = (a, reverse seen ++ rest)+ | otherwise = walk (acc - w) rest ((a, w) : seen)++-- The library's buildNetwork is private. The reference edges are valid input+-- to the public constructor, which assembles the same adjacency indices.+buildNetwork :: Ord k => S.Set k -> [(k, k)] -> TradeNetwork k+buildNetwork nodeSet es = case tradeNetwork (S.toAscList nodeSet) es of+ Right network -> network+ Left err -> error ("Invalid reference network: " ++ show err)++testNetworkSamplingCompatibility :: IO ()+testNetworkSamplingCompatibility = do+ checkRegular "ascending Int" (\n -> [1 .. n])+ checkRegular "reversed Int with duplicates" (\n -> [n, n - 1 .. 1] ++ [1 .. n])+ checkRegular "Char" (\n -> take n ['a' ..])+ assertEqual "Network: scaleFree matches reference across sizes, m and seeds"+ Nothing (L.find differsScaleFree scaleFreeCases)+ let ks = [1 .. 3000 :: Int]+ gen = mkStdGen 0+ assertEqual "Network: kRegular matches reference at N=3000, k=10"+ (edges (kRegularReference gen ks 10)) (edges (kRegular gen ks 10))+ assertEqual "Network: scaleFree matches reference at N=3000, m=3"+ (edges (scaleFreeReference gen ks 3)) (edges (scaleFree gen ks 3))+ where+ sizes = [0, 1, 2, 3, 10, 57, 200 :: Int]+ seeds = [0 .. 49]++ checkRegular label keys =+ assertEqual ("Network: kRegular matches reference for " ++ label)+ Nothing (L.find differs cases)+ where+ cases =+ [ (n, k, seed)+ | n <- sizes, k <- L.nub [0, 1, 2, 5, n - 1, n, n + 3], seed <- seeds ]+ differs (n, k, seed) =+ let ks = keys n+ gen = mkStdGen seed+ in edges (kRegularReference gen ks k) /= edges (kRegular gen ks k)++ scaleFreeCases =+ [ (n, m, seed)+ | n <- sizes, m <- L.nub [0, 1, 2, 3, 5, n], seed <- seeds ]+ differsScaleFree (n, m, seed) =+ let ks = [1 .. n]+ gen = mkStdGen seed+ in edges (scaleFreeReference gen ks m) /= edges (scaleFree gen ks m)+ -- | Run this domain in its original relative test order. runTests :: IO () runTests = do testIndustrialNetworkCases testNetworkInvariants+ testNetworkSamplingCompatibility testNetCompleteEquiv testNetHawkinsSimon testNetCsvRoundTrip
test/Spec.hs view
@@ -2,6 +2,7 @@ module Main (main) where import qualified Value.MoneyParseSpec as MoneyParseSpec+import qualified Value.MoneyDoubleBinarySpec as MoneyDoubleBinarySpec import qualified Algebra.ExactReadoutSpec as ExactReadoutSpec import qualified Algebra.AccumSpec as AccumSpec import qualified Algebra.ExactSumSpec as ExactSumSpec@@ -15,11 +16,19 @@ import qualified Journal.SideTotalsSpec as SideTotalsSpec import qualified Golden.WireFormat as WireFormat import qualified Algebra.CoreSpec as CoreSpec+import qualified Algebra.PairSpec as PairSpec import qualified Journal.JournalSpec as JournalSpec import qualified Journal.NormalFormSpec as NormalFormSpec import qualified Accounting.AdjustmentSpec as AdjustmentSpec+import qualified Accounting.AuditSpec as AuditSpec+import qualified Accounting.VocabularyLawSpec as VocabularyLawSpec+import qualified Accounting.ClosingTargetSpec as ClosingTargetSpec+import qualified Accounting.JcciSpec as JcciSpec+import qualified Accounting.ConsolidationVocabularySpec as ConsolidationVocabularySpec import qualified Accounting.RegistrySpec as RegistrySpec+import qualified Accounting.ProcedureLawSpec as ProcedureLawSpec import qualified IO.InputOutputSpec as InputOutputSpec+import qualified IO.AccountNamesSpec as AccountNamesSpec import qualified Simulate.SimulateSpec as SimulateSpec import qualified Simulation.NetworkSpec as NetworkSpec import qualified Simulation.OptimizeSpec as OptimizeSpec@@ -29,6 +38,7 @@ ExactReadoutSpec.runTests AccumSpec.runTests MoneyParseSpec.runTests+ MoneyDoubleBinarySpec.runTests ExactSumSpec.runTests AdmissionSpec.runTests TransferRuleSpec.runTests@@ -40,11 +50,19 @@ SideTotalsSpec.runTests WireFormat.checkFixture CoreSpec.runTests+ PairSpec.runTests JournalSpec.runTests NormalFormSpec.runTests AdjustmentSpec.runTests+ AuditSpec.runTests+ VocabularyLawSpec.runTests+ ClosingTargetSpec.runTests+ JcciSpec.runTests+ ConsolidationVocabularySpec.runTests RegistrySpec.runTests+ ProcedureLawSpec.runTests InputOutputSpec.runTests+ AccountNamesSpec.runTests SimulateSpec.runTests NetworkSpec.runTests OptimizeSpec.runTests
test/Surface/Accounting.hs view
@@ -37,7 +37,6 @@ , AmortizationExpense , SalesCost , BusinessTrip- , Commutation , UtilitiesExpense , RentExpense , AdvertisingExpense@@ -289,7 +288,7 @@ , projDeferredAssets , projCurrentLiability , projFixedLiability- , projCapitalStock+ , projNonContraCreditEquity , projContraAssets , projContra , (.->)@@ -333,7 +332,6 @@ , AmortizationExpense , SalesCost , BusinessTrip- , Commutation , UtilitiesExpense , RentExpense , AdvertisingExpense@@ -585,7 +583,7 @@ , projDeferredAssets , projCurrentLiability , projFixedLiability- , projCapitalStock+ , projNonContraCreditEquity , projContraAssets , projContra , (.->)
test/Surface/Render/Bookkeeping.hs view
@@ -1,5 +1,5 @@ -- | Compile-time lock for the public names exported by--- "ExchangeAlgebra.Render.Bookkeeping".+-- "ExchangeAlgebra.IO.Output.Statements". module Surface.Render.Bookkeeping ( writeJournal , journalRows@@ -15,7 +15,7 @@ , postClosingTrialBalanceRows ) where -import ExchangeAlgebra.Render.Bookkeeping+import ExchangeAlgebra.IO.Output.Statements ( writeJournal , journalRows , writeAccountOf
test/Surface/Render/Csv.hs view
@@ -1,11 +1,11 @@ -- | Compile-time lock for the public names exported by--- "ExchangeAlgebra.Render.Csv".+-- "ExchangeAlgebra.IO.Output.Csv". module Surface.Render.Csv ( writeCSV , csvTranspose ) where -import ExchangeAlgebra.Render.Csv+import ExchangeAlgebra.IO.Output.Csv ( writeCSV , csvTranspose )
test/Surface/Simulate/Engine.hs view
@@ -107,9 +107,9 @@ , SnapT ) import qualified ExchangeAlgebra.Simulate.Lite as Lite-import ExchangeAlgebra.Simulate.Policy ( HasTermAxis+import ExchangeAlgebra.Simulate.Policy ( HasNotePeriod , LedgerPolicy- , TermOf+ , PeriodOf ) -- | Compile-time lock for the pure per-term observer runner exported by@@ -132,7 +132,7 @@ :: forall w t n v b r. ( forall s. LiteWorld w s , HatVal v, HatBaseClass b- , HasTermAxis n, TermOf n ~ t+ , HasNotePeriod n, PeriodOf n ~ t , StateTime t , Binary.Binary t, Binary.Binary (Journal n v b) ) => (t -> w SnapT -> IO ())
test/Transfer/RuleSpec.hs view
@@ -15,30 +15,25 @@ import Data.List (permutations) import qualified Data.Map.Strict as Map import Data.Proxy (Proxy(..))-import qualified Data.Set as Set-import qualified ExchangeAlgebra.Accounting.TrialBalance.Validation as Validation+import qualified ExchangeAlgebra.Accounting.Audit as Audit import System.Exit (exitFailure) import Test.QuickCheck hiding (label, sample) import ExchangeAlgebra.Algebra hiding (map, filter) import qualified ExchangeAlgebra.Algebra as Algebra-import ExchangeAlgebra.Algebra.Transfer.Rule ( TransferScale(..)+import ExchangeAlgebra.Algebra.Transfer ( TransferScale(..) , TransferRule(..) , TransferRules , TransferRuleError(..) , TransferApplyError(..) , mkTransferRules , rulesToList- , relabel- , scaleBy- , divideBy , transferEntries , collapseEntries , collapseNetEntries )-import ExchangeAlgebra.Accounting.Closing (ClosingSide(..), closingSide, closingEntries)+import ExchangeAlgebra.Accounting.Closing (ClosingSide(..), ClosingError(..), closingSide, closingEntries) import qualified ExchangeAlgebra.Journal as Journal import ExchangeAlgebra.Journal ((.|), Note(..))-import qualified ExchangeAlgebra.Journal.Transfer.Rule as JournalRule import ExchangeAlgebra.Algebra.Value (MoneyDecimal) -- | Concrete account and unit coordinates for compatibility properties.@@ -53,12 +48,11 @@ -- | Integer posting quantities bounded away from zero for the independent oracle. type TestQuantity = Integer --- | Generated flat postings and one permitted scale coefficient.-data CompatibilityCase = CompatibilityCase [(TestQuantity, TestBase)] Rational+-- | Generated flat postings for the transfer laws.+newtype CompatibilityCase = CompatibilityCase [(TestQuantity, TestBase)] deriving (Show) --- | Generate P1-P5-compatible inputs; every rule table includes HatNot,--- Relabel, MulBy and DivBy, with uniform wildcard positions.+-- | Generate inputs for rules with uniform wildcard positions. genCompatibilityCase :: Gen CompatibilityCase genCompatibilityCase = do count <- chooseInt (1, 35)@@ -68,35 +62,31 @@ title <- elements [Cash, Products, Sales, Depreciation] unit <- elements [Yen, Amount, Dollar] pure (quantity, postingHat :< (title, unit))- coefficient <- elements [2, 3, 1 / 2, 4]- pure (CompatibilityCase entries coefficient)+ pure (CompatibilityCase entries) --- | Translate the generated scale without converting division into a reciprocal.-caseRules :: Fractional v => CompatibilityCase -> [TransferRule v TestBase]-caseRules (CompatibilityCase _ coefficient) =- [ relabel (HatNot :< (Cash, wildcard)) (HatNot :< (Deposits, wildcard))- , scaleBy (HatNot :< (Products, wildcard))- (HatNot :< (RawMaterials, wildcard)) (fromRational coefficient)- , divideBy (HatNot :< (Sales, wildcard))- (HatNot :< (RetainedEarnings, wildcard)) (fromRational coefficient)+-- | Rules used by the independent rewrite oracle.+caseRules :: [TransferRule v TestBase]+caseRules =+ [ TransferRule (HatNot :< (Cash, wildcard)) (HatNot :< (Deposits, wildcard)) Relabel+ , TransferRule (HatNot :< (Products, wildcard)) (HatNot :< (RawMaterials, wildcard)) Relabel+ , TransferRule (HatNot :< (Sales, wildcard)) (HatNot :< (RetainedEarnings, wildcard)) Relabel ] -- | Construct ordinary non-negative postings through the public smart constructor. caseAlgebra :: HatVal v => CompatibilityCase -> Alg v TestBase-caseAlgebra (CompatibilityCase entries _) =+caseAlgebra (CompatibilityCase entries) = Algebra.fromList [fromInteger quantity .@ postingBase | (quantity, postingBase) <- entries] -- | Independently rewrite the generated concrete account coordinates.--- The oracle uses the input coefficient, without interpreting transfer rules. expectedConversion :: forall v. HatVal v => CompatibilityCase -> Alg v TestBase-expectedConversion (CompatibilityCase entries coefficient) = Algebra.fromList+expectedConversion (CompatibilityCase entries) = Algebra.fromList [ convert (fromInteger quantity) posting | (quantity, posting) <- entries ] where convert :: v -> TestBase -> Alg v TestBase convert value (side :< (title, unit)) = case title of Cash -> value .@ side :< (Deposits, unit)- Products -> (value * fromRational coefficient) .@ side :< (RawMaterials, unit)- Sales -> (value / fromRational coefficient) .@ side :< (RetainedEarnings, unit)+ Products -> value .@ side :< (RawMaterials, unit)+ Sales -> value .@ side :< (RetainedEarnings, unit) _ -> value .@ side :< (title, unit) -- | Law observation: complete base including Hat/Not to value, after bar.@@ -120,7 +110,7 @@ -- | L1 compares every resulting base, not only the overall norm. propCompatibility :: forall v. HatVal v => Proxy v -> Property propCompatibility _ = forAll genCompatibilityCase $ \sample ->- let rules = caseRules sample :: [TransferRule v TestBase]+ let rules = caseRules :: [TransferRule v TestBase] ledger = caseAlgebra sample :: Alg v TestBase in case applyChecked (mkTransferRules rules) ledger of Left failure -> counterexample failure False@@ -155,7 +145,7 @@ propBalance :: forall v. HatVal v => Proxy v -> Property propBalance _ = forAll genCompatibilityCase $ \sample -> let ledger = caseAlgebra sample :: Alg v TestBase- rules = [relabel (HatNot :< (Cash, wildcard)) (HatNot :< (Deposits, wildcard))]+ rules = [TransferRule (HatNot :< (Cash, wildcard)) (HatNot :< (Deposits, wildcard)) Relabel] in case mkTransferRules rules of Left failure -> counterexample (show failure) False Right validated -> case transferEntries validated ledger of@@ -168,17 +158,18 @@ -- | L4 pins permutation invariance of successful construction and fingerprints. propCanonical :: Property-propCanonical = forAll genCompatibilityCase $ \sample ->- let rules = caseRules sample :: [TransferRule Double TestBase]- in forAll (shuffle rules) $ \permuted -> case (mkTransferRules rules, mkTransferRules permuted) of- (Right first, Right second) -> property (first == second && hash first == hash second)- failures -> counterexample (show failures) False+propCanonical =+ let rules = caseRules :: [TransferRule Double TestBase]+ in forAll (shuffle rules) $ \permuted ->+ case (mkTransferRules rules, mkTransferRules permuted) of+ (Right first, Right second) -> property (first == second && hash first == hash second)+ failures -> counterexample (show failures) False -- | L5 observes all output values before bar for transfers and closing. propNonnegative :: forall v. HatVal v => Proxy v -> Property propNonnegative _ = forAll genCompatibilityCase $ \sample -> let ledger = caseAlgebra sample :: Alg v TestBase- in case mkTransferRules (caseRules sample) of+ in case mkTransferRules (caseRules) of Left failure -> counterexample (show failure) False Right rules -> case transferEntries rules ledger of Left failure -> counterexample (show failure) False@@ -209,26 +200,24 @@ exitFailure putStrLn ("[PASS] " ++ label) --- | Reject overlaps, duplicates and all invalid coefficients deterministically.+-- | Reject overlaps and duplicates deterministically. testValidation :: IO () testValidation = do- let first = relabel (HatNot :< (Cash, wildcard)) (Not :< (Deposits, Yen))+ let first = TransferRule (HatNot :< (Cash, wildcard)) (Not :< (Deposits, Yen)) Relabel :: TransferRule Double TestBase- second = relabel (Not :< (Cash, Yen)) (Not :< (Products, Yen))- third = relabel (Not :< (Cash, Amount)) (Not :< (Sales, Amount))+ second = TransferRule (Not :< (Cash, Yen)) (Not :< (Products, Yen)) Relabel+ third = TransferRule (Not :< (Cash, Amount)) (Not :< (Sales, Amount)) Relabel overlap expectedFirst expectedSecond result = case result of Left (OverlappingRules actualFirst actualSecond) -> actualFirst == expectedFirst && actualSecond == expectedSecond _ -> False assertTest "overlap input order" (overlap first second (mkTransferRules [first, second, third])) assertTest "duplicate rejected" (overlap first first (mkTransferRules [first, first]))- mapM_ (\coefficient -> mapM_ (checkCoefficient first second coefficient) [scaleBy, divideBy])- [0, -1, 0 / 0, 1 / 0, -1 / 0]- let nestedFirst = relabel (Hat :< ((Cash, wildcard), Yen))- (Hat :< ((Deposits, Amount), Yen))+ let nestedFirst = TransferRule (Hat :< ((Cash, wildcard), Yen))+ (Hat :< ((Deposits, Amount), Yen)) Relabel :: TransferRule Double (HatBase ((AccountTitles, CountUnit), CountUnit))- nestedSecond = relabel (Hat :< ((wildcard, Amount), wildcard))- (Hat :< ((Products, Amount), Yen))+ nestedSecond = TransferRule (Hat :< ((wildcard, Amount), wildcard))+ (Hat :< ((Products, Amount), Yen)) Relabel assertTest "nested partial wildcard overlap" $ overlap nestedFirst nestedSecond (mkTransferRules [nestedFirst, nestedSecond]) canonical <- requireRight "valid rules" (mkTransferRules ([second, third] :: [TransferRule Double TestBase]))@@ -239,22 +228,13 @@ Left _ -> pure () Right (_, _, value) -> assertTest "Binary refuses overlapping rules" (const False (value :: TransferRules Double TestBase))- where- checkCoefficient first second coefficient constructor = do- let invalid = constructor (Not :< (Products, Yen)) (Not :< (Cash, Yen)) coefficient- later = scaleBy (Not :< (Deposits, Yen)) (Not :< (Cash, Yen)) 0- assertTest "coefficient checked before overlap; first error" $- case mkTransferRules [first, second, invalid, later] of- Left (InvalidCoefficient rule) -> ruleFrom rule == ruleFrom invalid- _ -> False- -- | Mixed wildcard positions match every posting under every rule permutation. testMixedWildcardPermutations :: IO () testMixedWildcardPermutations = do let rules =- [ relabel (Hat :< (wildcard, Yen)) (Hat :< (wildcard, Amount))- , relabel (Not :< (Cash, wildcard)) (Not :< (Deposits, wildcard))- , relabel (Hat :< (Products, Amount)) (Hat :< (Purchases, Amount))+ [ TransferRule (Hat :< (wildcard, Yen)) (Hat :< (wildcard, Amount)) Relabel+ , TransferRule (Not :< (Cash, wildcard)) (Not :< (Deposits, wildcard)) Relabel+ , TransferRule (Hat :< (Products, Amount)) (Hat :< (Purchases, Amount)) Relabel ] :: [TransferRule Double TestBase] ledger = 9 .@ Hat :< (Sales, Yen) .+ 8 .@ Hat :< (Deposits, Yen)@@ -269,7 +249,7 @@ entries <- requireRight "mixed wildcard application" (transferEntries validated ledger) assertTest "new API transforms all three entries" (obs (ledger .+ entries) == obs expected) --- | One-way matching, no-op, zero result, HatNot and overflow edge cases.+-- | One-way matching, identical bases, zero input, and HatNot. testApplication :: IO () testApplication = do let source = Not :< (Cash, Yen)@@ -279,65 +259,31 @@ (mkTransferRules [] :: Either (TransferRuleError Double TestBase) (TransferRules Double TestBase)) emptyEntries <- requireRight "empty rules emit nothing" (transferEntries emptyRules literalWildcard) assertTest "empty rule set" (Algebra.isZero emptyEntries)- concrete <- requireRight "concrete rule" (mkTransferRules [relabel source target])+ concrete <- requireRight "concrete rule" (mkTransferRules [TransferRule source target Relabel]) zeroEntries <- requireRight "zero input" (transferEntries concrete Zero) assertTest "zero input emits nothing" (Algebra.isZero zeroEntries) unmatched <- requireRight "ledger wildcard is literal" (transferEntries concrete literalWildcard) assertTest "one-way matching" (Algebra.isZero unmatched)- noOp <- requireRight "identity rule" (mkTransferRules [relabel source source])+ noOp <- requireRight "identity rule" (mkTransferRules [TransferRule source source Relabel]) identityEntries <- requireRight "identity application" (transferEntries noOp (10 .@ source :: Alg Double TestBase)) assertTest "identity emits nothing" (Algebra.isZero identityEntries) wildcardRule <- requireRight "HatNot rule" $- mkTransferRules [relabel (HatNot :< (Cash, wildcard)) (HatNot :< (Deposits, wildcard))]+ mkTransferRules+ [TransferRule (HatNot :< (Cash, wildcard)) (HatNot :< (Deposits, wildcard)) Relabel] invalidHat <- requireRight "HatNot posting is ignored" $ transferEntries wildcardRule (10 `Internal.Single` HatNot :< (Cash, Yen) :: Alg Double TestBase) assertTest "HatNot posting" (Algebra.isZero invalidHat)- underflow <- requireRight "underflow rule" (mkTransferRules [scaleBy source target (1e-300 :: Double)])- zeroTarget <- requireRight "underflow result" (transferEntries underflow (1e-300 .@ source))- assertTest "zero result emits only cancellation" $- rawObservation zeroTarget == Map.singleton (revHat source) 1e-300- overflow <- requireRight "overflow rule" (mkTransferRules [scaleBy source target (2 :: Double)])- assertTest "Algebra overflow is Left" $ case transferEntries overflow (1e308 .@ source) of- Left (NonFiniteResult rule value postingBase) ->- ruleFrom rule == source && value == 1e308 && postingBase == source- _ -> False- divisionOverflow <- requireRight "division overflow rule" $- mkTransferRules [divideBy source target (1e-308 :: Double)]- assertTest "division overflow is Left" $- case transferEntries divisionOverflow (2 .@ source) of- Left (NonFiniteResult rule value postingBase) ->- ruleScale rule == DivBy 1e-308 && value == 2 && postingBase == source- _ -> False let largeSource = 1e308 .@ source .+ 1e308 .@ source :: Alg Double TestBase largeEntries <- requireRight "Relabel preserves finite individual values" (transferEntries concrete largeSource) assertTest "transfer does not aggregate large postings" $ length (vals largeEntries) == 4 && all (not . isErrorValue) (vals largeEntries)- let journal = (5 .@ source .| "first") .+ (7 .@ source .| "second")- additions <- requireRight "two-note application" (JournalRule.transferEntries concrete journal)- let at note value = case HashMap.lookup note (Journal.toMap additions) of- Nothing -> False- Just entries -> rawObservation entries == rawObservation- (value .@ revHat source .+ value .@ target)- assertTest "two notes preserved" (HashMap.size (Journal.toMap additions) == 2 && at "first" 5 && at "second" 7) let cancellationInput = 10 .@ source .+ 10 .@ revHat source :: Alg Double TestBase rawEntries <- requireRight "no implicit bar" (transferEntries wildcardRule cancellationInput) assertTest "opposing generated postings remain raw" (length (vals rawEntries) == 4)- let overflowingJournal = (5 .@ source .| "small") .+ (1e308 .@ source .| "large")- assertTest "Journal overflow aborts whole result" $- case JournalRule.transferEntries overflow overflowingJournal of- Left (NonFiniteResult _ value _) -> value == 1e308- _ -> False- let failures = (1e308 .@ source .| "a") .+ (1.1e308 .@ source .| "b")- case HashMap.toList (Journal.toMap failures) of- [] -> assertTest "failure fixture is nonempty" False- (_, first) : _ -> assertTest "Journal returns first traversal error" $- case JournalRule.transferEntries overflow failures of- Left (NonFiniteResult _ value _) -> vals first == [value]- _ -> False- sideChanging <- requireRight "cross-side relabel" $- mkTransferRules [relabel source (Not :< (Sales, Yen))]+ sideChanging <- requireRight "cross-side transfer" $+ mkTransferRules [TransferRule source (Not :< (Sales, Yen)) Relabel] unbalanced <- requireRight "cross-side application" (transferEntries sideChanging (10 .@ source :: Alg Double TestBase)) assertTest "L3 needs equal debit-credit sides" (norm (decL unbalanced) /= norm (decR unbalanced)) @@ -371,7 +317,7 @@ overflowing postingBase = 1e308 .@ postingBase .+ 1e308 .@ postingBase :: Alg Double TestBase isBalanceError expected result = case result of- Left (NonFiniteBalance actual) -> actual == expected+ Left (ClosingTransferError (NonFiniteBalance actual)) -> actual == expected _ -> False assertTest "closing Not sum overflow" $ isBalanceError sales (closingEntries (overflowing sales))@@ -467,7 +413,7 @@ let source = Not :< (Sales, Yen) ledger = (-1) `Internal.Single` source :: Alg v TestBase assertTest "negative closing value" $ case closingEntries ledger of- Left (NonFiniteBalance actual) -> actual == source+ Left (ClosingTransferError (NonFiniteBalance actual)) -> actual == source _ -> False -- | C6: overflowing sides may still have a representable exact difference.@@ -483,7 +429,7 @@ Map.findWithDefault 1 source (exactNets (ledger .+ additions)) == 0 mapM_ (\value -> assertTest "nonfinite closing scalar" $ case closingEntries (value `Internal.Single` source :: Alg Double TestBase) of- Left (NonFiniteBalance actual) -> actual == source+ Left (ClosingTransferError (NonFiniteBalance actual)) -> actual == source _ -> False) [0 / 0, 1 / 0, -1 / 0] -- | C7: paying expenses 0.1 and 0.2 leaves no nominal residual after closing.@@ -493,13 +439,8 @@ expense value = value .@ Not :< DeliveryExpenses .+ value .@ Hat :< Cash ledger = expense 0.1 .+ expense 0.2 additions <- requireRight "fractional expense closing" (closingEntries ledger)- let input = Validation.TrialBalanceInput (ledger .+ additions)- Validation.AfterClosing Map.empty [] Set.empty- unclosed :: Validation.TBFinding v -> Bool- unclosed (Validation.UnclosedNominalBalance _ _) = True- unclosed _ = False- assertTest "C7 no UnclosedNominalBalance" $- not $ any unclosed $ Validation.trialBalanceFindings input+ assertTest "C7 no closing residuals" $+ Audit.closingResiduals (ledger .+ additions) == Audit.NoProblem -- | Two goods share an owner and differ only in the axis collapsed below. data ValuationGood = GoodA | GoodB | AnyValuationGood@@ -512,7 +453,7 @@ type ValuationBase = HatBase (AccountTitles, ValuationGood, Owner, CountUnit) --- | Retain the raw count in its own axes, then net the value across goods.+-- | Convert units, then net the value across goods. testValuationCollapse :: IO () testValuationCollapse = do let source good = Not :< (Products, good, Alice, Amount)@@ -522,11 +463,11 @@ patternBase = Not :< (Products, wildcard, Alice, Yen) dropGood (title, _, owner, unit) = (title, wildcard, owner, unit) expected = Not :< (Products, wildcard, Alice, Yen)- rules <- requireRight "valuation rules" $- mkTransferRules [scaleBy (source GoodA) (target GoodA) 2,- scaleBy (source GoodB) (target GoodB) 10]- valuationEntries <- requireRight "valuation transfer" (transferEntries rules ledger)- let valued = ledger .+ valuationEntries+ let valueGood value (_ :< (_, good, _, _)) = case good of+ GoodA -> (2 * value, target GoodA)+ GoodB -> (10 * value, target GoodB)+ AnyValuationGood -> (value, source AnyValuationGood)+ valued = Algebra.mapPosting valueGood ledger collapsed = bar (valued .+ collapseNetEntries [patternBase] dropGood valued) assertTest "valuation of two goods becomes one 40 posting" $ rawObservation collapsed == Map.singleton expected 40@@ -577,13 +518,13 @@ ledger = 7 .@ source :: Alg MoneyDecimal TestBase target = Not :< (Deposits, wildcard) concrete <- requireRight "concrete source rule" $- mkTransferRules [relabel (Not :< (Sales, Yen)) target]+ mkTransferRules [TransferRule (Not :< (Sales, Yen)) target Relabel] concreteEntries <- requireRight "concrete source application" $ transferEntries concrete ledger assertTest "concrete source does not match ledger wildcard" $ Algebra.isZero concreteEntries wildcardRule <- requireRight "wildcard source rule" $- mkTransferRules [relabel source target]+ mkTransferRules [TransferRule source target Relabel] wildcardEntries <- requireRight "wildcard source application" $ transferEntries wildcardRule ledger assertTest "wildcard source matches ledger wildcard" $
+ test/Value/MoneyDoubleBinarySpec.hs view
@@ -0,0 +1,60 @@+-- | Binary compatibility tests for the Algebra value layer.+-- The binary package's Double instance is the byte and decoder oracle.+-- Start with 'runTests' for exhaustive boundary cases and generated inputs.+module Value.MoneyDoubleBinarySpec (runTests) where++import Control.Monad (unless)+import qualified Data.Binary as Binary+import GHC.Float (castDoubleToWord64, castWord64ToDouble)+import System.Exit (exitFailure)+import Test.QuickCheck+import ExchangeAlgebra.Algebra.Value (MoneyDouble(..), toDouble)++-- | Check bytes and decoded bits, retaining binary's behavior for NaN and -0.+-- Finite inputs must additionally recover their original numeric value.+compatible :: Double -> Property+compatible value = conjoin+ [ Binary.encode (MoneyDouble value) === Binary.encode value+ , castDoubleToWord64 wrapped === castDoubleToWord64 bare+ , counterexample "finite value roundtrip" finiteRoundtrip+ ]+ where+ wrapped = toDouble (Binary.decode (Binary.encode (MoneyDouble value)))+ bare = Binary.decode (Binary.encode value) :: Double+ finiteRoundtrip :: Bool+ finiteRoundtrip+ | isNaN value || isInfinite value = True+ | otherwise = wrapped == value++-- | Include every binary exponent and signed special and mantissa boundaries.+boundaryValues :: [Double]+boundaryValues = signed+ ( [ 0, 5e-324, 1e-320, 1 / 0, 0 / 0+ , 2 ** 31 - 1, 2 ** 31, 2 ** 31 + 1+ , encodeFloat (2 ^ (53 :: Int) - 1) 971+ ]+ ++ [2 ^^ exponent | exponent <- [-1074 .. 1023 :: Int]]+ )+ ++ map castWord64ToDouble [0x7ff0000000000001, 0xfff8000000000001]+ where+ signed :: [Double] -> [Double]+ signed values = values ++ map negate values++-- | Fail the suite if a generated or deterministic compatibility check fails.+checkProperty :: String -> Property -> IO ()+checkProperty label law = do+ result <- quickCheckWithResult stdArgs { maxSuccess = 1000, chatty = False } law+ unless (isSuccess result) $ do+ putStrLn ("[FAIL] MoneyDouble Binary " ++ label)+ putStr (output result)+ exitFailure+ putStrLn ("[PASS] MoneyDouble Binary " ++ label)++-- | Check deterministic boundaries, arbitrary Double values, and arbitrary bits.+runTests :: IO ()+runTests = do+ checkProperty "special values and every exponent" $ once $+ conjoin [counterexample (show value) (compatible value) | value <- boundaryValues]+ checkProperty "arbitrary Double" (property compatible)+ checkProperty "arbitrary IEEE-754 bits" $+ forAll arbitrary (compatible . castWord64ToDouble)
test/compat-clients/MixedPath.hs view
@@ -17,12 +17,9 @@ import qualified ExchangeAlgebra.Algebra.Value as Value import qualified ExchangeAlgebra.Algebra.Core as Core import qualified ExchangeAlgebra.Algebra.Posting as Posting-import qualified ExchangeAlgebra.Algebra.Transfer.Rule as Rule import qualified ExchangeAlgebra.Accounting.Closing as Closing import qualified ExchangeAlgebra.Journal.Core as JournalCore-import qualified ExchangeAlgebra.Value as OldValue-import qualified ExchangeAlgebra.TrialBalance.Balance as OldTrialBalance-import qualified ExchangeAlgebra.Consolidation.Worksheet as OldConsolidation+import qualified ExchangeAlgebra.Accounting.TrialBalance.Balance as Balance import qualified ExchangeAlgebra.Accounting.TrialBalance as TrialBalance import qualified ExchangeAlgebra.Accounting.Consolidation as Consolidation import qualified ExchangeAlgebra.Accounting.Statements as Statements@@ -59,26 +56,23 @@ mixedValue :: Value.MoneyDecimal -> Value.MoneyDecimal mixedValue = id -mixedOldValue :: OldValue.MoneyDecimal -> Value.MoneyDecimal-mixedOldValue = id- -- | Apply the new closing entry point to an algebra built through the old path.-mixedClosing :: Either (Rule.TransferApplyError Double (HatBase Account.AccountTitles))+mixedClosing :: Either (Closing.ClosingError Double (HatBase Account.AccountTitles)) (Core.Alg Double (HatBase Account.AccountTitles)) mixedClosing = Closing.closingEntries Old.oldExpression --- | Pass a balance made through the old path to the new account readout.+-- | Pass a balance read through the balance module to the new account readout. mixedTrialBalance :: TrialBalance.AccountBalance Double-mixedTrialBalance = TrialBalance.combineBalances oldBalance oldBalance+mixedTrialBalance = TrialBalance.combineBalances balance balance where- oldBalance = OldTrialBalance.balanceFor Cash- (OldTrialBalance.accountBalances Old.oldExpression)+ balance = Balance.balanceFor Cash+ (Balance.accountBalances Old.oldExpression) mixedStatements :: Maybe Statements.DerivedMetric mixedStatements = Statements.metricForLegacyTitle Cash mixedConsolidation- :: OldConsolidation.WorksheetInput String String Double+ :: Consolidation.WorksheetInput String String Double -> Consolidation.WorksheetInput String String Double mixedConsolidation = id
test/compat-clients/NewPath.hs view
@@ -12,8 +12,10 @@ import qualified ExchangeAlgebra.Accounting.Exchange as Exchange import qualified ExchangeAlgebra.Accounting.Account as Account import qualified ExchangeAlgebra.Algebra.Element as Element-import qualified ExchangeAlgebra.Algebra.Transfer.Rule as Rule+import qualified ExchangeAlgebra.Algebra.Transfer as Rule import qualified ExchangeAlgebra.Accounting.Closing as Closing+import ExchangeAlgebra.Accounting.Closing+ ( ClosingTargetViolation(..), closingTargetViolation, ClosingError(..), SettleError(..) ) import qualified ExchangeAlgebra.Journal.Core as Journal import qualified ExchangeAlgebra.Algebra.Posting as Posting import qualified ExchangeAlgebra.Algebra.Value as Value@@ -22,6 +24,12 @@ import qualified ExchangeAlgebra.Accounting.Statements as Statements import qualified ExchangeAlgebra.Accounting.Consolidation as Consolidation import qualified ExchangeAlgebra.IO.Input as Input+import ExchangeAlgebra.IO.Input+ ( ConvErrorOf(..), ConvError, EntryErrorOf(..), EntryError+ , JournalErrorOf(..), JournalError, JournalCertOf(..), JournalCert+ , AccountResolver, AccountNameTable, resolveWith, defaultAccountNames+ , extendAccountNames, vocabularyNames, checkedEntryTextBy, certifyJournalTextBy )+import ExchangeAlgebra.IO.Input.Csv (parseJournalCsvBy, parseNotedJournalCsvBy) import qualified ExchangeAlgebra.IO.Input.Csv as InputCsv import qualified ExchangeAlgebra.IO.Input.Assist as Assist import qualified ExchangeAlgebra.IO.Output.Csv as OutputCsv@@ -77,7 +85,7 @@ elementClient = Element.matchesQuery Cash Cash -- | Use the public closing entry point with the new algebra and account paths.-closingClient :: Either (Rule.TransferApplyError Double (HatBase AccountTitles))+closingClient :: Either (Closing.ClosingError Double (HatBase AccountTitles)) (Alg Double (HatBase AccountTitles)) closingClient = Closing.closingEntries oldExpression @@ -154,3 +162,55 @@ -> Either (Admission.AdmissionFailure String (HatBase AccountTitles)) (Admission.Admitted String (HatBase AccountTitles)) admissionClient = Admission.admit++-- | Extend the built-in table with the client's local name for cash.+nameTableClient :: AccountNameTable AccountTitles+nameTableClient = extendAccountNames [(mempty, Cash)] defaultAccountNames++-- | Resolve a name using the extended chart.+nameResolverClient :: AccountResolver AccountTitles+nameResolverClient = resolveWith nameTableClient++-- | Construct a diagnostic using the built-in synonyms and the generic constructors.+nameErrorClient+ :: (ConvError, EntryError Double, JournalError String Double, JournalCert String Double)+nameErrorClient = (unknown, entry, journal, Rejected (Data.List.NonEmpty.singleton journal))+ where+ unknown = UnknownAccount mempty+ entry = EntryParse 0 unknown+ journal = EntryErrors "tx" (Data.List.NonEmpty.singleton entry)++-- | Check text rows against a chart extended with a local name.+checkedNamesClient :: Either (Data.List.NonEmpty.NonEmpty (EntryError Double))+ (Alg Double (HatBase AccountTitles))+checkedNamesClient = checkedEntryTextBy nameResolverClient Account.OrdinaryJournal []++-- | Certify entries against just the listed titles.+certifiedNamesClient :: JournalCert String Double+certifiedNamesClient = certifyJournalTextBy (resolveWith (vocabularyNames [Cash, Sales]))+ Account.OrdinaryJournal []++-- | Read terms using the same resolver as the checked input.+csvNamesClient :: Either ConvError (Alg Double (HatBase AccountTitles))+csvNamesClient = parseJournalCsvBy nameResolverClient InputCsv.scientificAmount mempty++-- | Extract the amounts from note-bearing rows.+notedCsvNamesClient :: Either ConvError [Double]+notedCsvNamesClient = fmap (map (\(_, _, amount, _) -> amount))+ (parseNotedJournalCsvBy nameResolverClient InputCsv.scientificAmount mempty)++-- | Check a closing target through the public accounting import.+closingTargetCheckClient :: Maybe ClosingTargetViolation+closingTargetCheckClient = closingTargetViolation Sales++-- | Construct a rejected target using the public closing diagnostic.+closingTargetErrorClient :: ClosingError Double (HatBase AccountTitles)+closingTargetErrorClient = InvalidClosingTarget Sales (ClosingTargetNotEquity Account.Revenue)++-- | Wrap a transfer failure in the public closing error type.+closingTransferErrorClient :: ClosingError Double (HatBase AccountTitles)+closingTransferErrorClient = ClosingTransferError (Rule.NonFiniteBalance (Not :< Sales))++-- | Construct the additional settlement failure through the public import.+settleTargetErrorClient :: SettleError (HatBase AccountTitles)+settleTargetErrorClient = InvalidSettleTarget Sales (ClosingTargetNotEquity Account.Revenue)
test/compat-clients/OldPath.hs view
@@ -6,12 +6,12 @@ import ExchangeAlgebra.Algebra (Alg(Zero, (:@)), Redundant((.+)), ( .@ )) import qualified ExchangeAlgebra.Algebra.Base as Base import ExchangeAlgebra.Algebra.Base (Hat(Not), HatBase((:<)))-import ExchangeAlgebra.Algebra.Base.Element (AccountTitles(Cash, Sales))-import qualified ExchangeAlgebra.Algebra.Base.Account.Registry as Registry-import ExchangeAlgebra.Algebra.Transfer.Rule ()+import ExchangeAlgebra.Accounting.Account (AccountTitles(Cash, Sales))+import qualified ExchangeAlgebra.Accounting.Account as Registry+import ExchangeAlgebra.Algebra.Transfer () import qualified ExchangeAlgebra.Journal as Journal-import qualified ExchangeAlgebra.Posting as Posting-import qualified ExchangeAlgebra.Value as Value+import qualified ExchangeAlgebra.Algebra.Posting as Posting+import qualified ExchangeAlgebra.Algebra.Value as Value type ClientBasePart = Base.BasePart (HatBase AccountTitles)
test/compat-clients/README.md view
@@ -6,12 +6,10 @@ STACK_ARGS="--system-ghc --no-install-ghc" bash test/compat-clients/check.sh ``` -`OldPath.hs` uses the current public imports, including the umbrella,-algebra, journal, base, transfer rule, posting, and value modules. It checks-the `.+`, `.@`, and `:<` fixities, a class method call, a constructor pattern,-and the `BasePart` associated type. `NewPath.hs` and `MixedPath.hs` are-placeholders that compile the old client now. Replace their imports and-expressions with the new and mixed paths as each P2 wave creates them.+`OldPath.hs` checks umbrella imports, operator fixities, a class method call,+a constructor pattern, and the `BasePart` associated type. `NewPath.hs` uses+the defining modules. `MixedPath.hs` combines current paths with retained+simulation paths. `CompatInstance.hs` defines two client-owned base types. One uses the `ExBaseClass` defaults, and the other overrides `whatDiv` and `isContra`.
test/compat-clients/check.sh view
@@ -16,7 +16,7 @@ -outputdir "$compat_tmp" \ "$compat_root/test/compat-clients/$compat_client.hs" done-printf '[PASS] old, new, and mixed clients compiled\n'+printf '[PASS] umbrella, defining-module, and mixed clients compiled\n' stack ${compat_stack_args[@]+"${compat_stack_args[@]}"} \ --stack-yaml "$compat_root/stack.yaml" exec -- ghc \ -fforce-recomp -v0 -fdiagnostics-color=never -i \
− test/compile-fail/DeprecatedTransfer.hs
@@ -1,9 +0,0 @@--- | Compilation succeeds, but the public rule-module re-export still warns.-module DeprecatedTransfer where--import ExchangeAlgebra hiding (scaleBy)-import ExchangeAlgebra.Algebra.Transfer.Rule (scaleBy)---- | Legacy per-posting scaling remains available during migration.-legacyRule :: TransferRule Double (HatBase (AccountTitles, CountUnit))-legacyRule = scaleBy (Not :< (RentExpense, Yen)) (Not :< (PrepaidExpenses, Yen)) 0.5
+ test/compile-fail/JcciHiddenConstructor.hs view
@@ -0,0 +1,7 @@+module JcciHiddenConstructor where++import ExchangeAlgebra.Accounting.Account (AccountTitles(GovernmentService))+import ExchangeAlgebra.Accounting.Account.Jcci++title :: JcciTitles+title = JcciTitles GovernmentService
+ test/compile-fail/JcciMacroTitle.hs view
@@ -0,0 +1,6 @@+module JcciMacroTitle where++import ExchangeAlgebra.Accounting.Account.Jcci++title :: JcciTitles+title = GovernmentService
test/compile-fail/check.sh view
@@ -15,19 +15,20 @@ compile() { local snippet=$1+ local source=${2:-"$admission_root/test/compile-fail/$snippet.hs"} stack ${admission_stack_args[@]+"${admission_stack_args[@]}"} \ --stack-yaml "$admission_root/stack.yaml" exec -- ghc \ -fno-code -fforce-recomp -v0 -Wdeprecations -fdiagnostics-color=never -i \ -hide-all-packages -package base -package text -package containers \ -package exchangealgebra -outputdir "$admission_tmp" \- "$admission_root/test/compile-fail/$snippet.hs" \+ "$source" \ > "$admission_tmp/$snippet.log" 2>&1 } reject() { local snippet=$1 local reason=$2- if compile "$snippet"; then+ if compile "$snippet" "${3:-}"; then printf '[FAIL] %s compiled unexpectedly\n' "$snippet" exit 1 fi@@ -66,22 +67,40 @@ reject AlgRecordUpdate 'non-bidirectional pattern synonym|not a record selector|not a record field' reject AlgHiddenConstructor 'does not export any children|does not export.*(Single|Liner)' -# Deprecated APIs remain usable, and their warning survives public rule-module re-export.-warn_deprecated() {- local snippet=$1- local identifier=$2- if ! compile "$snippet"; then- printf '[FAIL] %s did not compile\n' "$snippet"- cat "$admission_tmp/$snippet.log"- exit 1- fi- if ! grep -Eq "In the use of [‘'\"]([^‘’'\"]*\\.)?${identifier}[’'\"]" \- "$admission_tmp/$snippet.log"; then- printf '[FAIL] %s compiled without the expected deprecation warning\n' "$snippet"- cat "$admission_tmp/$snippet.log"- exit 1- fi- printf '[PASS] %s compiled with the expected deprecation warning\n' "$snippet"-}+reject JcciMacroTitle 'not in scope:.*GovernmentService'+# GHC reports the type-only name as an illegal term-level use when it is in scope.+reject JcciHiddenConstructor 'not in scope:.*JcciTitles|Illegal term-level use of the type constructor.*JcciTitles' -warn_deprecated DeprecatedTransfer scaleBy+# Build a case from the multiline pragma and remove one branch for the negative client.+jcci_source="$admission_root/src/ExchangeAlgebra/Accounting/Account/Jcci.hs"+awk '+ BEGIN {+ print "{-# OPTIONS_GHC -Werror=incomplete-patterns #-}"+ print "module JcciComplete where"+ print "import ExchangeAlgebra.Accounting.Account.Jcci"+ print "match :: JcciTitles -> ()"+ print "match title = case title of"+ }+ /^\{-# COMPLETE([[:space:]]|$)/ {+ in_pragma = 1+ sub(/^\{-# COMPLETE[[:space:]]*/, "")+ }+ in_pragma {+ last = sub(/::.*/, "")+ gsub(/,/, " ")+ for (i = 1; i <= NF; i++) {+ if ($i == "Cash") cash+++ print " " $i " -> ()"+ }+ if (last) in_pragma = 0+ }+ END { if (cash != 1 || in_pragma) exit 1 }+' "$jcci_source" > "$admission_tmp/JcciComplete.hs"+if ! compile JcciComplete "$admission_tmp/JcciComplete.hs"; then+ cat "$admission_tmp/JcciComplete.log"+ exit 1+fi+printf '[PASS] JcciComplete compiled as an exhaustive case\n'+sed -e 's/^module JcciComplete /module JcciIncomplete /' -e '/^ Cash -> ()$/d' \+ "$admission_tmp/JcciComplete.hs" > "$admission_tmp/JcciIncomplete.hs"+reject JcciIncomplete 'incomplete-patterns' "$admission_tmp/JcciIncomplete.hs"
test/doctests.hs view
@@ -15,9 +15,8 @@ , "src/ExchangeAlgebra/Algebra/Transfer/Representation.hs" , "src/ExchangeAlgebra/Accounting/Closing.hs" , "src/ExchangeAlgebra/Journal/Core/Representation.hs"- -- reporting gates have their own examples;+ -- reporting modules have their own examples; -- explicit roots keep them covered independently of umbrellas.- , "src/ExchangeAlgebra/Accounting/TrialBalance/Validation.hs" , "src/ExchangeAlgebra/Accounting/Statements/Presentation.hs" , "src/ExchangeAlgebra/Accounting/Consolidation.hs" -- admission execution modules are not re-exported in full;@@ -31,6 +30,9 @@ -- the admission examples import its public API qualified; -- load that module before doctest evaluates those imports. , "src/ExchangeAlgebra/IO/Input/Admission.hs"+ -- the admission walkthrough also imports the audits qualified;+ -- the module is not re-exported from the umbrella.+ , "src/ExchangeAlgebra/Accounting/Audit.hs" , "src/ExchangeAlgebra/Algebra/Value.hs" , "src/ExchangeAlgebra/Algebra/Value/Class.hs" , "src/ExchangeAlgebra/Simulation/Network/Representation.hs"@@ -40,7 +42,7 @@ , "src/ExchangeAlgebra/Simulate/Policy.hs" -- closing-adjustment builders: not re-exported from the -- umbrella, so listed explicitly to check its examples too.- , "src/ExchangeAlgebra/Bookkeeping.hs"+ , "src/ExchangeAlgebra/Accounting/Entries.hs" -- dependency-free input-conversion core: not re-exported from -- the umbrella, so listed explicitly to check its examples too. , "src/ExchangeAlgebra/IO/Input.hs"@@ -48,7 +50,7 @@ , "src/ExchangeAlgebra/IO/Input/Csv.hs" , "src/ExchangeAlgebra/IO/Input/Checked.hs" , "src/ExchangeAlgebra/IO/Input/Assist.hs"- , "src/ExchangeAlgebra/Reporting/Group.hs"+ , "src/ExchangeAlgebra/Accounting/Statements/Group.hs" -- optimization layer: not re-exported from the umbrella, -- so listed explicitly to check its examples too. , "src/ExchangeAlgebra/Simulation/Optimize.hs"@@ -60,7 +62,4 @@ , "src/ExchangeAlgebra/Simulate/Random.hs" , "src/ExchangeAlgebra/IO/Output/Csv.hs" , "src/ExchangeAlgebra/IO/Output/Statements.hs"- -- deprecated Render shims still carry the row-layout examples.- , "src/ExchangeAlgebra/Render/Csv.hs"- , "src/ExchangeAlgebra/Render/Bookkeeping.hs" , "src/ExchangeAlgebra/Simulation/Output.hs"]
test/fixtures/account-algebra-behavior/presentation.tsv view
@@ -34,7 +34,6 @@ AmortizationExpense SalesCost BusinessTrip-Commutation UtilitiesExpense RentExpense AdvertisingExpense@@ -242,3 +241,4 @@ SalesAllowances PurchaseAllowances ReversalOfAllowanceForBonuses+DirectorsCompensations
test/fixtures/account-algebra-behavior/projection-membership.tsv view
@@ -34,7 +34,6 @@ AmortizationExpense 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 SalesCost 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 BusinessTrip 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0-Commutation 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 UtilitiesExpense 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 RentExpense 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 AdvertisingExpense 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0@@ -242,3 +241,4 @@ SalesAllowances 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 PurchaseAllowances 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 ReversalOfAllowanceForBonuses 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0+DirectorsCompensations 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
test/fixtures/account-algebra-behavior/semantics.tsv view
@@ -1,244 +1,244 @@-# account-algebra-behavior semantics (title, enum, binaryHex, division, closing, isContra, whichSide Not, whichSide Hat, whatPIMO, fixedCurrent, finalStockProbe); schema 1-Cash 0 8000 Assets CloseByDivision False Debit Credit PS Current Nothing-Deposits 1 8001 Assets CloseByDivision False Debit Credit PS Current Nothing-CurrentDeposits 2 8002 Assets CloseByDivision False Debit Credit PS Current Nothing-Securities 3 8003 Assets CloseByDivision False Debit Credit PS Current Nothing-InvestmentSecurities 4 8004 Assets CloseByDivision False Debit Credit PS Fixed Nothing-InvestmentInAssociate 5 8005 Assets CloseByDivision False Debit Credit PS Fixed Nothing-LongTermNationalBonds 6 8006 Assets CloseByDivision False Debit Credit PS Fixed Nothing-ShortTermNationalBonds 7 8007 Assets CloseByDivision False Debit Credit PS Current Nothing-Products 8 8008 Assets CloseByDivision False Debit Credit PS Current Nothing-Machinery 9 8009 Assets CloseByDivision False Debit Credit PS Fixed Nothing-Building 10 800a Assets CloseByDivision False Debit Credit PS Fixed Nothing-Vehicle 11 800b Assets CloseByDivision False Debit Credit PS Fixed Nothing-StockInvestment 12 800c Assets CloseByDivision False Debit Credit PS Other Nothing-EquipmentInvestment 13 800d Assets CloseByDivision False Debit Credit PS Fixed Nothing-LongTermLoansReceivable 14 800e Assets CloseByDivision False Debit Credit PS Fixed Nothing-AccountsReceivable 15 800f Assets CloseByDivision False Debit Credit PS Current Nothing-ShortTermLoansReceivable 16 8010 Assets CloseByDivision False Debit Credit PS Current Nothing-ReserveDepositReceivable 17 8011 Assets CloseByDivision False Debit Credit PS Current Nothing-Gold 18 8012 Assets CloseByDivision False Debit Credit PS Fixed Nothing-GovernmentService 19 8013 Assets CloseByDivision False Debit Credit PS Current Nothing-CapitalStock 20 8014 Equity CloseByDivision False Credit Debit MS Other Nothing-RetainedEarnings 21 8015 Equity CloseByDivision False Credit Debit MS Other SELF-LongTermLoansPayable 22 8016 Liability CloseByDivision False Credit Debit MS Fixed Nothing-ShortTermLoansPayable 23 8017 Liability CloseByDivision False Credit Debit MS Current Nothing-LoansPayable 24 8018 Liability CloseByDivision False Credit Debit MS Current Nothing-ReserveForDepreciation 25 8019 Liability CloseByDivision False Credit Debit MS Current Nothing-DepositPayable 26 801a Liability CloseByDivision False Credit Debit MS Current Nothing-LongTermNationalBondsPayable 27 801b Liability CloseByDivision False Credit Debit MS Fixed Nothing-ShortTermNationalBondsPayable 28 801c Liability CloseByDivision False Credit Debit MS Current Nothing-ReserveDepositPayable 29 801d Liability CloseByDivision False Credit Debit MS Current Nothing-CentralBankNotePayable 30 801e Liability CloseByDivision False Credit Debit MS Current Nothing-Depreciation 31 801f Cost CloseByDivision False Debit Credit OUT Other Flip-AmortizationExpense 32 8020 Cost CloseByDivision False Debit Credit OUT Other Flip-SalesCost 33 8021 Cost CloseByDivision False Debit Credit OUT Other Flip-BusinessTrip 34 8022 Cost CloseByDivision False Debit Credit OUT Other Flip-Commutation 35 8023 Cost CloseByDivision False Debit Credit OUT Other Flip-UtilitiesExpense 36 8024 Cost CloseByDivision False Debit Credit OUT Other Flip-RentExpense 37 8025 Cost CloseByDivision False Debit Credit OUT Other Flip-AdvertisingExpense 38 8026 Cost CloseByDivision False Debit Credit OUT Other Flip-DeliveryExpenses 39 8027 Cost CloseByDivision False Debit Credit OUT Other Flip-SuppliesExpenses 40 8028 Cost CloseByDivision False Debit Credit OUT Other Flip-MiscellaneousExpenses 41 8029 Cost CloseByDivision False Debit Credit OUT Other Flip-WageExpenditure 42 802a Cost CloseByDivision False Debit Credit OUT Other Flip-InterestExpense 43 802b Cost CloseByDivision False Debit Credit OUT Other Flip-TaxesExpense 44 802c Cost CloseByDivision False Debit Credit OUT Other Flip-ConsumptionExpenditure 45 802d Cost CloseByDivision False Debit Credit OUT Other Flip-SubsidyExpense 46 802e Cost CloseByDivision False Debit Credit OUT Other Flip-CentralBankPaymentExpense 47 802f Cost CloseByDivision False Debit Credit OUT Other Flip-Purchases 48 8030 Cost CloseByDivision False Debit Credit OUT Other Flip-NetIncome 49 8031 Cost NoClose False Debit Credit OUT Other Nothing-ValueAdded 50 8032 Revenue CloseByDivision False Credit Debit IN Other Keep-SubsidyIncome 51 8033 Revenue CloseByDivision False Credit Debit IN Other Keep-NationalBondInterestEarned 52 8034 Revenue CloseByDivision False Credit Debit IN Other Keep-DepositInterestEarned 53 8035 Revenue CloseByDivision False Credit Debit IN Other Keep-GrossProfit 54 8036 Revenue CloseByDivision False Credit Debit IN Other Keep-OrdinaryProfit 55 8037 Revenue CloseByDivision False Credit Debit IN Other Keep-InterestEarned 56 8038 Revenue CloseByDivision False Credit Debit IN Other Keep-ReceiptFee 57 8039 Revenue CloseByDivision False Credit Debit IN Other Keep-RentalIncome 58 803a Revenue CloseByDivision False Credit Debit IN Other Keep-WageEarned 59 803b Revenue CloseByDivision False Credit Debit IN Other Keep-TaxesRevenue 60 803c Revenue CloseByDivision False Credit Debit IN Other Keep-CentralBankPaymentIncome 61 803d Revenue CloseByDivision False Credit Debit IN Other Keep-Sales 62 803e Revenue CloseByDivision False Credit Debit IN Other Keep-EquityInEarningsOfInvestee 63 803f Revenue CloseByDivision False Credit Debit IN Other Keep-NetLoss 64 8040 Revenue NoClose False Credit Debit IN Other Nothing-PettyCash 65 8041 Assets CloseByDivision False Debit Credit PS Current Nothing-NotesReceivable 66 8042 Assets CloseByDivision False Debit Credit PS Current Nothing-ElectronicallyRecordedReceivable 67 8043 Assets CloseByDivision False Debit Credit PS Current Nothing-CreditCardReceivable 68 8044 Assets CloseByDivision False Debit Credit PS Current Nothing-NotesLoansReceivable 69 8045 Assets CloseByDivision False Debit Credit PS Current Nothing-MerchandiseInventory 70 8046 Assets CloseByDivision False Debit Credit PS Current Nothing-AdvancesPaid 71 8047 Assets CloseByDivision False Debit Credit PS Current Nothing-PrepaidExpenses 72 8048 Assets CloseByDivision False Debit Credit PS Current Nothing-AccruedRevenue 73 8049 Assets CloseByDivision False Debit Credit PS Current Nothing-OtherReceivables 74 804a Assets CloseByDivision False Debit Credit PS Current Nothing-PaymentsOnBehalf 75 804b Assets CloseByDivision False Debit Credit PS Current Nothing-SuspensePayments 76 804c Assets CloseByDivision False Debit Credit PS Current Nothing-ConsumptionTaxPaid 77 804d Assets CloseByDivision False Debit Credit PS Current Nothing-PrepaidCorporateIncomeTaxes 78 804e Assets CloseByDivision False Debit Credit PS Current Nothing-Land 79 804f Assets CloseByDivision False Debit Credit PS Fixed Nothing-Fixtures 80 8050 Assets CloseByDivision False Debit Credit PS Fixed Nothing-Patent 81 8051 Assets CloseByDivision False Debit Credit PS Fixed Nothing-Trademark 82 8052 Assets CloseByDivision False Debit Credit PS Fixed Nothing-Software 83 8053 Assets CloseByDivision False Debit Credit PS Fixed Nothing-CashOverShort 84 8054 Assets CloseByDivision False Debit Credit PS Other Nothing-AccountsPayable 85 8055 Liability CloseByDivision False Credit Debit MS Current Nothing-NotesPayable 86 8056 Liability CloseByDivision False Credit Debit MS Current Nothing-ElectronicallyRecordedObligations 87 8057 Liability CloseByDivision False Credit Debit MS Current Nothing-NotesLoansPayable 88 8058 Liability CloseByDivision False Credit Debit MS Current Nothing-BankOverdraft 89 8059 Liability CloseByDivision False Credit Debit MS Current Nothing-AdvancesReceived 90 805a Liability CloseByDivision False Credit Debit MS Current Nothing-UnearnedRevenue 91 805b Liability CloseByDivision False Credit Debit MS Current Nothing-AccruedExpenses 92 805c Liability CloseByDivision False Credit Debit MS Current Nothing-OtherPayables 93 805d Liability CloseByDivision False Credit Debit MS Current Nothing-DepositsReceived 94 805e Liability CloseByDivision False Credit Debit MS Current Nothing-SuspenseReceipts 95 805f Liability CloseByDivision False Credit Debit MS Current Nothing-ConsumptionTaxReceived 96 8060 Liability CloseByDivision False Credit Debit MS Current Nothing-AccruedConsumptionTax 97 8061 Liability CloseByDivision False Credit Debit MS Current Nothing-AccruedCorporateIncomeTaxes 98 8062 Liability CloseByDivision False Credit Debit MS Current Nothing-UnpaidDividends 99 8063 Liability CloseByDivision False Credit Debit MS Current Nothing-AllowanceForDoubtfulAccounts 100 8064 Assets CloseByDivision True Credit Debit MS Current Nothing-AccumulatedDepreciation 101 8065 Assets CloseByDivision True Credit Debit MS Fixed Nothing-LegalRetainedEarnings 102 8066 Equity CloseByDivision False Credit Debit MS Other Nothing-CumulativeTranslationAdjustment 103 8067 Equity CloseByDivision False Credit Debit MS Other Nothing-ProvisionForDoubtfulAccounts 104 8068 Cost CloseByDivision False Debit Credit OUT Other Flip-BadDebtLoss 105 8069 Cost CloseByDivision False Debit Credit OUT Other Flip-LossOnSalesOfFixedAssets 106 806a Cost CloseByDivision False Debit Credit OUT Other Flip-LossOnSalesOfNotesReceivable 107 806b Cost CloseByDivision False Debit Credit OUT Other Flip-PaymentFees 108 806c Cost CloseByDivision False Debit Credit OUT Other Flip-MiscellaneousLoss 109 806d Cost CloseByDivision False Debit Credit OUT Other Flip-CorporateIncomeTaxes 110 806e Cost CloseByDivision False Debit Credit OUT Other Flip-CommunicationExpenses 111 806f Cost CloseByDivision False Debit Credit OUT Other Flip-GainOnSalesOfFixedAssets 112 8070 Revenue CloseByDivision False Credit Debit IN Other Keep-RecoveryOfBadDebts 113 8071 Revenue CloseByDivision False Credit Debit IN Other Keep-MiscellaneousIncome 114 8072 Revenue CloseByDivision False Credit Debit IN Other Keep-ReversalOfAllowanceForDoubtfulAccounts 115 8073 Revenue CloseByDivision False Credit Debit IN Other Keep-TimeDeposits 116 8074 Assets CloseByDivision False Debit Credit PS Current Nothing-LoansReceivable 117 8075 Assets CloseByDivision False Debit Credit PS Current Nothing-GiftCertificatesReceived 118 8076 Assets CloseByDivision False Debit Credit PS Current Nothing-SecurityDepositsPaid 119 8077 Assets CloseByDivision False Debit Credit PS Fixed Nothing-SuppliesOnHand 120 8078 Assets CloseByDivision False Debit Credit PS Current Nothing-ContractAssets 121 8079 Assets CloseByDivision False Debit Credit PS Current Nothing-IncomeTaxesRefundReceivable 122 807a Assets CloseByDivision False Debit Credit PS Current Nothing-WorkInProcess 123 807b Assets CloseByDivision False Debit Credit PS Current Nothing-DeferredTaxAssets 124 807c Assets CloseByDivision False Debit Credit PS Fixed Nothing-LeasedAssets 125 807d Assets CloseByDivision False Debit Credit PS Fixed Nothing-ToolsAndInstruments 126 807e Assets CloseByDivision False Debit Credit PS Fixed Nothing-ConstructionInProgress 127 807f Assets CloseByDivision False Debit Credit PS Fixed Nothing-Goodwill 128 8080 Assets CloseByDivision False Debit Credit PS Fixed Nothing-SoftwareInProgress 129 8081 Assets CloseByDivision False Debit Credit PS Fixed Nothing-LongTermPrepaidExpenses 130 8082 Assets CloseByDivision False Debit Credit PS Fixed Nothing-DishonoredNotesReceivable 131 8083 Assets CloseByDivision False Debit Credit PS Current Nothing-PrepaidPensionCost 132 8084 Assets CloseByDivision False Debit Credit PS Fixed Nothing-NetDefinedBenefitAsset 133 8085 Assets CloseByDivision False Debit Credit PS Fixed Nothing-DepositsInSpecialAccounts 134 8086 Assets CloseByDivision False Debit Credit PS Current Nothing-Structures 135 8087 Assets CloseByDivision False Debit Credit PS Fixed Nothing-LeaseholdRights 136 8088 Assets CloseByDivision False Debit Credit PS Fixed Nothing-NonOperatingNotesReceivable 137 8089 Assets CloseByDivision False Debit Credit PS Current Nothing-NonOperatingElectronicallyRecordedReceivable 138 808a Assets CloseByDivision False Debit Credit PS Current Nothing-RefundLiabilities 139 808b Liability CloseByDivision False Credit Debit MS Current Nothing-NonOperatingNotesPayable 140 808c Liability CloseByDivision False Credit Debit MS Current Nothing-NonOperatingElectronicallyRecordedObligations 141 808d Liability CloseByDivision False Credit Debit MS Current Nothing-BonusesPayable 142 808e Liability CloseByDivision False Credit Debit MS Current Nothing-AllowanceForRepairs 143 808f Liability CloseByDivision False Credit Debit MS Current Nothing-AllowanceForProductWarranties 144 8090 Liability CloseByDivision False Credit Debit MS Current Nothing-AllowanceForBonuses 145 8091 Liability CloseByDivision False Credit Debit MS Current Nothing-DeferredTaxLiabilities 146 8092 Liability CloseByDivision False Credit Debit MS Fixed Nothing-LeaseObligations 147 8093 Liability CloseByDivision False Credit Debit MS Fixed Nothing-GuaranteeDepositsReceived 148 8094 Liability CloseByDivision False Credit Debit MS Fixed Nothing-AllowanceForRetirementBenefits 149 8095 Liability CloseByDivision False Credit Debit MS Fixed Nothing-LongTermOtherPayables 150 8096 Liability CloseByDivision False Credit Debit MS Fixed Nothing-NetDefinedBenefitLiability 151 8097 Liability CloseByDivision False Credit Debit MS Fixed Nothing-StockSubscriptionDeposits 152 8098 Equity CloseByDivision False Credit Debit MS Other Nothing-LegalCapitalSurplus 153 8099 Equity CloseByDivision False Credit Debit MS Other Nothing-OtherCapitalSurplus 154 809a Equity CloseByDivision False Credit Debit MS Other Nothing-DividendEqualizationReserve 155 809b Equity CloseByDivision False Credit Debit MS Other Nothing-RepairFundReserve 156 809c Equity CloseByDivision False Credit Debit MS Other Nothing-ConstructionFundReserve 157 809d Equity CloseByDivision False Credit Debit MS Other Nothing-GeneralReserve 158 809e Equity CloseByDivision False Credit Debit MS Other Nothing-ValuationDifferenceOnOtherSecurities 159 809f Equity CloseByDivision False Credit Debit MS Other Nothing-NonControllingInterests 160 80a0 Equity CloseByDivision False Credit Debit MS Other Nothing-CapitalSurplus 161 80a1 Equity CloseByDivision False Credit Debit MS Other Nothing-EarnedSurplus 162 80a2 Equity CloseByDivision False Credit Debit MS Other Nothing-ServiceRevenue 163 80a3 Revenue CloseByDivision False Credit Debit IN Other Keep-OperatingRevenue 164 80a4 Revenue CloseByDivision False Credit Debit IN Other Keep-GainOnSalesOfSecurities 165 80a5 Revenue CloseByDivision False Credit Debit IN Other Keep-GainOnValuationOfSecurities 166 80a6 Revenue CloseByDivision False Credit Debit IN Other Keep-DividendsReceived 167 80a7 Revenue CloseByDivision False Credit Debit IN Other Keep-InterestOnSecurities 168 80a8 Revenue CloseByDivision False Credit Debit IN Other Keep-GainOnSalesOfInvestmentSecurities 169 80a9 Revenue CloseByDivision False Credit Debit IN Other Keep-InsuranceGain 170 80aa Revenue CloseByDivision False Credit Debit IN Other Keep-GainOnBargainPurchase 171 80ab Revenue CloseByDivision False Credit Debit IN Other Keep-ReversalOfAllowanceForRepairs 172 80ac Revenue CloseByDivision False Credit Debit IN Other Keep-ReversalOfAllowanceForProductWarranties 173 80ad Revenue CloseByDivision False Credit Debit IN Other Keep-GainOnDonationOfFixedAssets 174 80ae Revenue CloseByDivision False Credit Debit IN Other Keep-GainOnNationalSubsidies 175 80af Revenue CloseByDivision False Credit Debit IN Other Keep-GainOnConstructionGrants 176 80b0 Revenue CloseByDivision False Credit Debit IN Other Keep-LandRentReceived 177 80b1 Revenue CloseByDivision False Credit Debit IN Other Keep-SalesRebates 178 80b2 Revenue CloseByDivision True Debit Credit OUT Other Flip-CostOfServices 179 80b3 Cost CloseByDivision False Debit Credit OUT Other Flip-OperatingExpenses 180 80b4 Cost CloseByDivision False Debit Credit OUT Other Flip-InventoryShrinkageLoss 181 80b5 Cost CloseByDivision False Debit Credit OUT Other Flip-LossOnValuationOfMerchandise 182 80b6 Cost CloseByDivision False Debit Credit OUT Other Flip-Bonuses 183 80b7 Cost CloseByDivision False Debit Credit OUT Other Flip-RetirementBenefitExpenses 184 80b8 Cost CloseByDivision False Debit Credit OUT Other Flip-ProvisionForRepairs 185 80b9 Cost CloseByDivision False Debit Credit OUT Other Flip-ProvisionForBonuses 186 80ba Cost CloseByDivision False Debit Credit OUT Other Flip-ProvisionForProductWarranties 187 80bb Cost CloseByDivision False Debit Credit OUT Other Flip-ResearchAndDevelopmentExpenses 188 80bc Cost CloseByDivision False Debit Credit OUT Other Flip-AmortizationOfGoodwill 189 80bd Cost CloseByDivision False Debit Credit OUT Other Flip-AmortizationOfSoftware 190 80be Cost CloseByDivision False Debit Credit OUT Other Flip-AmortizationOfPatents 191 80bf Cost CloseByDivision False Debit Credit OUT Other Flip-LeaseExpenses 192 80c0 Cost CloseByDivision False Debit Credit OUT Other Flip-IncorporationExpenses 193 80c1 Cost CloseByDivision False Debit Credit OUT Other Flip-StockIssuanceCosts 194 80c2 Cost CloseByDivision False Debit Credit OUT Other Flip-BusinessCommencementExpenses 195 80c3 Cost CloseByDivision False Debit Credit OUT Other Flip-DevelopmentExpenses 196 80c4 Cost CloseByDivision False Debit Credit OUT Other Flip-LossOnSalesOfElectronicallyRecordedReceivables 197 80c5 Cost CloseByDivision False Debit Credit OUT Other Flip-LossOnSalesOfReceivables 198 80c6 Cost CloseByDivision False Debit Credit OUT Other Flip-LossOnSalesOfSecurities 199 80c7 Cost CloseByDivision False Debit Credit OUT Other Flip-LossOnValuationOfSecurities 200 80c8 Cost CloseByDivision False Debit Credit OUT Other Flip-LossOnSalesOfInvestmentSecurities 201 80c9 Cost CloseByDivision False Debit Credit OUT Other Flip-LossOnFire 202 80ca Cost CloseByDivision False Debit Credit OUT Other Flip-LossOnRetirementOfFixedAssets 203 80cb Cost CloseByDivision False Debit Credit OUT Other Flip-LossOnReductionOfFixedAssets 204 80cc Cost CloseByDivision False Debit Credit OUT Other Flip-AdditionalIncomeTaxesForPriorPeriods 205 80cd Cost CloseByDivision False Debit Credit OUT Other Flip-RefundOfIncomeTaxes 206 80ce Cost CloseByDivision True Credit Debit IN Other Keep-PurchaseRebates 207 80cf Cost CloseByDivision True Credit Debit IN Other Keep-WelfareExpenses 208 80d0 Cost CloseByDivision False Debit Credit OUT Other Flip-MaintenanceExpenses 209 80d1 Cost CloseByDivision False Debit Credit OUT Other Flip-StatutoryWelfareExpenses 210 80d2 Cost CloseByDivision False Debit Credit OUT Other Flip-LandRentPaid 211 80d3 Cost CloseByDivision False Debit Credit OUT Other Flip-InsuranceExpense 212 80d4 Cost CloseByDivision False Debit Credit OUT Other Flip-RepairsExpense 213 80d5 Cost CloseByDivision False Debit Credit OUT Other Flip-StorageExpenses 214 80d6 Cost CloseByDivision False Debit Credit OUT Other Flip-MembershipFees 215 80d7 Cost CloseByDivision False Debit Credit OUT Other Flip-IncomeSummary 216 80d8 Assets NoClose False Debit Credit PS Other Nothing-SuspenseAccount 217 80d9 Assets CloseByDivision False Debit Credit PS Current Nothing-ForeignExchangeGains 218 80da Revenue CloseByDivision False Credit Debit IN Other Keep-ForeignExchangeLosses 219 80db Cost CloseByDivision False Debit Credit OUT Other Flip-ContraAccountForGuaranteeObligations 220 80dc Assets CloseByDivision False Debit Credit PS Other Nothing-GuaranteeObligations 221 80dd Liability CloseByDivision False Credit Debit MS Other Nothing-IncomeTaxesAdjustment 222 80de Cost CloseByDivision False Debit Credit OUT Other Flip-BranchCurrentAccount 223 80df Assets CloseByDivision False Debit Credit PS Other Nothing-HeadOfficeCurrentAccount 224 80e0 Liability CloseByDivision False Credit Debit MS Other Nothing-NetIncomeAttributableToNCI 225 80e1 Cost NoClose False Debit Credit OUT Other Nothing-NetLossAttributableToNCI 226 80e2 Revenue NoClose False Credit Debit IN Other Nothing-TradingSecurities 227 80e3 Assets CloseByDivision False Debit Credit PS Current Nothing-HeldToMaturityBonds 228 80e4 Assets CloseByDivision False Debit Credit PS Fixed Nothing-SubsidiaryStocks 229 80e5 Assets CloseByDivision False Debit Credit PS Fixed Nothing-AffiliateStocks 230 80e6 Assets CloseByDivision False Debit Credit PS Fixed Nothing-AvailableForSaleSecurities 231 80e7 Assets CloseByDivision False Debit Credit PS Fixed Nothing-ConsumptionTaxRefundReceivable 232 80e8 Assets CloseByDivision False Debit Credit PS Current Nothing-PropertyTaxPayable 233 80e9 Liability CloseByDivision False Credit Debit MS Current Nothing-DepositsReceivedFromOfficers 234 80ea Liability CloseByDivision False Credit Debit MS Current Nothing-EntertainmentExpenses 235 80eb Cost CloseByDivision False Debit Credit OUT Other Flip-MeetingExpenses 236 80ec Cost CloseByDivision False Debit Credit OUT Other Flip-NewspaperBooksExpenses 237 80ed Cost CloseByDivision False Debit Credit OUT Other Flip-RawMaterials 238 80ee Assets CloseByDivision False Debit Credit PS Current Nothing-GoodsInTransit 239 80ef Assets CloseByDivision False Debit Credit PS Current Nothing-SalesAllowances 240 80f0 Revenue CloseByDivision True Debit Credit OUT Other Flip-PurchaseAllowances 241 80f1 Cost CloseByDivision True Credit Debit IN Other Keep-ReversalOfAllowanceForBonuses 242 80f2 Revenue CloseByDivision False Credit Debit IN Other Keep+# account-algebra-behavior semantics (title, binaryHex, division, closing, isContra, whichSide Not, whichSide Hat, whatPIMO, fixedCurrent, finalStockProbe); schema 1+Cash 8000 Assets CloseByDivision False Debit Credit PS Current Nothing+Deposits 8001 Assets CloseByDivision False Debit Credit PS Current Nothing+CurrentDeposits 8002 Assets CloseByDivision False Debit Credit PS Current Nothing+Securities 8003 Assets CloseByDivision False Debit Credit PS Current Nothing+InvestmentSecurities 8004 Assets CloseByDivision False Debit Credit PS Fixed Nothing+InvestmentInAssociate 8005 Assets CloseByDivision False Debit Credit PS Fixed Nothing+LongTermNationalBonds 8006 Assets CloseByDivision False Debit Credit PS Fixed Nothing+ShortTermNationalBonds 8007 Assets CloseByDivision False Debit Credit PS Current Nothing+Products 8008 Assets CloseByDivision False Debit Credit PS Current Nothing+Machinery 8009 Assets CloseByDivision False Debit Credit PS Fixed Nothing+Building 800a Assets CloseByDivision False Debit Credit PS Fixed Nothing+Vehicle 800b Assets CloseByDivision False Debit Credit PS Fixed Nothing+StockInvestment 800c Assets CloseByDivision False Debit Credit PS Other Nothing+EquipmentInvestment 800d Assets CloseByDivision False Debit Credit PS Fixed Nothing+LongTermLoansReceivable 800e Assets CloseByDivision False Debit Credit PS Fixed Nothing+AccountsReceivable 800f Assets CloseByDivision False Debit Credit PS Current Nothing+ShortTermLoansReceivable 8010 Assets CloseByDivision False Debit Credit PS Current Nothing+ReserveDepositReceivable 8011 Assets CloseByDivision False Debit Credit PS Current Nothing+Gold 8012 Assets CloseByDivision False Debit Credit PS Fixed Nothing+GovernmentService 8013 Assets CloseByDivision False Debit Credit PS Current Nothing+CapitalStock 8014 Equity CloseByDivision False Credit Debit MS Other Nothing+RetainedEarnings 8015 Equity CloseByDivision False Credit Debit MS Other SELF+LongTermLoansPayable 8016 Liability CloseByDivision False Credit Debit MS Fixed Nothing+ShortTermLoansPayable 8017 Liability CloseByDivision False Credit Debit MS Current Nothing+LoansPayable 8018 Liability CloseByDivision False Credit Debit MS Current Nothing+ReserveForDepreciation 8019 Liability CloseByDivision False Credit Debit MS Current Nothing+DepositPayable 801a Liability CloseByDivision False Credit Debit MS Current Nothing+LongTermNationalBondsPayable 801b Liability CloseByDivision False Credit Debit MS Fixed Nothing+ShortTermNationalBondsPayable 801c Liability CloseByDivision False Credit Debit MS Current Nothing+ReserveDepositPayable 801d Liability CloseByDivision False Credit Debit MS Current Nothing+CentralBankNotePayable 801e Liability CloseByDivision False Credit Debit MS Current Nothing+Depreciation 801f Cost CloseByDivision False Debit Credit OUT Other Flip+AmortizationExpense 8020 Cost CloseByDivision False Debit Credit OUT Other Flip+SalesCost 8021 Cost CloseByDivision False Debit Credit OUT Other Flip+BusinessTrip 8022 Cost CloseByDivision False Debit Credit OUT Other Flip+UtilitiesExpense 8024 Cost CloseByDivision False Debit Credit OUT Other Flip+RentExpense 8025 Cost CloseByDivision False Debit Credit OUT Other Flip+AdvertisingExpense 8026 Cost CloseByDivision False Debit Credit OUT Other Flip+DeliveryExpenses 8027 Cost CloseByDivision False Debit Credit OUT Other Flip+SuppliesExpenses 8028 Cost CloseByDivision False Debit Credit OUT Other Flip+MiscellaneousExpenses 8029 Cost CloseByDivision False Debit Credit OUT Other Flip+WageExpenditure 802a Cost CloseByDivision False Debit Credit OUT Other Flip+InterestExpense 802b Cost CloseByDivision False Debit Credit OUT Other Flip+TaxesExpense 802c Cost CloseByDivision False Debit Credit OUT Other Flip+ConsumptionExpenditure 802d Cost CloseByDivision False Debit Credit OUT Other Flip+SubsidyExpense 802e Cost CloseByDivision False Debit Credit OUT Other Flip+CentralBankPaymentExpense 802f Cost CloseByDivision False Debit Credit OUT Other Flip+Purchases 8030 Cost CloseByDivision False Debit Credit OUT Other Flip+NetIncome 8031 Cost NoClose False Debit Credit OUT Other Nothing+ValueAdded 8032 Revenue CloseByDivision False Credit Debit IN Other Keep+SubsidyIncome 8033 Revenue CloseByDivision False Credit Debit IN Other Keep+NationalBondInterestEarned 8034 Revenue CloseByDivision False Credit Debit IN Other Keep+DepositInterestEarned 8035 Revenue CloseByDivision False Credit Debit IN Other Keep+GrossProfit 8036 Revenue CloseByDivision False Credit Debit IN Other Keep+OrdinaryProfit 8037 Revenue CloseByDivision False Credit Debit IN Other Keep+InterestEarned 8038 Revenue CloseByDivision False Credit Debit IN Other Keep+ReceiptFee 8039 Revenue CloseByDivision False Credit Debit IN Other Keep+RentalIncome 803a Revenue CloseByDivision False Credit Debit IN Other Keep+WageEarned 803b Revenue CloseByDivision False Credit Debit IN Other Keep+TaxesRevenue 803c Revenue CloseByDivision False Credit Debit IN Other Keep+CentralBankPaymentIncome 803d Revenue CloseByDivision False Credit Debit IN Other Keep+Sales 803e Revenue CloseByDivision False Credit Debit IN Other Keep+EquityInEarningsOfInvestee 803f Revenue CloseByDivision False Credit Debit IN Other Keep+NetLoss 8040 Revenue NoClose False Credit Debit IN Other Nothing+PettyCash 8041 Assets CloseByDivision False Debit Credit PS Current Nothing+NotesReceivable 8042 Assets CloseByDivision False Debit Credit PS Current Nothing+ElectronicallyRecordedReceivable 8043 Assets CloseByDivision False Debit Credit PS Current Nothing+CreditCardReceivable 8044 Assets CloseByDivision False Debit Credit PS Current Nothing+NotesLoansReceivable 8045 Assets CloseByDivision False Debit Credit PS Current Nothing+MerchandiseInventory 8046 Assets CloseByDivision False Debit Credit PS Current Nothing+AdvancesPaid 8047 Assets CloseByDivision False Debit Credit PS Current Nothing+PrepaidExpenses 8048 Assets CloseByDivision False Debit Credit PS Current Nothing+AccruedRevenue 8049 Assets CloseByDivision False Debit Credit PS Current Nothing+OtherReceivables 804a Assets CloseByDivision False Debit Credit PS Current Nothing+PaymentsOnBehalf 804b Assets CloseByDivision False Debit Credit PS Current Nothing+SuspensePayments 804c Assets CloseByDivision False Debit Credit PS Current Nothing+ConsumptionTaxPaid 804d Assets CloseByDivision False Debit Credit PS Current Nothing+PrepaidCorporateIncomeTaxes 804e Assets CloseByDivision False Debit Credit PS Current Nothing+Land 804f Assets CloseByDivision False Debit Credit PS Fixed Nothing+Fixtures 8050 Assets CloseByDivision False Debit Credit PS Fixed Nothing+Patent 8051 Assets CloseByDivision False Debit Credit PS Fixed Nothing+Trademark 8052 Assets CloseByDivision False Debit Credit PS Fixed Nothing+Software 8053 Assets CloseByDivision False Debit Credit PS Fixed Nothing+CashOverShort 8054 Assets CloseByDivision False Debit Credit PS Other Nothing+AccountsPayable 8055 Liability CloseByDivision False Credit Debit MS Current Nothing+NotesPayable 8056 Liability CloseByDivision False Credit Debit MS Current Nothing+ElectronicallyRecordedObligations 8057 Liability CloseByDivision False Credit Debit MS Current Nothing+NotesLoansPayable 8058 Liability CloseByDivision False Credit Debit MS Current Nothing+BankOverdraft 8059 Liability CloseByDivision False Credit Debit MS Current Nothing+AdvancesReceived 805a Liability CloseByDivision False Credit Debit MS Current Nothing+UnearnedRevenue 805b Liability CloseByDivision False Credit Debit MS Current Nothing+AccruedExpenses 805c Liability CloseByDivision False Credit Debit MS Current Nothing+OtherPayables 805d Liability CloseByDivision False Credit Debit MS Current Nothing+DepositsReceived 805e Liability CloseByDivision False Credit Debit MS Current Nothing+SuspenseReceipts 805f Liability CloseByDivision False Credit Debit MS Current Nothing+ConsumptionTaxReceived 8060 Liability CloseByDivision False Credit Debit MS Current Nothing+AccruedConsumptionTax 8061 Liability CloseByDivision False Credit Debit MS Current Nothing+AccruedCorporateIncomeTaxes 8062 Liability CloseByDivision False Credit Debit MS Current Nothing+UnpaidDividends 8063 Liability CloseByDivision False Credit Debit MS Current Nothing+AllowanceForDoubtfulAccounts 8064 Assets CloseByDivision True Credit Debit MS Current Nothing+AccumulatedDepreciation 8065 Assets CloseByDivision True Credit Debit MS Fixed Nothing+LegalRetainedEarnings 8066 Equity CloseByDivision False Credit Debit MS Other Nothing+CumulativeTranslationAdjustment 8067 Equity CloseByDivision False Credit Debit MS Other Nothing+ProvisionForDoubtfulAccounts 8068 Cost CloseByDivision False Debit Credit OUT Other Flip+BadDebtLoss 8069 Cost CloseByDivision False Debit Credit OUT Other Flip+LossOnSalesOfFixedAssets 806a Cost CloseByDivision False Debit Credit OUT Other Flip+LossOnSalesOfNotesReceivable 806b Cost CloseByDivision False Debit Credit OUT Other Flip+PaymentFees 806c Cost CloseByDivision False Debit Credit OUT Other Flip+MiscellaneousLoss 806d Cost CloseByDivision False Debit Credit OUT Other Flip+CorporateIncomeTaxes 806e Cost CloseByDivision False Debit Credit OUT Other Flip+CommunicationExpenses 806f Cost CloseByDivision False Debit Credit OUT Other Flip+GainOnSalesOfFixedAssets 8070 Revenue CloseByDivision False Credit Debit IN Other Keep+RecoveryOfBadDebts 8071 Revenue CloseByDivision False Credit Debit IN Other Keep+MiscellaneousIncome 8072 Revenue CloseByDivision False Credit Debit IN Other Keep+ReversalOfAllowanceForDoubtfulAccounts 8073 Revenue CloseByDivision False Credit Debit IN Other Keep+TimeDeposits 8074 Assets CloseByDivision False Debit Credit PS Current Nothing+LoansReceivable 8075 Assets CloseByDivision False Debit Credit PS Current Nothing+GiftCertificatesReceived 8076 Assets CloseByDivision False Debit Credit PS Current Nothing+SecurityDepositsPaid 8077 Assets CloseByDivision False Debit Credit PS Fixed Nothing+SuppliesOnHand 8078 Assets CloseByDivision False Debit Credit PS Current Nothing+ContractAssets 8079 Assets CloseByDivision False Debit Credit PS Current Nothing+IncomeTaxesRefundReceivable 807a Assets CloseByDivision False Debit Credit PS Current Nothing+WorkInProcess 807b Assets CloseByDivision False Debit Credit PS Current Nothing+DeferredTaxAssets 807c Assets CloseByDivision False Debit Credit PS Fixed Nothing+LeasedAssets 807d Assets CloseByDivision False Debit Credit PS Fixed Nothing+ToolsAndInstruments 807e Assets CloseByDivision False Debit Credit PS Fixed Nothing+ConstructionInProgress 807f Assets CloseByDivision False Debit Credit PS Fixed Nothing+Goodwill 8080 Assets CloseByDivision False Debit Credit PS Fixed Nothing+SoftwareInProgress 8081 Assets CloseByDivision False Debit Credit PS Fixed Nothing+LongTermPrepaidExpenses 8082 Assets CloseByDivision False Debit Credit PS Fixed Nothing+DishonoredNotesReceivable 8083 Assets CloseByDivision False Debit Credit PS Current Nothing+PrepaidPensionCost 8084 Assets CloseByDivision False Debit Credit PS Fixed Nothing+NetDefinedBenefitAsset 8085 Assets CloseByDivision False Debit Credit PS Fixed Nothing+DepositsInSpecialAccounts 8086 Assets CloseByDivision False Debit Credit PS Current Nothing+Structures 8087 Assets CloseByDivision False Debit Credit PS Fixed Nothing+LeaseholdRights 8088 Assets CloseByDivision False Debit Credit PS Fixed Nothing+NonOperatingNotesReceivable 8089 Assets CloseByDivision False Debit Credit PS Current Nothing+NonOperatingElectronicallyRecordedReceivable 808a Assets CloseByDivision False Debit Credit PS Current Nothing+RefundLiabilities 808b Liability CloseByDivision False Credit Debit MS Current Nothing+NonOperatingNotesPayable 808c Liability CloseByDivision False Credit Debit MS Current Nothing+NonOperatingElectronicallyRecordedObligations 808d Liability CloseByDivision False Credit Debit MS Current Nothing+BonusesPayable 808e Liability CloseByDivision False Credit Debit MS Current Nothing+AllowanceForRepairs 808f Liability CloseByDivision False Credit Debit MS Current Nothing+AllowanceForProductWarranties 8090 Liability CloseByDivision False Credit Debit MS Current Nothing+AllowanceForBonuses 8091 Liability CloseByDivision False Credit Debit MS Current Nothing+DeferredTaxLiabilities 8092 Liability CloseByDivision False Credit Debit MS Fixed Nothing+LeaseObligations 8093 Liability CloseByDivision False Credit Debit MS Fixed Nothing+GuaranteeDepositsReceived 8094 Liability CloseByDivision False Credit Debit MS Fixed Nothing+AllowanceForRetirementBenefits 8095 Liability CloseByDivision False Credit Debit MS Fixed Nothing+LongTermOtherPayables 8096 Liability CloseByDivision False Credit Debit MS Fixed Nothing+NetDefinedBenefitLiability 8097 Liability CloseByDivision False Credit Debit MS Fixed Nothing+StockSubscriptionDeposits 8098 Equity CloseByDivision False Credit Debit MS Other Nothing+LegalCapitalSurplus 8099 Equity CloseByDivision False Credit Debit MS Other Nothing+OtherCapitalSurplus 809a Equity CloseByDivision False Credit Debit MS Other Nothing+DividendEqualizationReserve 809b Equity CloseByDivision False Credit Debit MS Other Nothing+RepairFundReserve 809c Equity CloseByDivision False Credit Debit MS Other Nothing+ConstructionFundReserve 809d Equity CloseByDivision False Credit Debit MS Other Nothing+GeneralReserve 809e Equity CloseByDivision False Credit Debit MS Other Nothing+ValuationDifferenceOnOtherSecurities 809f Equity CloseByDivision False Credit Debit MS Other Nothing+NonControllingInterests 80a0 Equity CloseByDivision False Credit Debit MS Other Nothing+CapitalSurplus 80a1 Equity CloseByDivision False Credit Debit MS Other Nothing+EarnedSurplus 80a2 Equity CloseByDivision False Credit Debit MS Other Nothing+ServiceRevenue 80a3 Revenue CloseByDivision False Credit Debit IN Other Keep+OperatingRevenue 80a4 Revenue CloseByDivision False Credit Debit IN Other Keep+GainOnSalesOfSecurities 80a5 Revenue CloseByDivision False Credit Debit IN Other Keep+GainOnValuationOfSecurities 80a6 Revenue CloseByDivision False Credit Debit IN Other Keep+DividendsReceived 80a7 Revenue CloseByDivision False Credit Debit IN Other Keep+InterestOnSecurities 80a8 Revenue CloseByDivision False Credit Debit IN Other Keep+GainOnSalesOfInvestmentSecurities 80a9 Revenue CloseByDivision False Credit Debit IN Other Keep+InsuranceGain 80aa Revenue CloseByDivision False Credit Debit IN Other Keep+GainOnBargainPurchase 80ab Revenue CloseByDivision False Credit Debit IN Other Keep+ReversalOfAllowanceForRepairs 80ac Revenue CloseByDivision False Credit Debit IN Other Keep+ReversalOfAllowanceForProductWarranties 80ad Revenue CloseByDivision False Credit Debit IN Other Keep+GainOnDonationOfFixedAssets 80ae Revenue CloseByDivision False Credit Debit IN Other Keep+GainOnNationalSubsidies 80af Revenue CloseByDivision False Credit Debit IN Other Keep+GainOnConstructionGrants 80b0 Revenue CloseByDivision False Credit Debit IN Other Keep+LandRentReceived 80b1 Revenue CloseByDivision False Credit Debit IN Other Keep+SalesRebates 80b2 Revenue CloseByDivision True Debit Credit OUT Other Flip+CostOfServices 80b3 Cost CloseByDivision False Debit Credit OUT Other Flip+OperatingExpenses 80b4 Cost CloseByDivision False Debit Credit OUT Other Flip+InventoryShrinkageLoss 80b5 Cost CloseByDivision False Debit Credit OUT Other Flip+LossOnValuationOfMerchandise 80b6 Cost CloseByDivision False Debit Credit OUT Other Flip+Bonuses 80b7 Cost CloseByDivision False Debit Credit OUT Other Flip+RetirementBenefitExpenses 80b8 Cost CloseByDivision False Debit Credit OUT Other Flip+ProvisionForRepairs 80b9 Cost CloseByDivision False Debit Credit OUT Other Flip+ProvisionForBonuses 80ba Cost CloseByDivision False Debit Credit OUT Other Flip+ProvisionForProductWarranties 80bb Cost CloseByDivision False Debit Credit OUT Other Flip+ResearchAndDevelopmentExpenses 80bc Cost CloseByDivision False Debit Credit OUT Other Flip+AmortizationOfGoodwill 80bd Cost CloseByDivision False Debit Credit OUT Other Flip+AmortizationOfSoftware 80be Cost CloseByDivision False Debit Credit OUT Other Flip+AmortizationOfPatents 80bf Cost CloseByDivision False Debit Credit OUT Other Flip+LeaseExpenses 80c0 Cost CloseByDivision False Debit Credit OUT Other Flip+IncorporationExpenses 80c1 Cost CloseByDivision False Debit Credit OUT Other Flip+StockIssuanceCosts 80c2 Cost CloseByDivision False Debit Credit OUT Other Flip+BusinessCommencementExpenses 80c3 Cost CloseByDivision False Debit Credit OUT Other Flip+DevelopmentExpenses 80c4 Cost CloseByDivision False Debit Credit OUT Other Flip+LossOnSalesOfElectronicallyRecordedReceivables 80c5 Cost CloseByDivision False Debit Credit OUT Other Flip+LossOnSalesOfReceivables 80c6 Cost CloseByDivision False Debit Credit OUT Other Flip+LossOnSalesOfSecurities 80c7 Cost CloseByDivision False Debit Credit OUT Other Flip+LossOnValuationOfSecurities 80c8 Cost CloseByDivision False Debit Credit OUT Other Flip+LossOnSalesOfInvestmentSecurities 80c9 Cost CloseByDivision False Debit Credit OUT Other Flip+LossOnFire 80ca Cost CloseByDivision False Debit Credit OUT Other Flip+LossOnRetirementOfFixedAssets 80cb Cost CloseByDivision False Debit Credit OUT Other Flip+LossOnReductionOfFixedAssets 80cc Cost CloseByDivision False Debit Credit OUT Other Flip+AdditionalIncomeTaxesForPriorPeriods 80cd Cost CloseByDivision False Debit Credit OUT Other Flip+RefundOfIncomeTaxes 80ce Cost CloseByDivision True Credit Debit IN Other Keep+PurchaseRebates 80cf Cost CloseByDivision True Credit Debit IN Other Keep+WelfareExpenses 80d0 Cost CloseByDivision False Debit Credit OUT Other Flip+MaintenanceExpenses 80d1 Cost CloseByDivision False Debit Credit OUT Other Flip+StatutoryWelfareExpenses 80d2 Cost CloseByDivision False Debit Credit OUT Other Flip+LandRentPaid 80d3 Cost CloseByDivision False Debit Credit OUT Other Flip+InsuranceExpense 80d4 Cost CloseByDivision False Debit Credit OUT Other Flip+RepairsExpense 80d5 Cost CloseByDivision False Debit Credit OUT Other Flip+StorageExpenses 80d6 Cost CloseByDivision False Debit Credit OUT Other Flip+MembershipFees 80d7 Cost CloseByDivision False Debit Credit OUT Other Flip+IncomeSummary 80d8 Assets NoClose False Debit Credit PS Other Nothing+SuspenseAccount 80d9 Assets CloseByDivision False Debit Credit PS Current Nothing+ForeignExchangeGains 80da Revenue CloseByDivision False Credit Debit IN Other Keep+ForeignExchangeLosses 80db Cost CloseByDivision False Debit Credit OUT Other Flip+ContraAccountForGuaranteeObligations 80dc Assets CloseByDivision False Debit Credit PS Other Nothing+GuaranteeObligations 80dd Liability CloseByDivision False Credit Debit MS Other Nothing+IncomeTaxesAdjustment 80de Cost CloseByDivision False Debit Credit OUT Other Flip+BranchCurrentAccount 80df Assets CloseByDivision False Debit Credit PS Other Nothing+HeadOfficeCurrentAccount 80e0 Liability CloseByDivision False Credit Debit MS Other Nothing+NetIncomeAttributableToNCI 80e1 Cost NoClose False Debit Credit OUT Other Nothing+NetLossAttributableToNCI 80e2 Revenue NoClose False Credit Debit IN Other Nothing+TradingSecurities 80e3 Assets CloseByDivision False Debit Credit PS Current Nothing+HeldToMaturityBonds 80e4 Assets CloseByDivision False Debit Credit PS Fixed Nothing+SubsidiaryStocks 80e5 Assets CloseByDivision False Debit Credit PS Fixed Nothing+AffiliateStocks 80e6 Assets CloseByDivision False Debit Credit PS Fixed Nothing+AvailableForSaleSecurities 80e7 Assets CloseByDivision False Debit Credit PS Fixed Nothing+ConsumptionTaxRefundReceivable 80e8 Assets CloseByDivision False Debit Credit PS Current Nothing+PropertyTaxPayable 80e9 Liability CloseByDivision False Credit Debit MS Current Nothing+DepositsReceivedFromOfficers 80ea Liability CloseByDivision False Credit Debit MS Current Nothing+EntertainmentExpenses 80eb Cost CloseByDivision False Debit Credit OUT Other Flip+MeetingExpenses 80ec Cost CloseByDivision False Debit Credit OUT Other Flip+NewspaperBooksExpenses 80ed Cost CloseByDivision False Debit Credit OUT Other Flip+RawMaterials 80ee Assets CloseByDivision False Debit Credit PS Current Nothing+GoodsInTransit 80ef Assets CloseByDivision False Debit Credit PS Current Nothing+SalesAllowances 80f0 Revenue CloseByDivision True Debit Credit OUT Other Flip+PurchaseAllowances 80f1 Cost CloseByDivision True Credit Debit IN Other Keep+ReversalOfAllowanceForBonuses 80f2 Revenue CloseByDivision False Credit Debit IN Other Keep+DirectorsCompensations 80f3 Cost CloseByDivision False Debit Credit OUT Other Flip
test/fixtures/account-semantics-050/account-info.tsv view
@@ -9,7 +9,7 @@ ShortTermNationalBonds [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Short-term national bonds 短期国債 Asset: Short-term national bonds (短期国債) Products [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Products 商品 Asset: Products (商品)。分記法用。3 分法 (仕入/売上/繰越商品) では 'MerchandiseInventory' を使う Machinery [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Machinery and equipment 機械装置 Asset: Machinery and equipment (機械装置)-Building [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Real estate 建物 Asset: Real estate (建物)+Building [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Buildings 建物 Asset: Buildings (建物) Vehicle [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Vehicles 車両運搬具 Asset: Vehicles (車両運搬具) StockInvestment [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Stock investment 株式投資 Asset: Stock investment (株式投資) EquipmentInvestment [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Equipment investment 設備投資 Asset: Equipment investment (設備投資)@@ -20,7 +20,7 @@ Gold [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Gold 金 Asset: Gold (金) GovernmentService [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Government service 政府サービス Asset: Government service (政府サービス。SNA/マクロ系) CapitalStock [OrdinaryAccount] OrdinaryPosting StatementDivision Equity FixedHomeSide Credit StatementEligible Capital stock 資本金 Equity: Capital stock (資本金)-RetainedEarnings [OrdinaryAccount] OrdinaryPosting StatementDivision Equity FixedHomeSide Credit StatementEligible Retained earnings 繰越利益剰余金 Equity: Retained earnings (繰越利益剰余金)+RetainedEarnings [OrdinaryAccount] OrdinaryPosting StatementDivision Equity FixedHomeSide Credit StatementEligible Retained earnings brought forward 繰越利益剰余金 Equity: Retained earnings brought forward (繰越利益剰余金) LongTermLoansPayable [OrdinaryAccount] OrdinaryPosting StatementDivision Liability FixedHomeSide Credit StatementEligible Long-term loans payable 長期借入金 Liability: Long-term loans payable (長期借入金) ShortTermLoansPayable [OrdinaryAccount] OrdinaryPosting StatementDivision Liability FixedHomeSide Credit StatementEligible Short-term loans payable 短期借入金 Liability: Short-term loans payable (短期借入金) LoansPayable [OrdinaryAccount] OrdinaryPosting StatementDivision Liability FixedHomeSide Credit StatementEligible Loans payable 借入金 Liability: Loans payable (借入金)@@ -34,33 +34,32 @@ AmortizationExpense [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Amortization expense for intangibles 無形固定資産償却費 Expense: Amortization expense for intangibles (無形固定資産償却費 — 特許権・商標権・ソフトウェア等の無形資産の償却費。有形の 'Depreciation' (減価償却費) と区別される) SalesCost [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Cost of sales 売上原価 Expense: Cost of sales (売上原価) BusinessTrip [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Travel and transportation 旅費交通費 Expense: Travel and transportation (旅費交通費)-Commutation [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Communication 通信費 Expense: Communication (通信費 — 旧称。新規コードでは 'CommunicationExpenses' を使う) UtilitiesExpense [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Utilities 水道光熱費 Expense: Utilities (水道光熱費) RentExpense [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Rent 支払家賃 Expense: Rent (支払家賃) AdvertisingExpense [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Advertising 広告宣伝費 Expense: Advertising (広告宣伝費) DeliveryExpenses [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Delivery 発送費 Expense: Delivery (発送費)-SuppliesExpenses [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Supplies 消耗品費 Expense: Supplies (消耗品費)+SuppliesExpenses [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Supplies expense 消耗品費 Expense: Supplies expense (消耗品費) MiscellaneousExpenses [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Miscellaneous 雑費 Expense: Miscellaneous (雑費) WageExpenditure [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Wages 給料 Expense: Wages (給料) InterestExpense [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Interest expense 支払利息 Expense: Interest expense (支払利息) TaxesExpense [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Taxes 租税公課 Expense: Taxes (租税公課) ConsumptionExpenditure [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Consumption expenditure 消費支出 Expense: Consumption expenditure (消費支出。SNA/マクロ系) SubsidyExpense [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Subsidy expenditure 補助金支出 Expense: Subsidy expenditure (補助金支出。SNA/マクロ系)-CentralBankPaymentExpense [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Central bank payment to treasury 国庫納付金支出 Expense: Central bank payment to treasury (国庫納付金支出。SNA/マクロ系)+CentralBankPaymentExpense [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Payment to national treasury 国庫納付金支出 Expense: Payment to national treasury (国庫納付金支出。SNA/マクロ系) Purchases [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Purchases 仕入 Expense: Purchases (仕入) NetIncome [PeriodResult] EngineGeneratedOnly DirectionEncoding Cost FixedHomeSide Debit DerivedPresentation Net income 当期純利益 Period result: net income (当期純利益). Engine-generated only; the legacy Cost value is an internal direction encoding, not an expense classification. ValueAdded [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Value added 付加価値 Revenue: Value added (付加価値。SNA/マクロ系) SubsidyIncome [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Subsidy income 補助金収入 Revenue: Subsidy income (補助金収入。SNA/マクロ系) NationalBondInterestEarned [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible National bond interest earned 国債利息収入 Revenue: National bond interest earned (国債利息収入) DepositInterestEarned [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Deposit interest earned 預金利息収入 Revenue: Deposit interest earned (預金利息収入)-GrossProfit [ReportingSubtotal] EngineGeneratedOnly DirectionEncoding Revenue FixedHomeSide Credit DerivedPresentation Gross profit 売上総利益 Legacy engine coordinate: gross profit (売上総利益). Engine-generated only; the legacy Revenue value is an internal direction encoding, not a statement subtotal definition.-OrdinaryProfit [ReportingSubtotal] EngineGeneratedOnly DirectionEncoding Revenue FixedHomeSide Credit DerivedPresentation Ordinary profit 経常利益 Legacy engine coordinate: ordinary profit (経常利益). Engine-generated only; the legacy Revenue value is an internal direction encoding, not a statement subtotal definition.+GrossProfit [ReportingSubtotal] EngineGeneratedOnly DirectionEncoding Revenue FixedHomeSide Credit DerivedPresentation Gross profit 売上総利益 Period subtotal: gross profit (売上総利益). Engine-generated only; the legacy Revenue value is an internal direction encoding, not a statement subtotal definition.+OrdinaryProfit [ReportingSubtotal] EngineGeneratedOnly DirectionEncoding Revenue FixedHomeSide Credit DerivedPresentation Ordinary profit 経常利益 Period subtotal: ordinary profit (経常利益). Engine-generated only; the legacy Revenue value is an internal direction encoding, not a statement subtotal definition. InterestEarned [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Interest earned 受取利息 Revenue: Interest earned (受取利息) ReceiptFee [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Receipt fee 受取手数料 Revenue: Receipt fee (受取手数料。支払側は 'PaymentFees') RentalIncome [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Rental income 受取家賃 Revenue: Rental income (受取家賃) WageEarned [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Wage income 賃金収入 Revenue: Wage income (賃金収入。SNA/マクロ系) TaxesRevenue [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Tax revenue 租税収入 Revenue: Tax revenue (租税収入。SNA/マクロ系)-CentralBankPaymentIncome [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Central bank payment to treasury 国庫納付金収入 Revenue: Central bank payment to treasury (国庫納付金収入。SNA/マクロ系)+CentralBankPaymentIncome [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Central bank payment received 国庫納付金収入 Revenue: Central bank payment received (国庫納付金収入。SNA/マクロ系) Sales [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Sales 売上 Revenue: Sales (売上) EquityInEarningsOfInvestee [OrdinaryAccount] ConsolidationOnly StatementDivision Revenue FixedHomeSide Credit ContextualPresentation Equity in earnings of investee 持分法による投資利益 Consolidation result: equity in earnings of investee (持分法による投資利益). Available only in consolidation worksheets. NetLoss [PeriodResult] EngineGeneratedOnly DirectionEncoding Revenue FixedHomeSide Credit DerivedPresentation Net loss 当期純損失 Period result: net loss (当期純損失). Engine-generated only; the legacy Revenue value is an internal direction encoding, not a revenue classification.@@ -110,7 +109,7 @@ PaymentFees [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Payment fees / fees paid 支払手数料 Expense: Payment fees / fees paid (支払手数料), the debit counterpart of 'ReceiptFee' MiscellaneousLoss [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Miscellaneous loss 雑損 Expense: Miscellaneous loss (雑損) CorporateIncomeTaxes [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Corporate income taxes 法人税等 Expense: Corporate income taxes (法人税等)-CommunicationExpenses [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Communication expenses 通信費 Expense: Communication expenses (通信費). Explicitly named counterpart of the legacy 'Commutation' (also "Communication"); 'Commutation' is retained for backward compatibility.+CommunicationExpenses [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Communication expenses 通信費 Expense: Communication expenses (通信費) GainOnSalesOfFixedAssets [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Gain on sales of fixed assets 固定資産売却益 Revenue: Gain on sales of fixed assets (固定資産売却益) RecoveryOfBadDebts [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Recovery of bad debts written off 償却債権取立益 Revenue: Recovery of bad debts written off (償却債権取立益) MiscellaneousIncome [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Miscellaneous income 雑益 Revenue: Miscellaneous income (雑益)@@ -119,7 +118,7 @@ LoansReceivable [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Loans receivable 貸付金 Asset: Loans receivable (貸付金) GiftCertificatesReceived [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Gift certificates received 受取商品券 Asset: Gift certificates received (受取商品券) SecurityDepositsPaid [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Guarantee deposits 差入保証金 Asset: Guarantee deposits (差入保証金)-SuppliesOnHand [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Supplies 貯蔵品 Asset: Supplies (貯蔵品)+SuppliesOnHand [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Supplies on hand 貯蔵品 Asset: Supplies on hand (貯蔵品) ContractAssets [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Contract assets 契約資産 Asset: Contract assets (契約資産) IncomeTaxesRefundReceivable [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Income taxes refund receivable 未収還付法人税等 Asset: Income taxes refund receivable (未収還付法人税等) WorkInProcess [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Work in process 仕掛品 Asset: Work in process (仕掛品)@@ -142,9 +141,9 @@ NonOperatingNotesPayable [OrdinaryAccount] OrdinaryPosting StatementDivision Liability FixedHomeSide Credit StatementEligible Non-operating notes payable 営業外支払手形 Liability: Non-operating notes payable (営業外支払手形) NonOperatingElectronicallyRecordedObligations [OrdinaryAccount] OrdinaryPosting StatementDivision Liability FixedHomeSide Credit StatementEligible Electronically recorded obligations - non-operating 営業外電子記録債務 Liability: Electronically recorded obligations - non-operating (営業外電子記録債務) BonusesPayable [OrdinaryAccount] OrdinaryPosting StatementDivision Liability FixedHomeSide Credit StatementEligible Accrued bonuses 未払賞与 Liability: Accrued bonuses (未払賞与)-AllowanceForRepairs [OrdinaryAccount] OrdinaryPosting StatementDivision Liability FixedHomeSide Credit StatementEligible Provision for repairs 修繕引当金 Liability: Provision for repairs (修繕引当金)-AllowanceForProductWarranties [OrdinaryAccount] OrdinaryPosting StatementDivision Liability FixedHomeSide Credit StatementEligible Provision for warranties 商品保証引当金 Liability: Provision for warranties (商品保証引当金)-AllowanceForBonuses [OrdinaryAccount] OrdinaryPosting StatementDivision Liability FixedHomeSide Credit StatementEligible Provision for bonuses 賞与引当金 Liability: Provision for bonuses (賞与引当金)+AllowanceForRepairs [OrdinaryAccount] OrdinaryPosting StatementDivision Liability FixedHomeSide Credit StatementEligible Allowance for repairs 修繕引当金 Liability: Allowance for repairs (修繕引当金)+AllowanceForProductWarranties [OrdinaryAccount] OrdinaryPosting StatementDivision Liability FixedHomeSide Credit StatementEligible Allowance for warranties 商品保証引当金 Liability: Allowance for warranties (商品保証引当金)+AllowanceForBonuses [OrdinaryAccount] OrdinaryPosting StatementDivision Liability FixedHomeSide Credit StatementEligible Allowance for bonuses 賞与引当金 Liability: Allowance for bonuses (賞与引当金) DeferredTaxLiabilities [OrdinaryAccount] OrdinaryPosting StatementDivision Liability FixedHomeSide Credit StatementEligible Deferred tax liabilities 繰延税金負債 Liability: Deferred tax liabilities (繰延税金負債) LeaseObligations [OrdinaryAccount] OrdinaryPosting StatementDivision Liability FixedHomeSide Credit StatementEligible Lease liabilities リース債務 Liability: Lease liabilities (リース債務) GuaranteeDepositsReceived [OrdinaryAccount] OrdinaryPosting StatementDivision Liability FixedHomeSide Credit StatementEligible Guarantee deposits received 預り保証金 Liability: Guarantee deposits received (預り保証金)@@ -171,8 +170,8 @@ GainOnSalesOfInvestmentSecurities [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Gain on sale of investment securities 投資有価証券売却益 Revenue: Gain on sale of investment securities (投資有価証券売却益) InsuranceGain [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Gain on insurance claims 保険差益 Revenue: Gain on insurance claims (保険差益) GainOnBargainPurchase [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Gain on bargain purchase 負ののれん発生益 Revenue: Gain on bargain purchase (負ののれん発生益)-ReversalOfAllowanceForRepairs [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Reversal of provision for repairs 修繕引当金戻入 Revenue: Reversal of provision for repairs (修繕引当金戻入)-ReversalOfAllowanceForProductWarranties [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Reversal of provision for warranties 商品保証引当金戻入 Revenue: Reversal of provision for warranties (商品保証引当金戻入)+ReversalOfAllowanceForRepairs [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Reversal of allowance for repairs 修繕引当金戻入 Revenue: Reversal of allowance for repairs (修繕引当金戻入)+ReversalOfAllowanceForProductWarranties [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Reversal of allowance for warranties 商品保証引当金戻入 Revenue: Reversal of allowance for warranties (商品保証引当金戻入) GainOnDonationOfFixedAssets [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Gain on receipt of donated non-current assets 固定資産受贈益 Revenue: Gain on receipt of donated non-current assets (固定資産受贈益) GainOnNationalSubsidies [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Gain on receipt of national subsidies 国庫補助金受贈益 Revenue: Gain on receipt of national subsidies (国庫補助金受贈益) GainOnConstructionGrants [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Gain on contribution received for construction 工事負担金受贈益 Revenue: Gain on contribution received for construction (工事負担金受贈益)@@ -241,4 +240,5 @@ GoodsInTransit [OrdinaryAccount] OrdinaryPosting StatementDivision Assets FixedHomeSide Debit StatementEligible Goods in transit 未着品 Asset: Goods in transit (未着品) SalesAllowances [OrdinaryAccount,ContraAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Debit StatementEligible Sales allowances 売上値引 Revenue: Sales allowances (売上値引) PurchaseAllowances [OrdinaryAccount,ContraAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Credit StatementEligible Purchase allowances 仕入値引 Expense: Purchase allowances (仕入値引)-ReversalOfAllowanceForBonuses [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Reversal of provision for bonuses 賞与引当金戻入 Revenue: Reversal of provision for bonuses (賞与引当金戻入)+ReversalOfAllowanceForBonuses [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible Reversal of allowance for bonuses 賞与引当金戻入 Revenue: Reversal of allowance for bonuses (賞与引当金戻入)+DirectorsCompensations [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible Remuneration for directors (and other officers) 役員報酬 Expense: Remuneration for directors (役員報酬)
test/fixtures/account-semantics-050/metadata.tsv view
@@ -34,7 +34,6 @@ AmortizationExpense [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible SalesCost [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible BusinessTrip [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible-Commutation [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible UtilitiesExpense [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible RentExpense [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible AdvertisingExpense [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible@@ -242,3 +241,4 @@ SalesAllowances [OrdinaryAccount,ContraAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Debit StatementEligible PurchaseAllowances [OrdinaryAccount,ContraAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Credit StatementEligible ReversalOfAllowanceForBonuses [OrdinaryAccount] OrdinaryPosting StatementDivision Revenue FixedHomeSide Credit StatementEligible+DirectorsCompensations [OrdinaryAccount] OrdinaryPosting StatementDivision Cost FixedHomeSide Debit StatementEligible
test/fixtures/account-semantics-050/suggest.tsv view
@@ -1,10 +1,7 @@ # account-semantics-050 Land 1 LLM suggestAccounts (query, total matches, top-10 titles); schema 1; base 09c8a60c0bfb1a7fedb01689ceee789b8b4e6084-"Communication"); 1 CommunicationExpenses 'AccountsPayable' 1 ReserveDepositPayable 'AccumulatedDepreciation' 1 ReserveForDepreciation 'AllowanceForDoubtfulAccounts' 1 ReversalOfAllowanceForDoubtfulAccounts-'CommunicationExpenses' 1 Commutation-'Commutation' 1 CommunicationExpenses 'DepositsReceived') 1 DepositPayable 'Depreciation' 1 AmortizationExpense 'MerchandiseInventory' 1 Products@@ -13,7 +10,6 @@ 'ReceiptFee' 1 PaymentFees 'ReserveForDepreciation' 1 AccumulatedDepreciation (3 1 MerchandiseInventory-(also 1 CommunicationExpenses (appropriated) 1 LegalRetainedEarnings (contra): 2 AllowanceForDoubtfulAccounts,AccumulatedDepreciation (isContra). 1 AccumulatedDepreciation@@ -126,6 +122,7 @@ (当期純損失). 1 NetLoss (役務原価) 1 CostOfServices (役務収益) 1 ServiceRevenue+(役員報酬) 1 DirectorsCompensations (役員預り金) 1 DepositsReceivedFromOfficers (手形借入金) 1 NotesLoansPayable (手形売却損) 1 LossOnSalesOfNotesReceivable@@ -242,8 +239,7 @@ (退職給付に係る資産) 1 NetDefinedBenefitAsset (退職給付引当金) 1 AllowanceForRetirementBenefits (退職給付費用) 1 RetirementBenefitExpenses-(通信費 2 Commutation,CommunicationExpenses-(通信費). 1 CommunicationExpenses+(通信費) 1 CommunicationExpenses (還付法人税等) 1 RefundOfIncomeTaxes (配当平均積立金) 1 DividendEqualizationReserve (金) 1 Gold@@ -281,7 +277,7 @@ Accrued (unpaid) consumption tax 21 AccruedConsumptionTax,AccruedCorporateIncomeTaxes,ConsumptionTaxPaid,ConsumptionTaxReceived,ConsumptionTaxRefundReceivable,TaxesExpense,ConsumptionExpenditure,TaxesRevenue,AccruedRevenue,PrepaidCorporateIncomeTaxes Accrued (unpaid) corporate income taxes 23 AccruedCorporateIncomeTaxes,PrepaidCorporateIncomeTaxes,CorporateIncomeTaxes,AccruedConsumptionTax,IncomeTaxesRefundReceivable,AdditionalIncomeTaxesForPriorPeriods,RefundOfIncomeTaxes,IncomeTaxesAdjustment,TaxesExpense,NetIncome Accrued bonuses 9 BonusesPayable,AccruedRevenue,AccruedExpenses,AccruedConsumptionTax,AccruedCorporateIncomeTaxes,AllowanceForBonuses,Bonuses,ProvisionForBonuses,ReversalOfAllowanceForBonuses-Accrued expenses 29 AccruedExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedRevenue,AccruedConsumptionTax,AccruedCorporateIncomeTaxes,CommunicationExpenses+Accrued expenses 28 AccruedExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedRevenue,AccruedConsumptionTax,AccruedCorporateIncomeTaxes,CommunicationExpenses,LongTermPrepaidExpenses Accrued revenue 44 AccruedRevenue,ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome AccruedConsumptionTax 1 AccruedConsumptionTax AccruedCorporateIncomeTaxes 1 AccruedCorporateIncomeTaxes@@ -291,25 +287,28 @@ Accumulated depreciation 4 ReserveForDepreciation,AccumulatedDepreciation,Depreciation,AmortizationExpense AccumulatedDepreciation 2 ReserveForDepreciation,AccumulatedDepreciation Additional 1 AdditionalIncomeTaxesForPriorPeriods-Additional income taxes for prior periods 50 AdditionalIncomeTaxesForPriorPeriods,PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,IncomeTaxesRefundReceivable,RefundOfIncomeTaxes,IncomeTaxesAdjustment,ReserveForDepreciation,AmortizationExpense,TaxesExpense+Additional income taxes for prior periods 51 AdditionalIncomeTaxesForPriorPeriods,PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,IncomeTaxesRefundReceivable,RefundOfIncomeTaxes,IncomeTaxesAdjustment,RetainedEarnings,ReserveForDepreciation,AmortizationExpense AdditionalIncomeTaxesForPriorPeriods 1 AdditionalIncomeTaxesForPriorPeriods Advances 2 AdvancesPaid,AdvancesReceived Advances paid 13 AdvancesPaid,PrepaidExpenses,ConsumptionTaxPaid,PrepaidCorporateIncomeTaxes,AdvancesReceived,AccruedConsumptionTax,AccruedCorporateIncomeTaxes,UnpaidDividends,PaymentFees,SecurityDepositsPaid-Advances received 11 AdvancesReceived,DepositPayable,AdvancesPaid,DepositsReceived,ConsumptionTaxReceived,GiftCertificatesReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants,LandRentReceived+Advances received 12 AdvancesReceived,DepositPayable,CentralBankPaymentIncome,AdvancesPaid,DepositsReceived,ConsumptionTaxReceived,GiftCertificatesReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants AdvancesPaid 1 AdvancesPaid AdvancesReceived 1 AdvancesReceived Advertising 1 AdvertisingExpense AdvertisingExpense 1 AdvertisingExpense AffiliateStocks 1 AffiliateStocks Allowance 11 AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,SalesAllowances,PurchaseAllowances-Allowance for doubtful accounts 39 AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses+Allowance for bonuses 37 AllowanceForBonuses,ReversalOfAllowanceForBonuses,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForBonuses+Allowance for doubtful accounts 40 AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses+Allowance for repairs 36 AllowanceForRepairs,ReversalOfAllowanceForRepairs,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,RepairFundReserve,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs+Allowance for warranties 35 AllowanceForProductWarranties,ReversalOfAllowanceForProductWarranties,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ProvisionForProductWarranties,ReversalOfAllowanceForBonuses AllowanceForBonuses 2 AllowanceForBonuses,ReversalOfAllowanceForBonuses AllowanceForDoubtfulAccounts 2 AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts AllowanceForProductWarranties 2 AllowanceForProductWarranties,ReversalOfAllowanceForProductWarranties AllowanceForRepairs 2 AllowanceForRepairs,ReversalOfAllowanceForRepairs AllowanceForRetirementBenefits 1 AllowanceForRetirementBenefits Amortization 4 AmortizationExpense,AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationOfPatents-Amortization expense for intangibles 97 AmortizationExpense,ProvisionForDoubtfulAccounts,CommunicationExpenses,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationOfPatents,AdditionalIncomeTaxesForPriorPeriods+Amortization expense for intangibles 98 AmortizationExpense,ProvisionForDoubtfulAccounts,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationOfPatents,AdditionalIncomeTaxesForPriorPeriods,ForeignExchangeLosses Amortization of goodwill 44 AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationOfPatents,AmortizationExpense,SalesCost,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee,MerchandiseInventory,Software Amortization of patent rights 45 AmortizationOfPatents,AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationExpense,SalesCost,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee,MerchandiseInventory,Patent Amortization of software 43 AmortizationOfSoftware,Software,SoftwareInProgress,AmortizationOfGoodwill,AmortizationOfPatents,AmortizationExpense,SalesCost,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee@@ -336,8 +335,9 @@ Branch current account 25 BranchCurrentAccount,HeadOfficeCurrentAccount,CurrentDeposits,AccountsReceivable,ReserveDepositPayable,MerchandiseInventory,PrepaidExpenses,AccruedRevenue,SuspensePayments,CashOverShort BranchCurrentAccount 1 BranchCurrentAccount Building 1 Building+Buildings 1 Building Business 2 BusinessTrip,BusinessCommencementExpenses-Business commencement expenses 26 BusinessCommencementExpenses,BusinessTrip,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses+Business commencement expenses 25 BusinessCommencementExpenses,BusinessTrip,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses BusinessCommencementExpenses 1 BusinessCommencementExpenses BusinessTrip 1 BusinessTrip Capital 4 CapitalStock,LegalCapitalSurplus,OtherCapitalSurplus,CapitalSurplus@@ -347,35 +347,34 @@ CapitalSurplus 3 LegalCapitalSurplus,OtherCapitalSurplus,CapitalSurplus Carrying 1 InvestmentInAssociate Cash 3 Cash,PettyCash,CashOverShort-Cash over and short 27 CashOverShort,Cash,ShortTermNationalBonds,Products,Machinery,ShortTermLoansReceivable,GovernmentService,ShortTermLoansPayable,ShortTermNationalBondsPayable,BusinessTrip+Cash over and short 28 CashOverShort,Cash,ShortTermNationalBonds,Products,Machinery,ShortTermLoansReceivable,GovernmentService,ShortTermLoansPayable,ShortTermNationalBondsPayable,BusinessTrip CashOverShort 1 CashOverShort Central 3 CentralBankNotePayable,CentralBankPaymentExpense,CentralBankPaymentIncome Central bank notes 12 CentralBankNotePayable,CentralBankPaymentExpense,CentralBankPaymentIncome,NotesReceivable,NotesLoansReceivable,NotesPayable,NotesLoansPayable,BankOverdraft,LossOnSalesOfNotesReceivable,DishonoredNotesReceivable-Central bank payment to treasury 28 CentralBankPaymentExpense,CentralBankPaymentIncome,CentralBankNotePayable,Products,StockInvestment,CapitalStock,GrossProfit,OrdinaryProfit,ReceiptFee,MerchandiseInventory+Central bank payment received 18 CentralBankPaymentIncome,CentralBankPaymentExpense,CentralBankNotePayable,DepositPayable,ReceiptFee,PaymentsOnBehalf,SuspensePayments,BankOverdraft,AdvancesReceived,DepositsReceived CentralBankNotePayable 1 CentralBankNotePayable CentralBankPaymentExpense 1 CentralBankPaymentExpense CentralBankPaymentIncome 1 CentralBankPaymentIncome Closing 2 CashOverShort,IncomeSummary-Communication 2 Commutation,CommunicationExpenses-Communication expenses 25 Commutation,CommunicationExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses-CommunicationExpenses 2 Commutation,CommunicationExpenses-Commutation 2 Commutation,CommunicationExpenses+Communication 1 CommunicationExpenses+Communication expenses 24 CommunicationExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses,ResearchAndDevelopmentExpenses+CommunicationExpenses 1 CommunicationExpenses Consolidation 4 EquityInEarningsOfInvestee,CumulativeTranslationAdjustment,NetIncomeAttributableToNCI,NetLossAttributableToNCI Construction 3 ConstructionInProgress,ConstructionFundReserve,GainOnConstructionGrants-Construction in progress 89 ConstructionInProgress,SoftwareInProgress,GainOnConstructionGrants,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment+Construction in progress 88 ConstructionInProgress,SoftwareInProgress,GainOnConstructionGrants,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment ConstructionFundReserve 1 ConstructionFundReserve ConstructionInProgress 1 ConstructionInProgress Consumption 5 ConsumptionExpenditure,ConsumptionTaxPaid,ConsumptionTaxReceived,AccruedConsumptionTax,ConsumptionTaxRefundReceivable Consumption expenditure 7 ConsumptionExpenditure,WageExpenditure,SubsidyExpense,ConsumptionTaxPaid,ConsumptionTaxReceived,AccruedConsumptionTax,ConsumptionTaxRefundReceivable Consumption tax paid 26 ConsumptionTaxPaid,AccruedConsumptionTax,PrepaidCorporateIncomeTaxes,ConsumptionTaxReceived,AccruedCorporateIncomeTaxes,ConsumptionTaxRefundReceivable,TaxesExpense,ConsumptionExpenditure,TaxesRevenue,AdvancesPaid-Consumption tax received 27 ConsumptionTaxReceived,ConsumptionTaxPaid,AccruedConsumptionTax,ConsumptionTaxRefundReceivable,DepositPayable,TaxesExpense,ConsumptionExpenditure,TaxesRevenue,PrepaidCorporateIncomeTaxes,AdvancesReceived+Consumption tax received 28 ConsumptionTaxReceived,ConsumptionTaxPaid,AccruedConsumptionTax,ConsumptionTaxRefundReceivable,DepositPayable,TaxesExpense,ConsumptionExpenditure,TaxesRevenue,CentralBankPaymentIncome,PrepaidCorporateIncomeTaxes Consumption tax refund receivable 36 ConsumptionTaxRefundReceivable,IncomeTaxesRefundReceivable,ConsumptionTaxPaid,ConsumptionTaxReceived,AccruedConsumptionTax,RefundOfIncomeTaxes,LongTermLoansReceivable,AccountsReceivable,ShortTermLoansReceivable,ReserveDepositReceivable ConsumptionExpenditure 1 ConsumptionExpenditure ConsumptionTaxPaid 1 ConsumptionTaxPaid ConsumptionTaxReceived 1 ConsumptionTaxReceived ConsumptionTaxRefundReceivable 1 ConsumptionTaxRefundReceivable Contra 4 AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ContractAssets,ContraAccountForGuaranteeObligations-Contra account for guarantee obligations 51 ContraAccountForGuaranteeObligations,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,MerchandiseInventory,SuspensePayments,SuspenseReceipts,ProvisionForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,SuspenseAccount,GuaranteeObligations+Contra account for guarantee obligations 52 ContraAccountForGuaranteeObligations,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,MerchandiseInventory,SuspensePayments,SuspenseReceipts,ProvisionForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,SuspenseAccount,GuaranteeObligations ContraAccountForGuaranteeObligations 1 ContraAccountForGuaranteeObligations Contract 1 ContractAssets Contract assets 12 ContractAssets,SuspensePayments,AccumulatedDepreciation,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,DeferredTaxAssets,LeasedAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets@@ -408,17 +407,18 @@ DepositPayable 2 DepositPayable,ReserveDepositPayable Deposits 12 Deposits,CurrentDeposits,ReserveDepositReceivable,DepositPayable,ReserveDepositPayable,DepositsReceived,TimeDeposits,SecurityDepositsPaid,DepositsInSpecialAccounts,GuaranteeDepositsReceived Deposits accepted 12 DepositPayable,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,DepositsReceived,TimeDeposits,SecurityDepositsPaid,DepositsInSpecialAccounts,GuaranteeDepositsReceived-Deposits for subscriptions of shares 77 StockSubscriptionDeposits,MerchandiseInventory,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,SubsidiaryStocks,AffiliateStocks,DepositsReceivedFromOfficers,ReversalOfAllowanceForBonuses-Deposits in special accounts 102 DepositsInSpecialAccounts,Deposits,ReserveDepositPayable,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,CurrentDeposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery-Deposits received 18 DepositPayable,DepositsReceived,GuaranteeDepositsReceived,DepositsReceivedFromOfficers,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,AdvancesReceived,ConsumptionTaxReceived-Deposits received from officers 20 DepositsReceivedFromOfficers,DepositPayable,DepositsReceived,GuaranteeDepositsReceived,LandRentReceived,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,AdvancesReceived+Deposits for subscriptions of shares 78 StockSubscriptionDeposits,MerchandiseInventory,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,SubsidiaryStocks,AffiliateStocks,DepositsReceivedFromOfficers,ReversalOfAllowanceForBonuses,DirectorsCompensations+Deposits in special accounts 101 DepositsInSpecialAccounts,Deposits,ReserveDepositPayable,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,CurrentDeposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery+Deposits received 19 DepositPayable,DepositsReceived,GuaranteeDepositsReceived,DepositsReceivedFromOfficers,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,CentralBankPaymentIncome,AdvancesReceived+Deposits received from officers 22 DepositsReceivedFromOfficers,DepositPayable,DepositsReceived,GuaranteeDepositsReceived,LandRentReceived,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,CentralBankPaymentIncome DepositsInSpecialAccounts 1 DepositsInSpecialAccounts DepositsReceived 4 DepositPayable,DepositsReceived,GuaranteeDepositsReceived,DepositsReceivedFromOfficers DepositsReceivedFromOfficers 1 DepositsReceivedFromOfficers Depreciation 4 ReserveForDepreciation,Depreciation,AmortizationExpense,AccumulatedDepreciation Development 2 ResearchAndDevelopmentExpenses,DevelopmentExpenses-Development expenses 25 ResearchAndDevelopmentExpenses,DevelopmentExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses+Development expenses 24 ResearchAndDevelopmentExpenses,DevelopmentExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses DevelopmentExpenses 2 ResearchAndDevelopmentExpenses,DevelopmentExpenses+DirectorsCompensations 1 DirectorsCompensations Dishonored 1 DishonoredNotesReceivable Dishonored notes receivable 23 DishonoredNotesReceivable,NotesReceivable,NotesLoansReceivable,LossOnSalesOfNotesReceivable,NonOperatingNotesReceivable,LongTermLoansReceivable,AccountsReceivable,ShortTermLoansReceivable,ReserveDepositReceivable,CentralBankNotePayable DishonoredNotesReceivable 1 DishonoredNotesReceivable@@ -436,35 +436,34 @@ ElectronicallyRecordedReceivable 3 ElectronicallyRecordedReceivable,NonOperatingElectronicallyRecordedReceivable,LossOnSalesOfElectronicallyRecordedReceivables Engine-generated 4 NetIncome,GrossProfit,OrdinaryProfit,NetLoss Entertainment 1 EntertainmentExpenses-Entertainment expenses 25 EntertainmentExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses+Entertainment expenses 24 EntertainmentExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses EntertainmentExpenses 1 EntertainmentExpenses Equipment 3 Machinery,EquipmentInvestment,Fixtures Equipment investment 8 EquipmentInvestment,InvestmentSecurities,InvestmentInAssociate,Machinery,StockInvestment,Fixtures,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities EquipmentInvestment 1 EquipmentInvestment-Equity in earnings of investee 121 EquityInEarningsOfInvestee,RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,InvestmentInAssociate,GrossProfit,OrdinaryProfit,MerchandiseInventory,CommunicationExpenses,GainOnSalesOfFixedAssets+Equity in earnings of investee 121 EquityInEarningsOfInvestee,RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,InvestmentInAssociate,GrossProfit,OrdinaryProfit,MerchandiseInventory,GainOnSalesOfFixedAssets,ReversalOfAllowanceForDoubtfulAccounts Equity: 14 CapitalStock,RetainedEarnings,LegalRetainedEarnings,StockSubscriptionDeposits,LegalCapitalSurplus,OtherCapitalSurplus,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve,GeneralReserve EquityInEarningsOfInvestee 1 EquityInEarningsOfInvestee ExchangeAlgebra.IO.Output 1 AllowanceForDoubtfulAccounts-Expense: 69 Depreciation,AmortizationExpense,SalesCost,BusinessTrip,Commutation,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses,SuppliesExpenses-Explicitly 1 CommunicationExpenses+Expense: 69 Depreciation,AmortizationExpense,SalesCost,BusinessTrip,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses Fixtures 1 Fixtures-Fixtures and equipment 19 Fixtures,Machinery,Products,EquipmentInvestment,BusinessTrip,MerchandiseInventory,Land,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand-For 32 ReserveForDepreciation,AmortizationExpense,MerchandiseInventory,SuspensePayments,SuspenseReceipts,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ProvisionForDoubtfulAccounts,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts+Fixtures and equipment 20 Fixtures,Machinery,Products,EquipmentInvestment,BusinessTrip,MerchandiseInventory,Land,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand+For 33 RetainedEarnings,ReserveForDepreciation,AmortizationExpense,MerchandiseInventory,SuspensePayments,SuspenseReceipts,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ProvisionForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts Foreign 2 ForeignExchangeGains,ForeignExchangeLosses Foreign exchange gains 3 ForeignExchangeGains,ForeignExchangeLosses,AllowanceForDoubtfulAccounts Foreign exchange losses 3 ForeignExchangeLosses,ForeignExchangeGains,AllowanceForDoubtfulAccounts ForeignExchangeGains 1 ForeignExchangeGains ForeignExchangeLosses 1 ForeignExchangeLosses Gain 11 MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,InsuranceGain,GainOnBargainPurchase,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,GainOnConstructionGrants-Gain on bargain purchase 102 GainOnBargainPurchase,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,InsuranceGain,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,GainOnConstructionGrants-Gain on contribution received for construction 111 GainOnConstructionGrants,MerchandiseInventory,ConstructionFundReserve,ReserveForDepreciation,AmortizationExpense,SuspensePayments,SuspenseReceipts,ConsumptionTaxReceived,AllowanceForDoubtfulAccounts,AccumulatedDepreciation-Gain on insurance claims 100 InsuranceGain,ElectronicallyRecordedReceivable,MerchandiseInventory,GainOnSalesOfFixedAssets,NonOperatingElectronicallyRecordedReceivable,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,GainOnBargainPurchase,GainOnDonationOfFixedAssets-Gain on receipt of donated non-current assets 115 GainOnDonationOfFixedAssets,GainOnSalesOfFixedAssets,GainOnNationalSubsidies,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,MerchandiseInventory,LossOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities-Gain on receipt of national subsidies 113 GainOnNationalSubsidies,GainOnDonationOfFixedAssets,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable-Gain on sale of investment securities 122 GainOnSalesOfInvestmentSecurities,GainOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnValuationOfSecurities,LossOnSalesOfSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities-Gain on sale of securities 119 GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnValuationOfSecurities,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities-Gain on sales of fixed assets 118 GainOnSalesOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,MerchandiseInventory,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnValuationOfSecurities-Gain on valuation of securities 116 GainOnValuationOfSecurities,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnValuationOfSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,ValuationDifferenceOnOtherSecurities,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,LossOnValuationOfMerchandise+Gain on bargain purchase 99 GainOnBargainPurchase,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,InsuranceGain,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,GainOnConstructionGrants+Gain on contribution received for construction 114 GainOnConstructionGrants,MerchandiseInventory,ConstructionFundReserve,ReserveForDepreciation,AmortizationExpense,SuspensePayments,SuspenseReceipts,ConsumptionTaxReceived,AllowanceForDoubtfulAccounts,AccumulatedDepreciation+Gain on insurance claims 97 InsuranceGain,ElectronicallyRecordedReceivable,MerchandiseInventory,GainOnSalesOfFixedAssets,NonOperatingElectronicallyRecordedReceivable,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,GainOnBargainPurchase,GainOnDonationOfFixedAssets+Gain on receipt of donated non-current assets 114 GainOnDonationOfFixedAssets,GainOnSalesOfFixedAssets,GainOnNationalSubsidies,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,MerchandiseInventory,LossOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities+Gain on receipt of national subsidies 112 GainOnNationalSubsidies,GainOnDonationOfFixedAssets,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable+Gain on sale of investment securities 121 GainOnSalesOfInvestmentSecurities,GainOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnValuationOfSecurities,LossOnSalesOfSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities+Gain on sale of securities 118 GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnValuationOfSecurities,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities+Gain on sales of fixed assets 117 GainOnSalesOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,MerchandiseInventory,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnValuationOfSecurities+Gain on valuation of securities 115 GainOnValuationOfSecurities,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnValuationOfSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,ValuationDifferenceOnOtherSecurities,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,LossOnValuationOfMerchandise GainOnBargainPurchase 1 GainOnBargainPurchase GainOnConstructionGrants 1 GainOnConstructionGrants GainOnDonationOfFixedAssets 1 GainOnDonationOfFixedAssets@@ -477,11 +476,11 @@ General reserve 9 GeneralReserve,ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,AccumulatedDepreciation,LegalRetainedEarnings,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve GeneralReserve 1 GeneralReserve Gift 1 GiftCertificatesReceived-Gift certificates received 10 GiftCertificatesReceived,DepositPayable,AdvancesReceived,DepositsReceived,ConsumptionTaxReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants,LandRentReceived,DepositsReceivedFromOfficers+Gift certificates received 11 GiftCertificatesReceived,DepositPayable,CentralBankPaymentIncome,AdvancesReceived,DepositsReceived,ConsumptionTaxReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants,LandRentReceived GiftCertificatesReceived 1 GiftCertificatesReceived Gold 1 Gold Goods 3 MerchandiseInventory,LossOnValuationOfMerchandise,GoodsInTransit-Goods in transit 89 GoodsInTransit,MerchandiseInventory,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment+Goods in transit 88 GoodsInTransit,MerchandiseInventory,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment GoodsInTransit 1 GoodsInTransit Goodwill 2 Goodwill,AmortizationOfGoodwill Government 1 GovernmentService@@ -491,12 +490,12 @@ GrossProfit 1 GrossProfit Guarantee 4 SecurityDepositsPaid,GuaranteeDepositsReceived,ContraAccountForGuaranteeObligations,GuaranteeObligations Guarantee deposits 14 SecurityDepositsPaid,GuaranteeDepositsReceived,Deposits,CurrentDeposits,ReserveDepositReceivable,DepositPayable,ReserveDepositPayable,DepositsReceived,TimeDeposits,DepositsInSpecialAccounts-Guarantee deposits received 20 GuaranteeDepositsReceived,DepositPayable,DepositsReceived,SecurityDepositsPaid,DepositsReceivedFromOfficers,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,AdvancesReceived+Guarantee deposits received 21 GuaranteeDepositsReceived,DepositPayable,DepositsReceived,SecurityDepositsPaid,DepositsReceivedFromOfficers,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,CentralBankPaymentIncome Guarantee obligations 7 ContraAccountForGuaranteeObligations,GuaranteeObligations,ElectronicallyRecordedObligations,SecurityDepositsPaid,NonOperatingElectronicallyRecordedObligations,LeaseObligations,GuaranteeDepositsReceived GuaranteeDepositsReceived 1 GuaranteeDepositsReceived GuaranteeObligations 2 ContraAccountForGuaranteeObligations,GuaranteeObligations Hat/Not 1 AllowanceForDoubtfulAccounts-Head office current account 26 BranchCurrentAccount,HeadOfficeCurrentAccount,CurrentDeposits,AccountsReceivable,ReserveDepositPayable,MerchandiseInventory,PrepaidExpenses,AccruedRevenue,SuspensePayments,CashOverShort+Head office current account 27 BranchCurrentAccount,HeadOfficeCurrentAccount,CurrentDeposits,AccountsReceivable,ReserveDepositPayable,MerchandiseInventory,PrepaidExpenses,AccruedRevenue,SuspensePayments,CashOverShort HeadOfficeCurrentAccount 1 HeadOfficeCurrentAccount Held-to-maturity 1 HeldToMaturityBonds Held-to-maturity bonds 5 HeldToMaturityBonds,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable@@ -511,13 +510,13 @@ IncomeTaxesRefundReceivable 1 IncomeTaxesRefundReceivable IncorporationExpenses 1 IncorporationExpenses Insurance 2 InsuranceGain,InsuranceExpense-Insurance expenses 26 InsuranceExpense,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,InsuranceGain+Insurance expenses 25 InsuranceExpense,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,InsuranceGain,OperatingExpenses InsuranceExpense 1 InsuranceExpense InsuranceGain 1 InsuranceGain Interest 9 InterestExpense,NationalBondInterestEarned,DepositInterestEarned,InterestEarned,LeaseholdRights,NonControllingInterests,InterestOnSecurities,NetIncomeAttributableToNCI,NetLossAttributableToNCI Interest earned 12 NationalBondInterestEarned,DepositInterestEarned,InterestEarned,InterestExpense,WageEarned,UnearnedRevenue,LeaseholdRights,NonControllingInterests,EarnedSurplus,InterestOnSecurities-Interest expense 81 InterestExpense,Depreciation,AmortizationExpense,SalesCost,BusinessTrip,Commutation,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses-Interest on securities 106 InterestOnSecurities,NationalBondInterestEarned,ValuationDifferenceOnOtherSecurities,NonControllingInterests,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities+Interest expense 81 InterestExpense,Depreciation,AmortizationExpense,SalesCost,BusinessTrip,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses,SuppliesExpenses+Interest on securities 103 InterestOnSecurities,NationalBondInterestEarned,ValuationDifferenceOnOtherSecurities,NonControllingInterests,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities InterestEarned 3 NationalBondInterestEarned,DepositInterestEarned,InterestEarned InterestExpense 1 InterestExpense InterestOnSecurities 1 InterestOnSecurities@@ -525,17 +524,17 @@ Inventory shrinkage loss 19 InventoryShrinkageLoss,Products,NetLoss,MerchandiseInventory,BadDebtLoss,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,MiscellaneousLoss,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables InventoryShrinkageLoss 1 InventoryShrinkageLoss Investment 6 InvestmentSecurities,InvestmentInAssociate,StockInvestment,EquipmentInvestment,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities-Investment in associate 89 InvestmentInAssociate,InvestmentSecurities,StockInvestment,EquipmentInvestment,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities,Deposits,Products,Machinery,Building+Investment in associate 88 InvestmentInAssociate,InvestmentSecurities,StockInvestment,EquipmentInvestment,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities,Deposits,Products,Machinery,Building Investment securities 15 InvestmentSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities,Securities,InvestmentInAssociate,StockInvestment,EquipmentInvestment,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnValuationOfSecurities InvestmentInAssociate 1 InvestmentInAssociate InvestmentSecurities 3 InvestmentSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities-It 98 Deposits,CurrentDeposits,Securities,InvestmentSecurities,InvestmentInAssociate,ReserveDepositReceivable,CapitalStock,RetainedEarnings,LongTermLoansPayable,ShortTermLoansPayable+It 97 Deposits,CurrentDeposits,Securities,InvestmentSecurities,InvestmentInAssociate,ReserveDepositReceivable,CapitalStock,RetainedEarnings,LongTermLoansPayable,ShortTermLoansPayable Its 16 Deposits,CurrentDeposits,ReserveDepositReceivable,DepositPayable,ReserveDepositPayable,SuspensePayments,DepositsReceived,SuspenseReceipts,TimeDeposits,SecurityDepositsPaid Land 4 Land,LeaseholdRights,LandRentReceived,LandRentPaid LandRentPaid 1 LandRentPaid LandRentReceived 1 LandRentReceived Lease 5 ReversalOfAllowanceForDoubtfulAccounts,LeasedAssets,LeaseholdRights,LeaseObligations,LeaseExpenses-Lease expenses 29 LeaseExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts,LeasedAssets+Lease expenses 28 LeaseExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts,LeasedAssets,LongTermPrepaidExpenses Lease liabilities 7 LeaseObligations,ReversalOfAllowanceForDoubtfulAccounts,LeasedAssets,LeaseholdRights,RefundLiabilities,DeferredTaxLiabilities,LeaseExpenses LeaseExpenses 1 LeaseExpenses LeaseObligations 1 LeaseObligations@@ -543,31 +542,30 @@ Leased assets 13 LeasedAssets,SuspensePayments,AccumulatedDepreciation,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,ReversalOfAllowanceForDoubtfulAccounts,ContractAssets,DeferredTaxAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets LeasedAssets 1 LeasedAssets Leasehold 1 LeaseholdRights-Leasehold interests in land 90 LeaseholdRights,NonControllingInterests,LandRentReceived,NetIncomeAttributableToNCI,NetLossAttributableToNCI,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery+Leasehold interests in land 89 LeaseholdRights,NonControllingInterests,LandRentReceived,NetIncomeAttributableToNCI,NetLossAttributableToNCI,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery LeaseholdRights 1 LeaseholdRights-Legacy 12 NetIncome,GrossProfit,OrdinaryProfit,NetLoss,SuspensePayments,SuspenseReceipts,AccumulatedDepreciation,CommunicationExpenses,IncomeSummary,SuspenseAccount Legal 3 LegalRetainedEarnings,LegalCapitalSurplus,StatutoryWelfareExpenses-Legal (appropriated) retained earnings reserve 15 LegalRetainedEarnings,RetainedEarnings,AccumulatedDepreciation,EarnedSurplus,ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,EquityInEarningsOfInvestee,CommunicationExpenses,LegalCapitalSurplus+Legal (appropriated) retained earnings reserve 14 LegalRetainedEarnings,RetainedEarnings,AccumulatedDepreciation,EarnedSurplus,ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,EquityInEarningsOfInvestee,LegalCapitalSurplus,DividendEqualizationReserve Legal capital surplus 7 LegalCapitalSurplus,OtherCapitalSurplus,CapitalSurplus,CapitalStock,LegalRetainedEarnings,EarnedSurplus,StatutoryWelfareExpenses-Legal welfare expenses 27 StatutoryWelfareExpenses,WelfareExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,LegalRetainedEarnings,CommunicationExpenses+Legal welfare expenses 26 StatutoryWelfareExpenses,WelfareExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,LegalRetainedEarnings,CommunicationExpenses,LongTermPrepaidExpenses LegalCapitalSurplus 1 LegalCapitalSurplus LegalRetainedEarnings 1 LegalRetainedEarnings Liability 40 LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,ReserveForDepreciation,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,CentralBankNotePayable,AccountsPayable Liability: 39 LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,ReserveForDepreciation,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,CentralBankNotePayable,AccountsPayable Loans 8 LongTermLoansReceivable,ShortTermLoansReceivable,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,NotesLoansReceivable,NotesLoansPayable,LoansReceivable Loans payable 20 LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,NotesLoansPayable,LongTermLoansReceivable,ShortTermLoansReceivable,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,ReserveDepositPayable-Loans payable on notes 110 NotesLoansPayable,LongTermLoansPayable,NotesLoansReceivable,NonOperatingNotesPayable,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,CentralBankNotePayable+Loans payable on notes 107 NotesLoansPayable,LongTermLoansPayable,NotesLoansReceivable,NonOperatingNotesPayable,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,CentralBankNotePayable Loans receivable 23 LongTermLoansReceivable,ShortTermLoansReceivable,NotesLoansReceivable,LoansReceivable,AccountsReceivable,ReserveDepositReceivable,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,NotesReceivable-Loans receivable on notes 110 NotesLoansReceivable,LongTermLoansReceivable,NotesLoansPayable,LossOnSalesOfNotesReceivable,DishonoredNotesReceivable,NonOperatingNotesReceivable,ShortTermLoansReceivable,LongTermLoansPayable,NotesReceivable,ElectronicallyRecordedReceivable+Loans receivable on notes 107 NotesLoansReceivable,LongTermLoansReceivable,NotesLoansPayable,LossOnSalesOfNotesReceivable,DishonoredNotesReceivable,NonOperatingNotesReceivable,ShortTermLoansReceivable,LongTermLoansPayable,NotesReceivable,ElectronicallyRecordedReceivable LoansPayable 4 LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,NotesLoansPayable LoansReceivable 4 LongTermLoansReceivable,ShortTermLoansReceivable,NotesLoansReceivable,LoansReceivable Long-term 6 LongTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,LongTermNationalBondsPayable,LongTermPrepaidExpenses,LongTermOtherPayables-Long-term accounts payable - other 50 LongTermOtherPayables,LongTermLoansPayable,LongTermNationalBondsPayable,LongTermNationalBonds,LongTermLoansReceivable,ShortTermLoansPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,AccountsPayable,OtherPayables+Long-term accounts payable - other 51 LongTermOtherPayables,LongTermLoansPayable,LongTermNationalBondsPayable,LongTermNationalBonds,LongTermLoansReceivable,ShortTermLoansPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,AccountsPayable,OtherPayables Long-term loans payable 22 LongTermLoansPayable,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,LongTermNationalBondsPayable,NotesLoansPayable,LongTermOtherPayables,LongTermNationalBonds,ShortTermLoansReceivable,DepositPayable Long-term loans receivable 27 LongTermLoansReceivable,ShortTermLoansReceivable,LongTermLoansPayable,NotesLoansReceivable,LoansReceivable,LongTermNationalBonds,AccountsReceivable,ReserveDepositReceivable,ShortTermLoansPayable,LoansPayable-Long-term national bonds 11 LongTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBonds,ShortTermNationalBondsPayable,LongTermLoansReceivable,LongTermLoansPayable,NationalBondInterestEarned,LongTermPrepaidExpenses,LongTermOtherPayables,GainOnNationalSubsidies-Long-term national bonds payable 23 LongTermNationalBondsPayable,LongTermNationalBonds,ShortTermNationalBondsPayable,ShortTermNationalBonds,LongTermLoansPayable,LongTermOtherPayables,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,DepositPayable-Long-term prepaid expenses 32 LongTermPrepaidExpenses,PrepaidExpenses,LongTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,LongTermNationalBondsPayable,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses+Long-term national bonds 12 LongTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBonds,ShortTermNationalBondsPayable,LongTermLoansReceivable,LongTermLoansPayable,CentralBankPaymentExpense,NationalBondInterestEarned,LongTermPrepaidExpenses,LongTermOtherPayables+Long-term national bonds payable 24 LongTermNationalBondsPayable,LongTermNationalBonds,ShortTermNationalBondsPayable,ShortTermNationalBonds,LongTermLoansPayable,LongTermOtherPayables,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,DepositPayable+Long-term prepaid expenses 31 LongTermPrepaidExpenses,PrepaidExpenses,LongTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,LongTermNationalBondsPayable,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidCorporateIncomeTaxes LongTermLoansPayable 1 LongTermLoansPayable LongTermLoansReceivable 1 LongTermLoansReceivable LongTermNationalBonds 2 LongTermNationalBonds,LongTermNationalBondsPayable@@ -576,16 +574,16 @@ LongTermPrepaidExpenses 1 LongTermPrepaidExpenses Loss 17 NetLoss,BadDebtLoss,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,MiscellaneousLoss,InventoryShrinkageLoss,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities Loss attributable to non-controlling interests 38 NetLossAttributableToNCI,NetIncomeAttributableToNCI,NonControllingInterests,InventoryShrinkageLoss,LossOnRetirementOfFixedAssets,Products,StockInvestment,CapitalStock,CentralBankPaymentExpense,GrossProfit-Loss on fire 102 LossOnFire,NetLoss,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities-Loss on retirement of non-current assets 120 LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfFixedAssets,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities-Loss on sale of electronically recorded monetary claims 119 LossOnSalesOfElectronicallyRecordedReceivables,ElectronicallyRecordedReceivable,NonOperatingElectronicallyRecordedReceivable,ElectronicallyRecordedObligations,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory-Loss on sale of investment securities 125 LossOnSalesOfInvestmentSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnValuationOfSecurities,MerchandiseInventory-Loss on sale of receivables 120 LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities-Loss on sale of securities 122 LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnValuationOfSecurities,MerchandiseInventory-Loss on sales of fixed assets 121 LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnDonationOfFixedAssets,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities-Loss on sales of notes receivable 129 LossOnSalesOfNotesReceivable,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfFixedAssets,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,NotesLoansReceivable,MerchandiseInventory,GainOnSalesOfFixedAssets,DishonoredNotesReceivable-Loss on tax purpose reduction entry of non-current assets 126 LossOnReductionOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfFixedAssets,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities-Loss on valuation of securities 119 LossOnValuationOfSecurities,GainOnValuationOfSecurities,LossOnValuationOfMerchandise,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities+Loss on fire 99 LossOnFire,NetLoss,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities+Loss on retirement of non-current assets 119 LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfFixedAssets,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities+Loss on sale of electronically recorded monetary claims 118 LossOnSalesOfElectronicallyRecordedReceivables,ElectronicallyRecordedReceivable,NonOperatingElectronicallyRecordedReceivable,ElectronicallyRecordedObligations,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory+Loss on sale of investment securities 124 LossOnSalesOfInvestmentSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnValuationOfSecurities,MerchandiseInventory+Loss on sale of receivables 119 LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities+Loss on sale of securities 121 LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnValuationOfSecurities,MerchandiseInventory+Loss on sales of fixed assets 120 LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnDonationOfFixedAssets,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities+Loss on sales of notes receivable 128 LossOnSalesOfNotesReceivable,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfFixedAssets,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,NotesLoansReceivable,MerchandiseInventory,GainOnSalesOfFixedAssets,DishonoredNotesReceivable+Loss on tax purpose reduction entry of non-current assets 125 LossOnReductionOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfFixedAssets,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities+Loss on valuation of securities 118 LossOnValuationOfSecurities,GainOnValuationOfSecurities,LossOnValuationOfMerchandise,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities LossOnFire 1 LossOnFire LossOnReductionOfFixedAssets 1 LossOnReductionOfFixedAssets LossOnRetirementOfFixedAssets 1 LossOnRetirementOfFixedAssets@@ -598,12 +596,12 @@ LossOnValuationOfMerchandise 1 LossOnValuationOfMerchandise LossOnValuationOfSecurities 1 LossOnValuationOfSecurities Machinery 1 Machinery-Machinery and equipment 19 Machinery,Fixtures,Products,EquipmentInvestment,BusinessTrip,MerchandiseInventory,Land,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand+Machinery and equipment 20 Machinery,Fixtures,Products,EquipmentInvestment,BusinessTrip,MerchandiseInventory,Land,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand Maintenance 1 MaintenanceExpenses-Maintenance expenses 25 MaintenanceExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses+Maintenance expenses 24 MaintenanceExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses MaintenanceExpenses 1 MaintenanceExpenses Meeting 1 MeetingExpenses-Meeting expenses 25 MeetingExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses+Meeting expenses 24 MeetingExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses MeetingExpenses 1 MeetingExpenses Membership 1 MembershipFees Membership fees 3 MembershipFees,ReceiptFee,PaymentFees@@ -617,8 +615,8 @@ MiscellaneousExpenses 1 MiscellaneousExpenses MiscellaneousIncome 1 MiscellaneousIncome MiscellaneousLoss 1 MiscellaneousLoss-National 6 LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,NationalBondInterestEarned,GainOnNationalSubsidies-National bond interest earned 18 NationalBondInterestEarned,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,DepositInterestEarned,InterestEarned,InterestExpense,WageEarned,UnearnedRevenue+National 7 LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,CentralBankPaymentExpense,NationalBondInterestEarned,GainOnNationalSubsidies+National bond interest earned 19 NationalBondInterestEarned,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,DepositInterestEarned,InterestEarned,InterestExpense,CentralBankPaymentExpense,WageEarned NationalBondInterestEarned 1 NationalBondInterestEarned Net income 26 NetIncome,NetIncomeAttributableToNCI,SubsidyIncome,RentalIncome,WageEarned,CentralBankPaymentIncome,NetLoss,ElectronicallyRecordedReceivable,PrepaidCorporateIncomeTaxes,ElectronicallyRecordedObligations Net loss 25 NetLoss,LossOnSalesOfElectronicallyRecordedReceivables,NetLossAttributableToNCI,NetIncome,ElectronicallyRecordedReceivable,ElectronicallyRecordedObligations,AllowanceForDoubtfulAccounts,BadDebtLoss,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable@@ -630,7 +628,7 @@ NetLossAttributableToNCI 1 NetLossAttributableToNCI NewspaperBooksExpenses 1 NewspaperBooksExpenses Newspapers 1 NewspaperBooksExpenses-Newspapers and books 18 NewspaperBooksExpenses,BranchCurrentAccount,HeadOfficeCurrentAccount,Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort+Newspapers and books 19 NewspaperBooksExpenses,BranchCurrentAccount,HeadOfficeCurrentAccount,Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort Non-controlling 3 NonControllingInterests,NetIncomeAttributableToNCI,NetLossAttributableToNCI Non-controlling interests 4 NonControllingInterests,NetIncomeAttributableToNCI,NetLossAttributableToNCI,LeaseholdRights Non-operating 4 NonOperatingNotesReceivable,NonOperatingElectronicallyRecordedReceivable,NonOperatingNotesPayable,NonOperatingElectronicallyRecordedObligations@@ -649,50 +647,51 @@ NotesPayable 2 NotesPayable,NonOperatingNotesPayable NotesReceivable 4 NotesReceivable,LossOnSalesOfNotesReceivable,DishonoredNotesReceivable,NonOperatingNotesReceivable Operating 6 NonOperatingNotesReceivable,NonOperatingElectronicallyRecordedReceivable,NonOperatingNotesPayable,NonOperatingElectronicallyRecordedObligations,OperatingRevenue,OperatingExpenses-Operating expenses 30 OperatingExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,NonOperatingNotesReceivable+Operating expenses 29 OperatingExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,NonOperatingNotesReceivable,NonOperatingElectronicallyRecordedReceivable Operating revenue 45 OperatingRevenue,ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome OperatingExpenses 1 OperatingExpenses OperatingRevenue 1 OperatingRevenue Ordinary profit 3 OrdinaryProfit,GrossProfit,NetIncomeAttributableToNCI OrdinaryProfit 1 OrdinaryProfit Organization 1 IncorporationExpenses-Organization expenses 25 IncorporationExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses-Other 5 OtherReceivables,OtherPayables,LongTermOtherPayables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities-Other capital surplus 9 OtherCapitalSurplus,LegalCapitalSurplus,CapitalSurplus,CapitalStock,OtherReceivables,OtherPayables,LongTermOtherPayables,ValuationDifferenceOnOtherSecurities,EarnedSurplus-Other payables 5 OtherPayables,LongTermOtherPayables,OtherReceivables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities-Other receivables 8 OtherReceivables,OtherPayables,AllowanceForDoubtfulAccounts,LongTermOtherPayables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables+Organization expenses 24 IncorporationExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses+Other 6 OtherReceivables,OtherPayables,LongTermOtherPayables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities,DirectorsCompensations+Other capital surplus 10 OtherCapitalSurplus,LegalCapitalSurplus,CapitalSurplus,CapitalStock,OtherReceivables,OtherPayables,LongTermOtherPayables,ValuationDifferenceOnOtherSecurities,EarnedSurplus,DirectorsCompensations+Other payables 6 OtherPayables,LongTermOtherPayables,OtherReceivables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities,DirectorsCompensations+Other receivables 9 OtherReceivables,OtherPayables,AllowanceForDoubtfulAccounts,LongTermOtherPayables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,DirectorsCompensations OtherCapitalSurplus 1 OtherCapitalSurplus OtherPayables 2 OtherPayables,LongTermOtherPayables OtherReceivables 1 OtherReceivables Patent 2 Patent,AmortizationOfPatents Payment 6 CentralBankPaymentExpense,ReceiptFee,CentralBankPaymentIncome,PaymentsOnBehalf,SuspensePayments,PaymentFees Payment fees / fees paid 35 PaymentFees,ReceiptFee,CentralBankPaymentExpense,CentralBankPaymentIncome,MembershipFees,Products,ReserveDepositReceivable,GovernmentService,ReserveForDepreciation,DepositPayable+Payment to national treasury 33 CentralBankPaymentExpense,LongTermNationalBonds,ShortTermNationalBonds,Products,StockInvestment,CapitalStock,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,NationalBondInterestEarned,GrossProfit PaymentFees 2 ReceiptFee,PaymentFees Payments 2 PaymentsOnBehalf,SuspensePayments-Payments made on behalf 98 PaymentsOnBehalf,SuspensePayments,LongTermNationalBonds,ShortTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,ReserveForDepreciation,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,Depreciation+Payments made on behalf 95 PaymentsOnBehalf,SuspensePayments,LongTermNationalBonds,ShortTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,ReserveForDepreciation,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,Depreciation PaymentsOnBehalf 1 PaymentsOnBehalf-Period 4 NetIncome,NetLoss,MerchandiseInventory,AdditionalIncomeTaxesForPriorPeriods+Period 6 NetIncome,GrossProfit,OrdinaryProfit,NetLoss,MerchandiseInventory,AdditionalIncomeTaxesForPriorPeriods Petty 1 PettyCash Petty cash 3 PettyCash,Cash,CashOverShort PettyCash 1 PettyCash Prepaid 4 PrepaidExpenses,PrepaidCorporateIncomeTaxes,LongTermPrepaidExpenses,PrepaidPensionCost Prepaid corporate income taxes 22 PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,IncomeTaxesRefundReceivable,AdditionalIncomeTaxesForPriorPeriods,RefundOfIncomeTaxes,IncomeTaxesAdjustment,TaxesExpense,NetIncome,SubsidyIncome-Prepaid expenses 27 PrepaidExpenses,LongTermPrepaidExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidCorporateIncomeTaxes,AccruedExpenses,CommunicationExpenses,PrepaidPensionCost+Prepaid expenses 26 PrepaidExpenses,LongTermPrepaidExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidCorporateIncomeTaxes,AccruedExpenses,CommunicationExpenses,PrepaidPensionCost,OperatingExpenses Prepaid pension costs 6 PrepaidPensionCost,PrepaidExpenses,PrepaidCorporateIncomeTaxes,LongTermPrepaidExpenses,StockIssuanceCosts,StorageExpenses PrepaidCorporateIncomeTaxes 1 PrepaidCorporateIncomeTaxes PrepaidExpenses 2 PrepaidExpenses,LongTermPrepaidExpenses PrepaidPensionCost 1 PrepaidPensionCost Products 2 Products,MerchandiseInventory-Profit attributable to non-controlling interests 24 NetIncomeAttributableToNCI,NetLossAttributableToNCI,GrossProfit,OrdinaryProfit,NonControllingInterests,Products,StockInvestment,CapitalStock,CentralBankPaymentExpense,CentralBankPaymentIncome+Profit attributable to non-controlling interests 24 NetIncomeAttributableToNCI,NetLossAttributableToNCI,GrossProfit,OrdinaryProfit,NonControllingInterests,Products,StockInvestment,CapitalStock,CentralBankPaymentExpense,MerchandiseInventory Property 1 PropertyTaxPayable Property tax payable 32 PropertyTaxPayable,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,CentralBankNotePayable,TaxesExpense PropertyTaxPayable 1 PropertyTaxPayable-Provision 11 ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties-Provision for bonuses 34 AllowanceForBonuses,ProvisionForBonuses,ReversalOfAllowanceForBonuses,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs-Provision for doubtful accounts 37 ProvisionForDoubtfulAccounts,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs-Provision for repairs 33 AllowanceForRepairs,ReversalOfAllowanceForRepairs,ProvisionForRepairs,ProvisionForDoubtfulAccounts,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,RepairFundReserve,ReversalOfAllowanceForProductWarranties,ProvisionForBonuses-Provision for retirement benefits 36 AllowanceForRetirementBenefits,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties-Provision for warranties 32 AllowanceForProductWarranties,ReversalOfAllowanceForProductWarranties,ProvisionForProductWarranties,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ProvisionForRepairs,ProvisionForBonuses+Provision 5 ProvisionForDoubtfulAccounts,AllowanceForRetirementBenefits,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties+Provision for bonuses 35 ProvisionForBonuses,ProvisionForDoubtfulAccounts,AllowanceForBonuses,AllowanceForRetirementBenefits,ProvisionForRepairs,ProvisionForProductWarranties,ReversalOfAllowanceForBonuses,RetainedEarnings,ReserveForDepreciation,AmortizationExpense+Provision for doubtful accounts 38 ProvisionForDoubtfulAccounts,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRetirementBenefits,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,AccountsReceivable,RetainedEarnings,ReserveForDepreciation+Provision for repairs 34 ProvisionForRepairs,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForRetirementBenefits,RepairFundReserve,ReversalOfAllowanceForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,RetainedEarnings,ReserveForDepreciation+Provision for retirement benefits 37 AllowanceForRetirementBenefits,ProvisionForDoubtfulAccounts,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,RetainedEarnings,ReserveForDepreciation,AmortizationExpense,MerchandiseInventory,SuspensePayments+Provision for warranties 33 ProvisionForProductWarranties,ProvisionForDoubtfulAccounts,AllowanceForProductWarranties,AllowanceForRetirementBenefits,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs,ProvisionForBonuses,RetainedEarnings,ReserveForDepreciation,AmortizationExpense ProvisionForBonuses 1 ProvisionForBonuses ProvisionForDoubtfulAccounts 1 ProvisionForDoubtfulAccounts ProvisionForProductWarranties 1 ProvisionForProductWarranties@@ -707,59 +706,60 @@ Raw 1 RawMaterials Raw materials 1 RawMaterials RawMaterials 1 RawMaterials-Real 1 Building-Real estate 1 Building Receipt 5 ReceiptFee,SuspenseReceipts,PaymentFees,GainOnDonationOfFixedAssets,GainOnNationalSubsidies Receipt fee 6 ReceiptFee,PaymentFees,SuspenseReceipts,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,MembershipFees ReceiptFee 2 ReceiptFee,PaymentFees Reciprocal 2 BranchCurrentAccount,HeadOfficeCurrentAccount Recovery 1 RecoveryOfBadDebts-Recovery of bad debts written off 43 RecoveryOfBadDebts,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,BranchCurrentAccount,HeadOfficeCurrentAccount,DepositsReceivedFromOfficers,SalesCost+Recovery of bad debts written off 43 RecoveryOfBadDebts,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,BranchCurrentAccount,HeadOfficeCurrentAccount,DepositsReceivedFromOfficers,DirectorsCompensations RecoveryOfBadDebts 1 RecoveryOfBadDebts Refund 4 IncomeTaxesRefundReceivable,RefundLiabilities,RefundOfIncomeTaxes,ConsumptionTaxRefundReceivable Refund liabilities 6 RefundLiabilities,IncomeTaxesRefundReceivable,DeferredTaxLiabilities,LeaseObligations,RefundOfIncomeTaxes,ConsumptionTaxRefundReceivable Refund of income taxes 61 RefundOfIncomeTaxes,IncomeTaxesRefundReceivable,PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,AdditionalIncomeTaxesForPriorPeriods,IncomeTaxesAdjustment,NetIncomeAttributableToNCI,SalesCost,TaxesExpense RefundLiabilities 1 RefundLiabilities RefundOfIncomeTaxes 1 RefundOfIncomeTaxes+Remuneration 1 DirectorsCompensations+Remuneration for directors (and other officers) 37 DirectorsCompensations,ValuationDifferenceOnOtherSecurities,RetainedEarnings,ReserveForDepreciation,AmortizationExpense,MerchandiseInventory,OtherReceivables,SuspensePayments,OtherPayables,SuspenseReceipts Rent 10 CurrentDeposits,RentExpense,RentalIncome,GainOnDonationOfFixedAssets,LandRentReceived,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LandRentPaid,BranchCurrentAccount,HeadOfficeCurrentAccount-Rent expenses on land 126 LandRentPaid,Commutation,CommunicationExpenses,LongTermPrepaidExpenses,GainOnDonationOfFixedAssets,LandRentReceived,IncorporationExpenses,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,CurrentDeposits+Rent expenses on land 123 LandRentPaid,CommunicationExpenses,LongTermPrepaidExpenses,GainOnDonationOfFixedAssets,LandRentReceived,IncorporationExpenses,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,CurrentDeposits,LongTermNationalBonds RentExpense 1 RentExpense Rental 2 RentalIncome,LandRentReceived Rental income 17 RentalIncome,LandRentReceived,NetIncome,SubsidyIncome,WageEarned,CentralBankPaymentIncome,PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,MiscellaneousIncome Rental income from land 23 LandRentReceived,RentalIncome,NetIncome,SubsidyIncome,WageEarned,CentralBankPaymentIncome,PrepaidCorporateIncomeTaxes,Land,AccruedCorporateIncomeTaxes,AllowanceForDoubtfulAccounts RentalIncome 1 RentalIncome Repair 5 AllowanceForRepairs,RepairFundReserve,ReversalOfAllowanceForRepairs,ProvisionForRepairs,RepairsExpense-Repair expenses 29 RepairsExpense,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,AllowanceForRepairs+Repair expenses 28 RepairsExpense,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,AllowanceForRepairs,RepairFundReserve RepairFundReserve 1 RepairFundReserve RepairsExpense 1 RepairsExpense Research 1 ResearchAndDevelopmentExpenses-Research and development expenses 40 ResearchAndDevelopmentExpenses,DevelopmentExpenses,LandRentPaid,NewspaperBooksExpenses,Products,Machinery,BusinessTrip,Commutation,DeliveryExpenses,SuppliesExpenses+Research and development expenses 40 ResearchAndDevelopmentExpenses,DevelopmentExpenses,LandRentPaid,NewspaperBooksExpenses,Products,Machinery,BusinessTrip,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses ResearchAndDevelopmentExpenses 1 ResearchAndDevelopmentExpenses Reserve 9 ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,AccumulatedDepreciation,LegalRetainedEarnings,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve,GeneralReserve Reserve deposits, asset side 87 ReserveDepositReceivable,ReserveDepositPayable,AccumulatedDepreciation,AllowanceForDoubtfulAccounts,Cash,Deposits,CurrentDeposits,Securities,InvestmentSecurities,InvestmentInAssociate Reserve deposits, liability side 48 ReserveDepositPayable,ReserveDepositReceivable,ReserveForDepreciation,AccumulatedDepreciation,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable-Reserve for depreciation 37 ReserveForDepreciation,AccumulatedDepreciation,AmortizationExpense,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve,ReserveDepositReceivable,ReserveDepositPayable,Depreciation,MerchandiseInventory-Reserve for dividend equalization 38 DividendEqualizationReserve,ReserveForDepreciation,AccumulatedDepreciation,RepairFundReserve,ConstructionFundReserve,ReserveDepositReceivable,ReserveDepositPayable,AmortizationExpense,MerchandiseInventory,SuspensePayments-Reserve for new construction 38 ConstructionFundReserve,ReserveForDepreciation,AccumulatedDepreciation,DividendEqualizationReserve,RepairFundReserve,GainOnConstructionGrants,ReserveDepositReceivable,ReserveDepositPayable,AmortizationExpense,MerchandiseInventory-Reserve for repairs 37 RepairFundReserve,ReserveForDepreciation,AccumulatedDepreciation,AllowanceForRepairs,DividendEqualizationReserve,ConstructionFundReserve,ReversalOfAllowanceForRepairs,ProvisionForRepairs,ReserveDepositReceivable,ReserveDepositPayable+Reserve for depreciation 38 ReserveForDepreciation,AccumulatedDepreciation,AmortizationExpense,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve,ReserveDepositReceivable,RetainedEarnings,ReserveDepositPayable,Depreciation+Reserve for dividend equalization 39 DividendEqualizationReserve,ReserveForDepreciation,AccumulatedDepreciation,RepairFundReserve,ConstructionFundReserve,ReserveDepositReceivable,RetainedEarnings,ReserveDepositPayable,AmortizationExpense,MerchandiseInventory+Reserve for new construction 39 ConstructionFundReserve,ReserveForDepreciation,AccumulatedDepreciation,DividendEqualizationReserve,RepairFundReserve,GainOnConstructionGrants,ReserveDepositReceivable,RetainedEarnings,ReserveDepositPayable,AmortizationExpense+Reserve for repairs 38 RepairFundReserve,ReserveForDepreciation,AccumulatedDepreciation,AllowanceForRepairs,DividendEqualizationReserve,ConstructionFundReserve,ReversalOfAllowanceForRepairs,ProvisionForRepairs,ReserveDepositReceivable,RetainedEarnings ReserveDepositPayable 1 ReserveDepositPayable ReserveDepositReceivable 1 ReserveDepositReceivable ReserveForDepreciation 2 ReserveForDepreciation,AccumulatedDepreciation-Retained 5 RetainedEarnings,AccumulatedDepreciation,LegalRetainedEarnings,CommunicationExpenses,EarnedSurplus-Retained earnings 6 RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,EquityInEarningsOfInvestee,AccumulatedDepreciation,CommunicationExpenses+Retained 4 RetainedEarnings,AccumulatedDepreciation,LegalRetainedEarnings,EarnedSurplus+Retained earnings 5 RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,EquityInEarningsOfInvestee,AccumulatedDepreciation+Retained earnings brought forward 5 RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,EquityInEarningsOfInvestee,AccumulatedDepreciation RetainedEarnings 2 RetainedEarnings,LegalRetainedEarnings Retirement 5 NetDefinedBenefitAsset,AllowanceForRetirementBenefits,NetDefinedBenefitLiability,RetirementBenefitExpenses,LossOnRetirementOfFixedAssets Retirement benefit asset 83 NetDefinedBenefitAsset,AllowanceForRetirementBenefits,NetDefinedBenefitLiability,RetirementBenefitExpenses,LossOnRetirementOfFixedAssets,Cash,Deposits,CurrentDeposits,Securities,InvestmentSecurities-Retirement benefit expenses 29 RetirementBenefitExpenses,NetDefinedBenefitAsset,AllowanceForRetirementBenefits,NetDefinedBenefitLiability,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses+Retirement benefit expenses 28 RetirementBenefitExpenses,NetDefinedBenefitAsset,AllowanceForRetirementBenefits,NetDefinedBenefitLiability,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses Retirement benefit liability 43 AllowanceForRetirementBenefits,NetDefinedBenefitLiability,NetDefinedBenefitAsset,RetirementBenefitExpenses,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,ReserveForDepreciation,DepositPayable,LongTermNationalBondsPayable RetirementBenefitExpenses 1 RetirementBenefitExpenses Revenue 40 ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome,WageEarned Revenue: 34 ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,InterestEarned,ReceiptFee,RentalIncome,WageEarned,TaxesRevenue,CentralBankPaymentIncome Reversal 4 ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses-Reversal of allowance for doubtful accounts 74 ReversalOfAllowanceForDoubtfulAccounts,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses,ProvisionForDoubtfulAccounts,MerchandiseInventory,CommunicationExpenses,AllowanceForRepairs,AllowanceForProductWarranties-Reversal of provision for bonuses 69 ReversalOfAllowanceForBonuses,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForBonuses,ProvisionForBonuses,MerchandiseInventory,ProvisionForDoubtfulAccounts,CommunicationExpenses,AllowanceForRepairs-Reversal of provision for repairs 68 ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,ProvisionForRepairs,MerchandiseInventory,ProvisionForDoubtfulAccounts,CommunicationExpenses,AllowanceForProductWarranties-Reversal of provision for warranties 67 ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForBonuses,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForProductWarranties,ProvisionForProductWarranties,MerchandiseInventory,ProvisionForDoubtfulAccounts,CommunicationExpenses,AllowanceForRepairs+Reversal of allowance for bonuses 72 ReversalOfAllowanceForBonuses,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,AllowanceForBonuses,MerchandiseInventory,AllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForRetirementBenefits+Reversal of allowance for doubtful accounts 75 ReversalOfAllowanceForDoubtfulAccounts,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses,ProvisionForDoubtfulAccounts,MerchandiseInventory,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses+Reversal of allowance for repairs 71 ReversalOfAllowanceForRepairs,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses,AllowanceForRepairs,MerchandiseInventory,AllowanceForDoubtfulAccounts,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits+Reversal of allowance for warranties 70 ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForBonuses,AllowanceForProductWarranties,MerchandiseInventory,AllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForBonuses,AllowanceForRetirementBenefits ReversalOfAllowanceForBonuses 1 ReversalOfAllowanceForBonuses ReversalOfAllowanceForDoubtfulAccounts 1 ReversalOfAllowanceForDoubtfulAccounts ReversalOfAllowanceForProductWarranties 1 ReversalOfAllowanceForProductWarranties@@ -787,14 +787,14 @@ Short-term 4 ShortTermNationalBonds,ShortTermLoansReceivable,ShortTermLoansPayable,ShortTermNationalBondsPayable Short-term loans payable 21 ShortTermLoansPayable,ShortTermLoansReceivable,LongTermLoansPayable,LoansPayable,ShortTermNationalBondsPayable,NotesLoansPayable,ShortTermNationalBonds,LongTermLoansReceivable,DepositPayable,LongTermNationalBondsPayable Short-term loans receivable 25 ShortTermLoansReceivable,LongTermLoansReceivable,ShortTermLoansPayable,NotesLoansReceivable,LoansReceivable,ShortTermNationalBonds,AccountsReceivable,ReserveDepositReceivable,LongTermLoansPayable,LoansPayable-Short-term national bonds 9 ShortTermNationalBonds,ShortTermNationalBondsPayable,LongTermNationalBonds,LongTermNationalBondsPayable,ShortTermLoansReceivable,ShortTermLoansPayable,NationalBondInterestEarned,GainOnNationalSubsidies,HeldToMaturityBonds-Short-term national bonds payable 22 ShortTermNationalBondsPayable,ShortTermNationalBonds,LongTermNationalBondsPayable,LongTermNationalBonds,ShortTermLoansPayable,ShortTermLoansReceivable,LongTermLoansPayable,LoansPayable,DepositPayable,ReserveDepositPayable+Short-term national bonds 10 ShortTermNationalBonds,ShortTermNationalBondsPayable,LongTermNationalBonds,LongTermNationalBondsPayable,ShortTermLoansReceivable,ShortTermLoansPayable,CentralBankPaymentExpense,NationalBondInterestEarned,GainOnNationalSubsidies,HeldToMaturityBonds+Short-term national bonds payable 23 ShortTermNationalBondsPayable,ShortTermNationalBonds,LongTermNationalBondsPayable,LongTermNationalBonds,ShortTermLoansPayable,ShortTermLoansReceivable,LongTermLoansPayable,LoansPayable,DepositPayable,ReserveDepositPayable ShortTermLoansPayable 1 ShortTermLoansPayable ShortTermLoansReceivable 1 ShortTermLoansReceivable ShortTermNationalBonds 2 ShortTermNationalBonds,ShortTermNationalBondsPayable ShortTermNationalBondsPayable 1 ShortTermNationalBondsPayable Software 3 Software,SoftwareInProgress,AmortizationOfSoftware-Software in progress 90 SoftwareInProgress,ConstructionInProgress,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment+Software in progress 89 SoftwareInProgress,ConstructionInProgress,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment SoftwareInProgress 1 SoftwareInProgress StatutoryWelfareExpenses 1 StatutoryWelfareExpenses Stock 6 StockInvestment,CapitalStock,StockSubscriptionDeposits,StockIssuanceCosts,SubsidiaryStocks,AffiliateStocks@@ -813,6 +813,8 @@ SubsidyExpense 1 SubsidyExpense SubsidyIncome 1 SubsidyIncome Supplies 2 SuppliesExpenses,SuppliesOnHand+Supplies expense 74 SuppliesExpenses,Depreciation,AmortizationExpense,SalesCost,BusinessTrip,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses,MiscellaneousExpenses+Supplies on hand 98 SuppliesOnHand,MerchandiseInventory,LossOnValuationOfMerchandise,LongTermNationalBonds,ShortTermNationalBonds,Products,LongTermLoansReceivable,LongTermLoansPayable,ReserveForDepreciation,LongTermNationalBondsPayable SuppliesExpenses 1 SuppliesExpenses SuppliesOnHand 1 SuppliesOnHand Suspense account 21 SuspensePayments,SuspenseReceipts,SuspenseAccount,AccountsReceivable,ReserveDepositPayable,MerchandiseInventory,PrepaidExpenses,AccruedRevenue,CashOverShort,AccountsPayable@@ -832,14 +834,14 @@ Time deposits 12 TimeDeposits,Deposits,CurrentDeposits,ReserveDepositReceivable,DepositPayable,ReserveDepositPayable,DepositsReceived,SecurityDepositsPaid,DepositsInSpecialAccounts,GuaranteeDepositsReceived TimeDeposits 1 TimeDeposits Tools 1 ToolsAndInstruments-Tools and instruments 18 ToolsAndInstruments,Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand+Tools and instruments 19 ToolsAndInstruments,Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand ToolsAndInstruments 1 ToolsAndInstruments Trademark 1 Trademark Trading 1 TradingSecurities Trading securities 12 TradingSecurities,Securities,InvestmentSecurities,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnValuationOfSecurities,InterestOnSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnValuationOfSecurities TradingSecurities 1 TradingSecurities Travel 1 BusinessTrip-Travel and transportation 18 BusinessTrip,Products,Machinery,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand,ToolsAndInstruments+Travel and transportation 19 BusinessTrip,Products,Machinery,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand,ToolsAndInstruments Unearned 1 UnearnedRevenue Unearned revenue 40 UnearnedRevenue,ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome UnearnedRevenue 1 UnearnedRevenue@@ -850,8 +852,8 @@ Utilities 1 UtilitiesExpense UtilitiesExpense 1 UtilitiesExpense Valuation 6 AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities,LossOnValuationOfMerchandise,LossOnValuationOfSecurities-Valuation difference on available-for-sale securities 102 ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities,LossOnValuationOfSecurities,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,GainOnSalesOfSecurities,InterestOnSecurities,GainOnSalesOfInvestmentSecurities,LossOnValuationOfMerchandise,LossOnSalesOfSecurities-Valuation loss on goods 103 LossOnValuationOfMerchandise,LossOnValuationOfSecurities,NetLoss,MerchandiseInventory,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities+Valuation difference on available-for-sale securities 99 ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities,LossOnValuationOfSecurities,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,GainOnSalesOfSecurities,InterestOnSecurities,GainOnSalesOfInvestmentSecurities,LossOnValuationOfMerchandise,LossOnSalesOfSecurities+Valuation loss on goods 100 LossOnValuationOfMerchandise,LossOnValuationOfSecurities,NetLoss,MerchandiseInventory,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities ValuationDifferenceOnOtherSecurities 1 ValuationDifferenceOnOtherSecurities Value 12 NetIncome,ValueAdded,GrossProfit,OrdinaryProfit,NetLoss,SuspensePayments,SuspenseReceipts,AllowanceForDoubtfulAccounts,IncomeSummary,SuspenseAccount Value added 12 ValueAdded,NetIncome,GrossProfit,OrdinaryProfit,NetLoss,SuspensePayments,SuspenseReceipts,AllowanceForDoubtfulAccounts,IncomeSummary,SuspenseAccount@@ -864,10 +866,10 @@ WageExpenditure 1 WageExpenditure Wages 1 WageExpenditure Welfare 2 WelfareExpenses,StatutoryWelfareExpenses-Welfare expenses 25 WelfareExpenses,StatutoryWelfareExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses+Welfare expenses 24 WelfareExpenses,StatutoryWelfareExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses WelfareExpenses 2 WelfareExpenses,StatutoryWelfareExpenses Work 5 EquityInEarningsOfInvestee,CumulativeTranslationAdjustment,WorkInProcess,NetIncomeAttributableToNCI,NetLossAttributableToNCI-Work in process 88 WorkInProcess,EquityInEarningsOfInvestee,CumulativeTranslationAdjustment,NetIncomeAttributableToNCI,NetLossAttributableToNCI,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery+Work in process 87 WorkInProcess,EquityInEarningsOfInvestee,CumulativeTranslationAdjustment,NetIncomeAttributableToNCI,NetLossAttributableToNCI,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery WorkInProcess 1 WorkInProcess a 224 Cash,Deposits,CurrentDeposits,Securities,InvestmentSecurities,InvestmentInAssociate,LongTermNationalBonds,ShortTermNationalBonds,Products,Machinery accepted 1 DepositPayable@@ -882,7 +884,7 @@ accrued (unpaid) consumption tax 21 AccruedConsumptionTax,AccruedCorporateIncomeTaxes,ConsumptionTaxPaid,ConsumptionTaxReceived,ConsumptionTaxRefundReceivable,TaxesExpense,ConsumptionExpenditure,TaxesRevenue,AccruedRevenue,PrepaidCorporateIncomeTaxes accrued (unpaid) corporate income taxes 23 AccruedCorporateIncomeTaxes,PrepaidCorporateIncomeTaxes,CorporateIncomeTaxes,AccruedConsumptionTax,IncomeTaxesRefundReceivable,AdditionalIncomeTaxesForPriorPeriods,RefundOfIncomeTaxes,IncomeTaxesAdjustment,TaxesExpense,NetIncome accrued bonuses 9 BonusesPayable,AccruedRevenue,AccruedExpenses,AccruedConsumptionTax,AccruedCorporateIncomeTaxes,AllowanceForBonuses,Bonuses,ProvisionForBonuses,ReversalOfAllowanceForBonuses-accrued expenses 29 AccruedExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedRevenue,AccruedConsumptionTax,AccruedCorporateIncomeTaxes,CommunicationExpenses+accrued expenses 28 AccruedExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedRevenue,AccruedConsumptionTax,AccruedCorporateIncomeTaxes,CommunicationExpenses,LongTermPrepaidExpenses accrued revenue 44 AccruedRevenue,ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome accruedconsumptiontax 1 AccruedConsumptionTax accruedcorporateincometaxes 1 AccruedCorporateIncomeTaxes@@ -892,26 +894,29 @@ accumulated depreciation 4 ReserveForDepreciation,AccumulatedDepreciation,Depreciation,AmortizationExpense accumulateddepreciation 2 ReserveForDepreciation,AccumulatedDepreciation added 1 ValueAdded-additional income taxes for prior periods 50 AdditionalIncomeTaxesForPriorPeriods,PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,IncomeTaxesRefundReceivable,RefundOfIncomeTaxes,IncomeTaxesAdjustment,ReserveForDepreciation,AmortizationExpense,TaxesExpense+additional income taxes for prior periods 51 AdditionalIncomeTaxesForPriorPeriods,PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,IncomeTaxesRefundReceivable,RefundOfIncomeTaxes,IncomeTaxesAdjustment,RetainedEarnings,ReserveForDepreciation,AmortizationExpense additionalincometaxesforpriorperiods 1 AdditionalIncomeTaxesForPriorPeriods adjustment 2 CumulativeTranslationAdjustment,IncomeTaxesAdjustment adjustment: 1 CumulativeTranslationAdjustment advances paid 13 AdvancesPaid,PrepaidExpenses,ConsumptionTaxPaid,PrepaidCorporateIncomeTaxes,AdvancesReceived,AccruedConsumptionTax,AccruedCorporateIncomeTaxes,UnpaidDividends,PaymentFees,SecurityDepositsPaid-advances received 11 AdvancesReceived,DepositPayable,AdvancesPaid,DepositsReceived,ConsumptionTaxReceived,GiftCertificatesReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants,LandRentReceived+advances received 12 AdvancesReceived,DepositPayable,CentralBankPaymentIncome,AdvancesPaid,DepositsReceived,ConsumptionTaxReceived,GiftCertificatesReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants advancespaid 1 AdvancesPaid advancesreceived 1 AdvancesReceived advertising 1 AdvertisingExpense advertisingexpense 1 AdvertisingExpense affiliatestocks 1 AffiliateStocks allowance 11 AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,SalesAllowances,PurchaseAllowances-allowance for doubtful accounts 39 AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses+allowance for bonuses 37 AllowanceForBonuses,ReversalOfAllowanceForBonuses,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForBonuses+allowance for doubtful accounts 40 AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses+allowance for repairs 36 AllowanceForRepairs,ReversalOfAllowanceForRepairs,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,RepairFundReserve,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs+allowance for warranties 35 AllowanceForProductWarranties,ReversalOfAllowanceForProductWarranties,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ProvisionForProductWarranties,ReversalOfAllowanceForBonuses allowanceforbonuses 2 AllowanceForBonuses,ReversalOfAllowanceForBonuses allowancefordoubtfulaccounts 2 AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts allowanceforproductwarranties 2 AllowanceForProductWarranties,ReversalOfAllowanceForProductWarranties allowanceforrepairs 2 AllowanceForRepairs,ReversalOfAllowanceForRepairs allowanceforretirementbenefits 1 AllowanceForRetirementBenefits allowances 2 SalesAllowances,PurchaseAllowances-amortization expense for intangibles 97 AmortizationExpense,ProvisionForDoubtfulAccounts,CommunicationExpenses,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationOfPatents,AdditionalIncomeTaxesForPriorPeriods+amortization expense for intangibles 98 AmortizationExpense,ProvisionForDoubtfulAccounts,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationOfPatents,AdditionalIncomeTaxesForPriorPeriods,ForeignExchangeLosses amortization of goodwill 44 AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationOfPatents,AmortizationExpense,SalesCost,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee,MerchandiseInventory,Software amortization of patent rights 45 AmortizationOfPatents,AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationExpense,SalesCost,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee,MerchandiseInventory,Patent amortization of software 43 AmortizationOfSoftware,Software,SoftwareInProgress,AmortizationOfGoodwill,AmortizationOfPatents,AmortizationExpense,SalesCost,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee@@ -920,22 +925,21 @@ amortizationofpatents 1 AmortizationOfPatents amortizationofsoftware 1 AmortizationOfSoftware amount 1 InvestmentInAssociate-an 72 Products,Machinery,LongTermLoansReceivable,ShortTermLoansReceivable,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,CentralBankNotePayable,AmortizationExpense,BusinessTrip-and 18 Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand,ToolsAndInstruments+an 73 Products,Machinery,LongTermLoansReceivable,ShortTermLoansReceivable,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,CentralBankNotePayable,AmortizationExpense,BusinessTrip+and 19 Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand,ToolsAndInstruments are 12 Software,CashOverShort,SoftwareInProgress,StockSubscriptionDeposits,AmortizationOfSoftware,StockIssuanceCosts,WelfareExpenses,StatutoryWelfareExpenses,BranchCurrentAccount,HeadOfficeCurrentAccount-as 93 Cash,Deposits,CurrentDeposits,Securities,InvestmentSecurities,InvestmentInAssociate,LongTermNationalBonds,ShortTermNationalBonds,Products,Machinery+as 92 Cash,Deposits,CurrentDeposits,Securities,InvestmentSecurities,InvestmentInAssociate,LongTermNationalBonds,ShortTermNationalBonds,Products,Machinery asset 80 Cash,Deposits,CurrentDeposits,Securities,InvestmentSecurities,InvestmentInAssociate,LongTermNationalBonds,ShortTermNationalBonds,Products,Machinery assets 12 SuspensePayments,AccumulatedDepreciation,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,ContractAssets,DeferredTaxAssets,LeasedAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets assets. 1 AccumulatedDepreciation associate 2 InvestmentInAssociate,AffiliateStocks associates 1 AffiliateStocks-at 65 InvestmentInAssociate,LongTermNationalBonds,ShortTermNationalBonds,Building,ReserveForDepreciation,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,Depreciation,AmortizationExpense,BusinessTrip+at 65 InvestmentInAssociate,LongTermNationalBonds,ShortTermNationalBonds,ReserveForDepreciation,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,Depreciation,AmortizationExpense,BusinessTrip,CentralBankPaymentExpense attributable 2 NetIncomeAttributableToNCI,NetLossAttributableToNCI attribution 2 NetIncomeAttributableToNCI,NetLossAttributableToNCI available-for-sale 2 ValuationDifferenceOnOtherSecurities,AvailableForSaleSecurities available-for-sale securities 12 ValuationDifferenceOnOtherSecurities,AvailableForSaleSecurities,Securities,InvestmentSecurities,GainOnSalesOfSecurities,GainOnValuationOfSecurities,InterestOnSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnValuationOfSecurities availableforsalesecurities 1 AvailableForSaleSecurities-backward 1 CommunicationExpenses bad 2 BadDebtLoss,RecoveryOfBadDebts bad debt loss 18 BadDebtLoss,RecoveryOfBadDebts,NetLoss,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,MiscellaneousLoss,InventoryShrinkageLoss,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables baddebtloss 1 BadDebtLoss@@ -961,8 +965,10 @@ branch 2 BranchCurrentAccount,HeadOfficeCurrentAccount branch current account 25 BranchCurrentAccount,HeadOfficeCurrentAccount,CurrentDeposits,AccountsReceivable,ReserveDepositPayable,MerchandiseInventory,PrepaidExpenses,AccruedRevenue,SuspensePayments,CashOverShort branchcurrentaccount 1 BranchCurrentAccount+brought 1 RetainedEarnings building 1 Building-business commencement expenses 26 BusinessCommencementExpenses,BusinessTrip,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses+buildings 1 Building+business commencement expenses 25 BusinessCommencementExpenses,BusinessTrip,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses businesscommencementexpenses 1 BusinessCommencementExpenses businesstrip 1 BusinessTrip but 5 GainOnConstructionGrants,BranchCurrentAccount,HeadOfficeCurrentAccount,NetIncomeAttributableToNCI,NetLossAttributableToNCI@@ -975,10 +981,10 @@ capitalsurplus 3 LegalCapitalSurplus,OtherCapitalSurplus,CapitalSurplus card 1 CreditCardReceivable cash 3 Cash,PettyCash,CashOverShort-cash over and short 27 CashOverShort,Cash,ShortTermNationalBonds,Products,Machinery,ShortTermLoansReceivable,GovernmentService,ShortTermLoansPayable,ShortTermNationalBondsPayable,BusinessTrip+cash over and short 28 CashOverShort,Cash,ShortTermNationalBonds,Products,Machinery,ShortTermLoansReceivable,GovernmentService,ShortTermLoansPayable,ShortTermNationalBondsPayable,BusinessTrip cashovershort 1 CashOverShort central bank notes 12 CentralBankNotePayable,CentralBankPaymentExpense,CentralBankPaymentIncome,NotesReceivable,NotesLoansReceivable,NotesPayable,NotesLoansPayable,BankOverdraft,LossOnSalesOfNotesReceivable,DishonoredNotesReceivable-central bank payment to treasury 28 CentralBankPaymentExpense,CentralBankPaymentIncome,CentralBankNotePayable,Products,StockInvestment,CapitalStock,GrossProfit,OrdinaryProfit,ReceiptFee,MerchandiseInventory+central bank payment received 18 CentralBankPaymentIncome,CentralBankPaymentExpense,CentralBankNotePayable,DepositPayable,ReceiptFee,PaymentsOnBehalf,SuspensePayments,BankOverdraft,AdvancesReceived,DepositsReceived centralbanknotepayable 1 CentralBankNotePayable centralbankpaymentexpense 1 CentralBankPaymentExpense centralbankpaymentincome 1 CentralBankPaymentIncome@@ -991,33 +997,29 @@ closing; 1 IncomeSummary combined. 2 BranchCurrentAccount,HeadOfficeCurrentAccount commencement 1 BusinessCommencementExpenses-communication 2 Commutation,CommunicationExpenses-communication expenses 25 Commutation,CommunicationExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses-communicationexpenses 2 Commutation,CommunicationExpenses-commutation 2 Commutation,CommunicationExpenses-compatibility. 1 CommunicationExpenses+communication expenses 24 CommunicationExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses,ResearchAndDevelopmentExpenses+communicationexpenses 1 CommunicationExpenses consolidation 4 EquityInEarningsOfInvestee,CumulativeTranslationAdjustment,NetIncomeAttributableToNCI,NetLossAttributableToNCI construction 3 ConstructionInProgress,ConstructionFundReserve,GainOnConstructionGrants-construction in progress 89 ConstructionInProgress,SoftwareInProgress,GainOnConstructionGrants,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment+construction in progress 88 ConstructionInProgress,SoftwareInProgress,GainOnConstructionGrants,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment constructionfundreserve 1 ConstructionFundReserve constructioninprogress 1 ConstructionInProgress consumption 5 ConsumptionExpenditure,ConsumptionTaxPaid,ConsumptionTaxReceived,AccruedConsumptionTax,ConsumptionTaxRefundReceivable consumption expenditure 7 ConsumptionExpenditure,WageExpenditure,SubsidyExpense,ConsumptionTaxPaid,ConsumptionTaxReceived,AccruedConsumptionTax,ConsumptionTaxRefundReceivable consumption tax paid 26 ConsumptionTaxPaid,AccruedConsumptionTax,PrepaidCorporateIncomeTaxes,ConsumptionTaxReceived,AccruedCorporateIncomeTaxes,ConsumptionTaxRefundReceivable,TaxesExpense,ConsumptionExpenditure,TaxesRevenue,AdvancesPaid-consumption tax received 27 ConsumptionTaxReceived,ConsumptionTaxPaid,AccruedConsumptionTax,ConsumptionTaxRefundReceivable,DepositPayable,TaxesExpense,ConsumptionExpenditure,TaxesRevenue,PrepaidCorporateIncomeTaxes,AdvancesReceived+consumption tax received 28 ConsumptionTaxReceived,ConsumptionTaxPaid,AccruedConsumptionTax,ConsumptionTaxRefundReceivable,DepositPayable,TaxesExpense,ConsumptionExpenditure,TaxesRevenue,CentralBankPaymentIncome,PrepaidCorporateIncomeTaxes consumption tax refund receivable 36 ConsumptionTaxRefundReceivable,IncomeTaxesRefundReceivable,ConsumptionTaxPaid,ConsumptionTaxReceived,AccruedConsumptionTax,RefundOfIncomeTaxes,LongTermLoansReceivable,AccountsReceivable,ShortTermLoansReceivable,ReserveDepositReceivable consumptionexpenditure 1 ConsumptionExpenditure consumptiontaxpaid 1 ConsumptionTaxPaid consumptiontaxreceived 1 ConsumptionTaxReceived consumptiontaxrefundreceivable 1 ConsumptionTaxRefundReceivable contra 4 AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ContractAssets,ContraAccountForGuaranteeObligations-contra account for guarantee obligations 51 ContraAccountForGuaranteeObligations,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,MerchandiseInventory,SuspensePayments,SuspenseReceipts,ProvisionForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,SuspenseAccount,GuaranteeObligations+contra account for guarantee obligations 52 ContraAccountForGuaranteeObligations,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,MerchandiseInventory,SuspensePayments,SuspenseReceipts,ProvisionForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,SuspenseAccount,GuaranteeObligations contraaccountforguaranteeobligations 1 ContraAccountForGuaranteeObligations contract assets 12 ContractAssets,SuspensePayments,AccumulatedDepreciation,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,DeferredTaxAssets,LeasedAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets contractassets 1 ContractAssets contribution 1 GainOnConstructionGrants control 6 SuspensePayments,SuspenseReceipts,NonControllingInterests,SuspenseAccount,NetIncomeAttributableToNCI,NetLossAttributableToNCI-coordinate: 2 GrossProfit,OrdinaryProfit corporate 3 PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes corporate income taxes 19 PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,IncomeTaxesRefundReceivable,AdditionalIncomeTaxesForPriorPeriods,RefundOfIncomeTaxes,IncomeTaxesAdjustment,TaxesExpense,NetIncome,SubsidyIncome corporateincometaxes 3 PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes@@ -1026,7 +1028,7 @@ cost of services 46 CostOfServices,SalesCost,MerchandiseInventory,NetIncomeAttributableToNCI,NetIncome,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee,Software,LossOnSalesOfFixedAssets costofservices 1 CostOfServices costs 3 PrepaidPensionCost,StockIssuanceCosts,StorageExpenses-counterpart 3 PaymentFees,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts+counterpart 2 PaymentFees,ReversalOfAllowanceForDoubtfulAccounts credit card receivable 21 CreditCardReceivable,AllowanceForDoubtfulAccounts,LongTermLoansReceivable,AccountsReceivable,ShortTermLoansReceivable,ReserveDepositReceivable,NotesReceivable,ElectronicallyRecordedReceivable,NotesLoansReceivable,OtherReceivables credit-balance 2 AllowanceForDoubtfulAccounts,AccumulatedDepreciation creditcardreceivable 1 CreditCardReceivable@@ -1055,10 +1057,10 @@ depositpayable 2 DepositPayable,ReserveDepositPayable deposits 12 Deposits,CurrentDeposits,ReserveDepositReceivable,DepositPayable,ReserveDepositPayable,DepositsReceived,TimeDeposits,SecurityDepositsPaid,DepositsInSpecialAccounts,GuaranteeDepositsReceived deposits accepted 12 DepositPayable,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,DepositsReceived,TimeDeposits,SecurityDepositsPaid,DepositsInSpecialAccounts,GuaranteeDepositsReceived-deposits for subscriptions of shares 77 StockSubscriptionDeposits,MerchandiseInventory,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,SubsidiaryStocks,AffiliateStocks,DepositsReceivedFromOfficers,ReversalOfAllowanceForBonuses-deposits in special accounts 102 DepositsInSpecialAccounts,Deposits,ReserveDepositPayable,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,CurrentDeposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery-deposits received 18 DepositPayable,DepositsReceived,GuaranteeDepositsReceived,DepositsReceivedFromOfficers,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,AdvancesReceived,ConsumptionTaxReceived-deposits received from officers 20 DepositsReceivedFromOfficers,DepositPayable,DepositsReceived,GuaranteeDepositsReceived,LandRentReceived,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,AdvancesReceived+deposits for subscriptions of shares 78 StockSubscriptionDeposits,MerchandiseInventory,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,SubsidiaryStocks,AffiliateStocks,DepositsReceivedFromOfficers,ReversalOfAllowanceForBonuses,DirectorsCompensations+deposits in special accounts 101 DepositsInSpecialAccounts,Deposits,ReserveDepositPayable,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,CurrentDeposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery+deposits received 19 DepositPayable,DepositsReceived,GuaranteeDepositsReceived,DepositsReceivedFromOfficers,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,CentralBankPaymentIncome,AdvancesReceived+deposits received from officers 22 DepositsReceivedFromOfficers,DepositPayable,DepositsReceived,GuaranteeDepositsReceived,LandRentReceived,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,CentralBankPaymentIncome deposits, 2 ReserveDepositReceivable,ReserveDepositPayable depositsinspecialaccounts 1 DepositsInSpecialAccounts depositsreceived 4 DepositPayable,DepositsReceived,GuaranteeDepositsReceived,DepositsReceivedFromOfficers@@ -1067,11 +1069,13 @@ depreciation 4 ReserveForDepreciation,Depreciation,AmortizationExpense,AccumulatedDepreciation depreciation; 1 AccumulatedDepreciation development 2 ResearchAndDevelopmentExpenses,DevelopmentExpenses-development expenses 25 ResearchAndDevelopmentExpenses,DevelopmentExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses+development expenses 24 ResearchAndDevelopmentExpenses,DevelopmentExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses developmentexpenses 2 ResearchAndDevelopmentExpenses,DevelopmentExpenses device: 1 IncomeSummary difference 1 ValuationDifferenceOnOtherSecurities direction 7 NetIncome,GrossProfit,OrdinaryProfit,NetLoss,IncomeSummary,NetIncomeAttributableToNCI,NetLossAttributableToNCI+directors 1 DirectorsCompensations+directorscompensations 1 DirectorsCompensations dishonored notes receivable 23 DishonoredNotesReceivable,NotesReceivable,NotesLoansReceivable,LossOnSalesOfNotesReceivable,NonOperatingNotesReceivable,LongTermLoansReceivable,AccountsReceivable,ShortTermLoansReceivable,ReserveDepositReceivable,CentralBankNotePayable dishonorednotesreceivable 1 DishonoredNotesReceivable dividend 3 UnpaidDividends,DividendEqualizationReserve,DividendsReceived@@ -1096,8 +1100,7 @@ eliminated 2 BranchCurrentAccount,HeadOfficeCurrentAccount encoding, 5 NetIncome,GrossProfit,OrdinaryProfit,NetLoss,IncomeSummary encoding. 2 NetIncomeAttributableToNCI,NetLossAttributableToNCI-engine 4 NetIncome,GrossProfit,OrdinaryProfit,NetLoss-entertainment expenses 25 EntertainmentExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses+entertainment expenses 24 EntertainmentExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses entertainmentexpenses 1 EntertainmentExpenses entry 1 LossOnReductionOfFixedAssets equalization 1 DividendEqualizationReserve@@ -1105,40 +1108,40 @@ equipment investment 8 EquipmentInvestment,InvestmentSecurities,InvestmentInAssociate,Machinery,StockInvestment,Fixtures,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities equipmentinvestment 1 EquipmentInvestment equity 16 InvestmentInAssociate,CapitalStock,RetainedEarnings,EquityInEarningsOfInvestee,LegalRetainedEarnings,StockSubscriptionDeposits,LegalCapitalSurplus,OtherCapitalSurplus,DividendEqualizationReserve,RepairFundReserve-equity in earnings of investee 121 EquityInEarningsOfInvestee,RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,InvestmentInAssociate,GrossProfit,OrdinaryProfit,MerchandiseInventory,CommunicationExpenses,GainOnSalesOfFixedAssets+equity in earnings of investee 121 EquityInEarningsOfInvestee,RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,InvestmentInAssociate,GrossProfit,OrdinaryProfit,MerchandiseInventory,GainOnSalesOfFixedAssets,ReversalOfAllowanceForDoubtfulAccounts equityinearningsofinvestee 1 EquityInEarningsOfInvestee-estate 1 Building estimated 1 ReversalOfAllowanceForDoubtfulAccounts examples 1 ReserveDepositPayable excess 1 ReversalOfAllowanceForDoubtfulAccounts exchange 3 AllowanceForDoubtfulAccounts,ForeignExchangeGains,ForeignExchangeLosses existing 2 AccumulatedDepreciation,ReversalOfAllowanceForDoubtfulAccounts expenditure 3 WageExpenditure,ConsumptionExpenditure,SubsidyExpense-expense 73 Depreciation,AmortizationExpense,SalesCost,BusinessTrip,Commutation,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses,SuppliesExpenses-expenses 25 Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses+expense 73 Depreciation,AmortizationExpense,SalesCost,BusinessTrip,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses+expenses 24 DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses,ResearchAndDevelopmentExpenses fee 3 ReceiptFee,PaymentFees,MembershipFees fees 3 ReceiptFee,PaymentFees,MembershipFees financial 1 CashOverShort fire 1 LossOnFire fixed 5 LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets fixtures 1 Fixtures-fixtures and equipment 19 Fixtures,Machinery,Products,EquipmentInvestment,BusinessTrip,MerchandiseInventory,Land,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand-for 32 ReserveForDepreciation,AmortizationExpense,MerchandiseInventory,SuspensePayments,SuspenseReceipts,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ProvisionForDoubtfulAccounts,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts+fixtures and equipment 20 Fixtures,Machinery,Products,EquipmentInvestment,BusinessTrip,MerchandiseInventory,Land,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand+for 33 RetainedEarnings,ReserveForDepreciation,AmortizationExpense,MerchandiseInventory,SuspensePayments,SuspenseReceipts,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ProvisionForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts foreign exchange gains 3 ForeignExchangeGains,ForeignExchangeLosses,AllowanceForDoubtfulAccounts foreign exchange losses 3 ForeignExchangeLosses,ForeignExchangeGains,AllowanceForDoubtfulAccounts foreignexchangegains 1 ForeignExchangeGains foreignexchangelosses 1 ForeignExchangeLosses+forward 1 RetainedEarnings from 4 AllowanceForDoubtfulAccounts,AccumulatedDepreciation,LandRentReceived,DepositsReceivedFromOfficers gain 11 MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,InsuranceGain,GainOnBargainPurchase,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,GainOnConstructionGrants-gain on bargain purchase 102 GainOnBargainPurchase,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,InsuranceGain,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,GainOnConstructionGrants-gain on contribution received for construction 111 GainOnConstructionGrants,MerchandiseInventory,ConstructionFundReserve,ReserveForDepreciation,AmortizationExpense,SuspensePayments,SuspenseReceipts,ConsumptionTaxReceived,AllowanceForDoubtfulAccounts,AccumulatedDepreciation-gain on insurance claims 100 InsuranceGain,ElectronicallyRecordedReceivable,MerchandiseInventory,GainOnSalesOfFixedAssets,NonOperatingElectronicallyRecordedReceivable,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,GainOnBargainPurchase,GainOnDonationOfFixedAssets-gain on receipt of donated non-current assets 115 GainOnDonationOfFixedAssets,GainOnSalesOfFixedAssets,GainOnNationalSubsidies,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,MerchandiseInventory,LossOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities-gain on receipt of national subsidies 113 GainOnNationalSubsidies,GainOnDonationOfFixedAssets,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable-gain on sale of investment securities 122 GainOnSalesOfInvestmentSecurities,GainOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnValuationOfSecurities,LossOnSalesOfSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities-gain on sale of securities 119 GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnValuationOfSecurities,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities-gain on sales of fixed assets 118 GainOnSalesOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,MerchandiseInventory,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnValuationOfSecurities-gain on valuation of securities 116 GainOnValuationOfSecurities,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnValuationOfSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,ValuationDifferenceOnOtherSecurities,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,LossOnValuationOfMerchandise+gain on bargain purchase 99 GainOnBargainPurchase,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,InsuranceGain,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,GainOnConstructionGrants+gain on contribution received for construction 114 GainOnConstructionGrants,MerchandiseInventory,ConstructionFundReserve,ReserveForDepreciation,AmortizationExpense,SuspensePayments,SuspenseReceipts,ConsumptionTaxReceived,AllowanceForDoubtfulAccounts,AccumulatedDepreciation+gain on insurance claims 97 InsuranceGain,ElectronicallyRecordedReceivable,MerchandiseInventory,GainOnSalesOfFixedAssets,NonOperatingElectronicallyRecordedReceivable,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,GainOnBargainPurchase,GainOnDonationOfFixedAssets+gain on receipt of donated non-current assets 114 GainOnDonationOfFixedAssets,GainOnSalesOfFixedAssets,GainOnNationalSubsidies,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,MerchandiseInventory,LossOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities+gain on receipt of national subsidies 112 GainOnNationalSubsidies,GainOnDonationOfFixedAssets,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable+gain on sale of investment securities 121 GainOnSalesOfInvestmentSecurities,GainOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnValuationOfSecurities,LossOnSalesOfSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities+gain on sale of securities 118 GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnValuationOfSecurities,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities+gain on sales of fixed assets 117 GainOnSalesOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,MerchandiseInventory,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnValuationOfSecurities+gain on valuation of securities 115 GainOnValuationOfSecurities,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnValuationOfSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,ValuationDifferenceOnOtherSecurities,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,LossOnValuationOfMerchandise gainonbargainpurchase 1 GainOnBargainPurchase gainonconstructiongrants 1 GainOnConstructionGrants gainondonationoffixedassets 1 GainOnDonationOfFixedAssets@@ -1150,11 +1153,11 @@ gains 1 ForeignExchangeGains general reserve 9 GeneralReserve,ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,AccumulatedDepreciation,LegalRetainedEarnings,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve generalreserve 1 GeneralReserve-gift certificates received 10 GiftCertificatesReceived,DepositPayable,AdvancesReceived,DepositsReceived,ConsumptionTaxReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants,LandRentReceived,DepositsReceivedFromOfficers+gift certificates received 11 GiftCertificatesReceived,DepositPayable,CentralBankPaymentIncome,AdvancesReceived,DepositsReceived,ConsumptionTaxReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants,LandRentReceived giftcertificatesreceived 1 GiftCertificatesReceived gold 1 Gold goods 3 MerchandiseInventory,LossOnValuationOfMerchandise,GoodsInTransit-goods in transit 89 GoodsInTransit,MerchandiseInventory,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment+goods in transit 88 GoodsInTransit,MerchandiseInventory,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment goodsintransit 1 GoodsInTransit goodwill 2 Goodwill,AmortizationOfGoodwill government service 3 GovernmentService,ServiceRevenue,CostOfServices@@ -1164,16 +1167,17 @@ grossprofit 1 GrossProfit guarantee 4 SecurityDepositsPaid,GuaranteeDepositsReceived,ContraAccountForGuaranteeObligations,GuaranteeObligations guarantee deposits 14 SecurityDepositsPaid,GuaranteeDepositsReceived,Deposits,CurrentDeposits,ReserveDepositReceivable,DepositPayable,ReserveDepositPayable,DepositsReceived,TimeDeposits,DepositsInSpecialAccounts-guarantee deposits received 20 GuaranteeDepositsReceived,DepositPayable,DepositsReceived,SecurityDepositsPaid,DepositsReceivedFromOfficers,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,AdvancesReceived+guarantee deposits received 21 GuaranteeDepositsReceived,DepositPayable,DepositsReceived,SecurityDepositsPaid,DepositsReceivedFromOfficers,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,CentralBankPaymentIncome guarantee obligations 7 ContraAccountForGuaranteeObligations,GuaranteeObligations,ElectronicallyRecordedObligations,SecurityDepositsPaid,NonOperatingElectronicallyRecordedObligations,LeaseObligations,GuaranteeDepositsReceived guaranteedepositsreceived 1 GuaranteeDepositsReceived guaranteeobligations 2 ContraAccountForGuaranteeObligations,GuaranteeObligations-head office current account 26 BranchCurrentAccount,HeadOfficeCurrentAccount,CurrentDeposits,AccountsReceivable,ReserveDepositPayable,MerchandiseInventory,PrepaidExpenses,AccruedRevenue,SuspensePayments,CashOverShort+hand 5 Products,MerchandiseInventory,SuppliesOnHand,LossOnValuationOfMerchandise,ResearchAndDevelopmentExpenses+head office current account 27 BranchCurrentAccount,HeadOfficeCurrentAccount,CurrentDeposits,AccountsReceivable,ReserveDepositPayable,MerchandiseInventory,PrepaidExpenses,AccruedRevenue,SuspensePayments,CashOverShort head-office 2 BranchCurrentAccount,HeadOfficeCurrentAccount headofficecurrentaccount 1 HeadOfficeCurrentAccount held-to-maturity bonds 5 HeldToMaturityBonds,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable heldtomaturitybonds 1 HeldToMaturityBonds-in 88 Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment,RetainedEarnings,AmortizationExpense+in 87 Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment,RetainedEarnings,AmortizationExpense income 17 NetIncome,SubsidyIncome,RentalIncome,WageEarned,CentralBankPaymentIncome,PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,MiscellaneousIncome,IncomeTaxesRefundReceivable income summary 17 IncomeSummary,NetIncome,SubsidyIncome,RentalIncome,WageEarned,CentralBankPaymentIncome,PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,MiscellaneousIncome income taxes - deferred 51 IncomeTaxesAdjustment,NetIncome,PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,IncomeTaxesRefundReceivable,AdditionalIncomeTaxesForPriorPeriods,RefundOfIncomeTaxes,IncomeSummary,NetIncomeAttributableToNCI@@ -1186,15 +1190,15 @@ instead. 1 MerchandiseInventory instruments 1 ToolsAndInstruments insurance 2 InsuranceGain,InsuranceExpense-insurance expenses 26 InsuranceExpense,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,InsuranceGain+insurance expenses 25 InsuranceExpense,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,InsuranceGain,OperatingExpenses insuranceexpense 1 InsuranceExpense insurancegain 1 InsuranceGain intact. 1 AllowanceForDoubtfulAccounts intangibles 1 AmortizationExpense interest 9 InterestExpense,NationalBondInterestEarned,DepositInterestEarned,InterestEarned,LeaseholdRights,NonControllingInterests,InterestOnSecurities,NetIncomeAttributableToNCI,NetLossAttributableToNCI interest earned 12 NationalBondInterestEarned,DepositInterestEarned,InterestEarned,InterestExpense,WageEarned,UnearnedRevenue,LeaseholdRights,NonControllingInterests,EarnedSurplus,InterestOnSecurities-interest expense 81 InterestExpense,Depreciation,AmortizationExpense,SalesCost,BusinessTrip,Commutation,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses-interest on securities 106 InterestOnSecurities,NationalBondInterestEarned,ValuationDifferenceOnOtherSecurities,NonControllingInterests,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities+interest expense 81 InterestExpense,Depreciation,AmortizationExpense,SalesCost,BusinessTrip,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses,SuppliesExpenses+interest on securities 103 InterestOnSecurities,NationalBondInterestEarned,ValuationDifferenceOnOtherSecurities,NonControllingInterests,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities interestearned 3 NationalBondInterestEarned,DepositInterestEarned,InterestEarned interestexpense 1 InterestExpense interestonsecurities 1 InterestOnSecurities@@ -1205,46 +1209,46 @@ inventoryshrinkageloss 1 InventoryShrinkageLoss investee 1 EquityInEarningsOfInvestee investment 6 InvestmentSecurities,InvestmentInAssociate,StockInvestment,EquipmentInvestment,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities-investment in associate 89 InvestmentInAssociate,InvestmentSecurities,StockInvestment,EquipmentInvestment,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities,Deposits,Products,Machinery,Building+investment in associate 88 InvestmentInAssociate,InvestmentSecurities,StockInvestment,EquipmentInvestment,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities,Deposits,Products,Machinery,Building investment securities 15 InvestmentSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities,Securities,InvestmentInAssociate,StockInvestment,EquipmentInvestment,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnValuationOfSecurities investmentinassociate 1 InvestmentInAssociate investmentsecurities 3 InvestmentSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities-is 37 Products,AdvertisingExpense,MiscellaneousExpenses,NetIncome,GrossProfit,OrdinaryProfit,NetLoss,MerchandiseInventory,SuspensePayments,CashOverShort+is 30 Products,AdvertisingExpense,MiscellaneousExpenses,NetIncome,GrossProfit,OrdinaryProfit,NetLoss,MerchandiseInventory,SuspensePayments,CashOverShort issuance 1 StockIssuanceCosts-it 98 Deposits,CurrentDeposits,Securities,InvestmentSecurities,InvestmentInAssociate,ReserveDepositReceivable,CapitalStock,RetainedEarnings,LongTermLoansPayable,ShortTermLoansPayable+it 97 Deposits,CurrentDeposits,Securities,InvestmentSecurities,InvestmentInAssociate,ReserveDepositReceivable,CapitalStock,RetainedEarnings,LongTermLoansPayable,ShortTermLoansPayable job. 1 AllowanceForDoubtfulAccounts land 4 Land,LeaseholdRights,LandRentReceived,LandRentPaid landrentpaid 1 LandRentPaid landrentreceived 1 LandRentReceived-lease expenses 29 LeaseExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts,LeasedAssets+lease expenses 28 LeaseExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts,LeasedAssets,LongTermPrepaidExpenses lease liabilities 7 LeaseObligations,ReversalOfAllowanceForDoubtfulAccounts,LeasedAssets,LeaseholdRights,RefundLiabilities,DeferredTaxLiabilities,LeaseExpenses leased assets 13 LeasedAssets,SuspensePayments,AccumulatedDepreciation,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,ReversalOfAllowanceForDoubtfulAccounts,ContractAssets,DeferredTaxAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets leasedassets 1 LeasedAssets leaseexpenses 1 LeaseExpenses-leasehold interests in land 90 LeaseholdRights,NonControllingInterests,LandRentReceived,NetIncomeAttributableToNCI,NetLossAttributableToNCI,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery+leasehold interests in land 89 LeaseholdRights,NonControllingInterests,LandRentReceived,NetIncomeAttributableToNCI,NetLossAttributableToNCI,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery leaseholdrights 1 LeaseholdRights leaseobligations 1 LeaseObligations-legacy 12 NetIncome,GrossProfit,OrdinaryProfit,NetLoss,SuspensePayments,SuspenseReceipts,AccumulatedDepreciation,CommunicationExpenses,IncomeSummary,SuspenseAccount-legal (appropriated) retained earnings reserve 15 LegalRetainedEarnings,RetainedEarnings,AccumulatedDepreciation,EarnedSurplus,ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,EquityInEarningsOfInvestee,CommunicationExpenses,LegalCapitalSurplus+legacy 11 NetIncome,GrossProfit,OrdinaryProfit,NetLoss,SuspensePayments,SuspenseReceipts,AccumulatedDepreciation,IncomeSummary,SuspenseAccount,NetIncomeAttributableToNCI+legal (appropriated) retained earnings reserve 14 LegalRetainedEarnings,RetainedEarnings,AccumulatedDepreciation,EarnedSurplus,ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,EquityInEarningsOfInvestee,LegalCapitalSurplus,DividendEqualizationReserve legal capital surplus 7 LegalCapitalSurplus,OtherCapitalSurplus,CapitalSurplus,CapitalStock,LegalRetainedEarnings,EarnedSurplus,StatutoryWelfareExpenses-legal welfare expenses 27 StatutoryWelfareExpenses,WelfareExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,LegalRetainedEarnings,CommunicationExpenses+legal welfare expenses 26 StatutoryWelfareExpenses,WelfareExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,LegalRetainedEarnings,CommunicationExpenses,LongTermPrepaidExpenses legalcapitalsurplus 1 LegalCapitalSurplus legalretainedearnings 1 LegalRetainedEarnings liabilities 3 RefundLiabilities,DeferredTaxLiabilities,LeaseObligations liability 40 LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,ReserveForDepreciation,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,CentralBankNotePayable,AccountsPayable loans 8 LongTermLoansReceivable,ShortTermLoansReceivable,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,NotesLoansReceivable,NotesLoansPayable,LoansReceivable loans payable 20 LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,NotesLoansPayable,LongTermLoansReceivable,ShortTermLoansReceivable,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,ReserveDepositPayable-loans payable on notes 110 NotesLoansPayable,LongTermLoansPayable,NotesLoansReceivable,NonOperatingNotesPayable,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,CentralBankNotePayable+loans payable on notes 107 NotesLoansPayable,LongTermLoansPayable,NotesLoansReceivable,NonOperatingNotesPayable,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,CentralBankNotePayable loans receivable 23 LongTermLoansReceivable,ShortTermLoansReceivable,NotesLoansReceivable,LoansReceivable,AccountsReceivable,ReserveDepositReceivable,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,NotesReceivable-loans receivable on notes 110 NotesLoansReceivable,LongTermLoansReceivable,NotesLoansPayable,LossOnSalesOfNotesReceivable,DishonoredNotesReceivable,NonOperatingNotesReceivable,ShortTermLoansReceivable,LongTermLoansPayable,NotesReceivable,ElectronicallyRecordedReceivable+loans receivable on notes 107 NotesLoansReceivable,LongTermLoansReceivable,NotesLoansPayable,LossOnSalesOfNotesReceivable,DishonoredNotesReceivable,NonOperatingNotesReceivable,ShortTermLoansReceivable,LongTermLoansPayable,NotesReceivable,ElectronicallyRecordedReceivable loanspayable 4 LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,NotesLoansPayable loansreceivable 4 LongTermLoansReceivable,ShortTermLoansReceivable,NotesLoansReceivable,LoansReceivable-long-term accounts payable - other 50 LongTermOtherPayables,LongTermLoansPayable,LongTermNationalBondsPayable,LongTermNationalBonds,LongTermLoansReceivable,ShortTermLoansPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,AccountsPayable,OtherPayables+long-term accounts payable - other 51 LongTermOtherPayables,LongTermLoansPayable,LongTermNationalBondsPayable,LongTermNationalBonds,LongTermLoansReceivable,ShortTermLoansPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,AccountsPayable,OtherPayables long-term loans payable 22 LongTermLoansPayable,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,LongTermNationalBondsPayable,NotesLoansPayable,LongTermOtherPayables,LongTermNationalBonds,ShortTermLoansReceivable,DepositPayable long-term loans receivable 27 LongTermLoansReceivable,ShortTermLoansReceivable,LongTermLoansPayable,NotesLoansReceivable,LoansReceivable,LongTermNationalBonds,AccountsReceivable,ReserveDepositReceivable,ShortTermLoansPayable,LoansPayable-long-term national bonds 11 LongTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBonds,ShortTermNationalBondsPayable,LongTermLoansReceivable,LongTermLoansPayable,NationalBondInterestEarned,LongTermPrepaidExpenses,LongTermOtherPayables,GainOnNationalSubsidies-long-term national bonds payable 23 LongTermNationalBondsPayable,LongTermNationalBonds,ShortTermNationalBondsPayable,ShortTermNationalBonds,LongTermLoansPayable,LongTermOtherPayables,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,DepositPayable-long-term prepaid expenses 32 LongTermPrepaidExpenses,PrepaidExpenses,LongTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,LongTermNationalBondsPayable,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses+long-term national bonds 12 LongTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBonds,ShortTermNationalBondsPayable,LongTermLoansReceivable,LongTermLoansPayable,CentralBankPaymentExpense,NationalBondInterestEarned,LongTermPrepaidExpenses,LongTermOtherPayables+long-term national bonds payable 24 LongTermNationalBondsPayable,LongTermNationalBonds,ShortTermNationalBondsPayable,ShortTermNationalBonds,LongTermLoansPayable,LongTermOtherPayables,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,DepositPayable+long-term prepaid expenses 31 LongTermPrepaidExpenses,PrepaidExpenses,LongTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,LongTermNationalBondsPayable,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidCorporateIncomeTaxes longtermloanspayable 1 LongTermLoansPayable longtermloansreceivable 1 LongTermLoansReceivable longtermnationalbonds 2 LongTermNationalBonds,LongTermNationalBondsPayable@@ -1253,16 +1257,16 @@ longtermprepaidexpenses 1 LongTermPrepaidExpenses loss 17 NetLoss,BadDebtLoss,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,MiscellaneousLoss,InventoryShrinkageLoss,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities loss attributable to non-controlling interests 38 NetLossAttributableToNCI,NetIncomeAttributableToNCI,NonControllingInterests,InventoryShrinkageLoss,LossOnRetirementOfFixedAssets,Products,StockInvestment,CapitalStock,CentralBankPaymentExpense,GrossProfit-loss on fire 102 LossOnFire,NetLoss,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities-loss on retirement of non-current assets 120 LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfFixedAssets,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities-loss on sale of electronically recorded monetary claims 119 LossOnSalesOfElectronicallyRecordedReceivables,ElectronicallyRecordedReceivable,NonOperatingElectronicallyRecordedReceivable,ElectronicallyRecordedObligations,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory-loss on sale of investment securities 125 LossOnSalesOfInvestmentSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnValuationOfSecurities,MerchandiseInventory-loss on sale of receivables 120 LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities-loss on sale of securities 122 LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnValuationOfSecurities,MerchandiseInventory-loss on sales of fixed assets 121 LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnDonationOfFixedAssets,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities-loss on sales of notes receivable 129 LossOnSalesOfNotesReceivable,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfFixedAssets,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,NotesLoansReceivable,MerchandiseInventory,GainOnSalesOfFixedAssets,DishonoredNotesReceivable-loss on tax purpose reduction entry of non-current assets 126 LossOnReductionOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfFixedAssets,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities-loss on valuation of securities 119 LossOnValuationOfSecurities,GainOnValuationOfSecurities,LossOnValuationOfMerchandise,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities+loss on fire 99 LossOnFire,NetLoss,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities+loss on retirement of non-current assets 119 LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfFixedAssets,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities+loss on sale of electronically recorded monetary claims 118 LossOnSalesOfElectronicallyRecordedReceivables,ElectronicallyRecordedReceivable,NonOperatingElectronicallyRecordedReceivable,ElectronicallyRecordedObligations,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory+loss on sale of investment securities 124 LossOnSalesOfInvestmentSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnValuationOfSecurities,MerchandiseInventory+loss on sale of receivables 119 LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities+loss on sale of securities 121 LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnValuationOfSecurities,MerchandiseInventory+loss on sales of fixed assets 120 LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnDonationOfFixedAssets,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities+loss on sales of notes receivable 128 LossOnSalesOfNotesReceivable,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfFixedAssets,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,NotesLoansReceivable,MerchandiseInventory,GainOnSalesOfFixedAssets,DishonoredNotesReceivable+loss on tax purpose reduction entry of non-current assets 125 LossOnReductionOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfFixedAssets,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities+loss on valuation of securities 118 LossOnValuationOfSecurities,GainOnValuationOfSecurities,LossOnValuationOfMerchandise,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities losses 1 ForeignExchangeLosses lossonfire 1 LossOnFire lossonreductionoffixedassets 1 LossOnReductionOfFixedAssets@@ -1276,13 +1280,13 @@ lossonvaluationofmerchandise 1 LossOnValuationOfMerchandise lossonvaluationofsecurities 1 LossOnValuationOfSecurities machinery 1 Machinery-machinery and equipment 19 Machinery,Fixtures,Products,EquipmentInvestment,BusinessTrip,MerchandiseInventory,Land,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand+machinery and equipment 20 Machinery,Fixtures,Products,EquipmentInvestment,BusinessTrip,MerchandiseInventory,Land,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand made 1 PaymentsOnBehalf-maintenance expenses 25 MaintenanceExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses+maintenance expenses 24 MaintenanceExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses maintenanceexpenses 1 MaintenanceExpenses materials 1 RawMaterials may 2 BranchCurrentAccount,HeadOfficeCurrentAccount-meeting expenses 25 MeetingExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses+meeting expenses 24 MeetingExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses meetingexpenses 1 MeetingExpenses membership fees 3 MembershipFees,ReceiptFee,PaymentFees membershipfees 1 MembershipFees@@ -1299,9 +1303,8 @@ monetary 4 ElectronicallyRecordedReceivable,ElectronicallyRecordedObligations,NonOperatingElectronicallyRecordedReceivable,LossOnSalesOfElectronicallyRecordedReceivables must 1 CashOverShort name. 1 AccumulatedDepreciation-named 1 CommunicationExpenses-national 6 LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,NationalBondInterestEarned,GainOnNationalSubsidies-national bond interest earned 18 NationalBondInterestEarned,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,DepositInterestEarned,InterestEarned,InterestExpense,WageEarned,UnearnedRevenue+national 7 LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,CentralBankPaymentExpense,NationalBondInterestEarned,GainOnNationalSubsidies+national bond interest earned 19 NationalBondInterestEarned,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,DepositInterestEarned,InterestEarned,InterestExpense,CentralBankPaymentExpense,WageEarned nationalbondinterestearned 1 NationalBondInterestEarned net 11 NetIncome,NetLoss,ElectronicallyRecordedReceivable,ElectronicallyRecordedObligations,AllowanceForDoubtfulAccounts,NetDefinedBenefitAsset,NonOperatingElectronicallyRecordedReceivable,NetDefinedBenefitLiability,LossOnSalesOfElectronicallyRecordedReceivables,NetIncomeAttributableToNCI net income 26 NetIncome,NetIncomeAttributableToNCI,SubsidyIncome,RentalIncome,WageEarned,CentralBankPaymentIncome,NetLoss,ElectronicallyRecordedReceivable,PrepaidCorporateIncomeTaxes,ElectronicallyRecordedObligations@@ -1314,7 +1317,7 @@ netlossattributabletonci 1 NetLossAttributableToNCI new 2 ConstructionFundReserve,NewspaperBooksExpenses newspaperbooksexpenses 1 NewspaperBooksExpenses-newspapers and books 18 NewspaperBooksExpenses,BranchCurrentAccount,HeadOfficeCurrentAccount,Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort+newspapers and books 19 NewspaperBooksExpenses,BranchCurrentAccount,HeadOfficeCurrentAccount,Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort non-controlling 3 NonControllingInterests,NetIncomeAttributableToNCI,NetLossAttributableToNCI non-controlling interests 4 NonControllingInterests,NetIncomeAttributableToNCI,NetLossAttributableToNCI,LeaseholdRights non-current 3 GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets@@ -1336,24 +1339,24 @@ notespayable 2 NotesPayable,NonOperatingNotesPayable notesreceivable 4 NotesReceivable,LossOnSalesOfNotesReceivable,DishonoredNotesReceivable,NonOperatingNotesReceivable obligations 5 ElectronicallyRecordedObligations,NonOperatingElectronicallyRecordedObligations,LeaseObligations,ContraAccountForGuaranteeObligations,GuaranteeObligations-of 42 SalesCost,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee,MerchandiseInventory,Software,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,PaymentFees,CommunicationExpenses-off 9 LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,RecoveryOfBadDebts,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,BranchCurrentAccount,HeadOfficeCurrentAccount,DepositsReceivedFromOfficers-officers 1 DepositsReceivedFromOfficers-on 98 LongTermNationalBonds,ShortTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,ReserveForDepreciation,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,Depreciation,AmortizationExpense,BusinessTrip+of 42 SalesCost,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee,MerchandiseInventory,Software,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,PaymentFees,GainOnSalesOfFixedAssets+off 10 LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,RecoveryOfBadDebts,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,BranchCurrentAccount,HeadOfficeCurrentAccount,DepositsReceivedFromOfficers,DirectorsCompensations+officers 2 DepositsReceivedFromOfficers,DirectorsCompensations+on 95 LongTermNationalBonds,ShortTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,ReserveForDepreciation,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,Depreciation,AmortizationExpense,BusinessTrip only 9 NetIncome,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee,NetLoss,CumulativeTranslationAdjustment,IncomeSummary,NetIncomeAttributableToNCI,NetLossAttributableToNCI only; 4 NetIncome,GrossProfit,OrdinaryProfit,NetLoss-operating expenses 30 OperatingExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,NonOperatingNotesReceivable+operating expenses 29 OperatingExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,NonOperatingNotesReceivable,NonOperatingElectronicallyRecordedReceivable operating revenue 45 OperatingRevenue,ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome operatingexpenses 1 OperatingExpenses operatingrevenue 1 OperatingRevenue ordinary 1 OrdinaryProfit ordinary profit 3 OrdinaryProfit,GrossProfit,NetIncomeAttributableToNCI ordinaryprofit 1 OrdinaryProfit-organization expenses 25 IncorporationExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses-other 5 OtherReceivables,OtherPayables,LongTermOtherPayables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities-other capital surplus 9 OtherCapitalSurplus,LegalCapitalSurplus,CapitalSurplus,CapitalStock,OtherReceivables,OtherPayables,LongTermOtherPayables,ValuationDifferenceOnOtherSecurities,EarnedSurplus-other payables 5 OtherPayables,LongTermOtherPayables,OtherReceivables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities-other receivables 8 OtherReceivables,OtherPayables,AllowanceForDoubtfulAccounts,LongTermOtherPayables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables+organization expenses 24 IncorporationExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses+other 6 OtherReceivables,OtherPayables,LongTermOtherPayables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities,DirectorsCompensations+other capital surplus 10 OtherCapitalSurplus,LegalCapitalSurplus,CapitalSurplus,CapitalStock,OtherReceivables,OtherPayables,LongTermOtherPayables,ValuationDifferenceOnOtherSecurities,EarnedSurplus,DirectorsCompensations+other payables 6 OtherPayables,LongTermOtherPayables,OtherReceivables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities,DirectorsCompensations+other receivables 9 OtherReceivables,OtherPayables,AllowanceForDoubtfulAccounts,LongTermOtherPayables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,DirectorsCompensations othercapitalsurplus 1 OtherCapitalSurplus otherpayables 2 OtherPayables,LongTermOtherPayables otherreceivables 1 OtherReceivables@@ -1365,9 +1368,10 @@ payables 2 OtherPayables,LongTermOtherPayables payment 6 CentralBankPaymentExpense,ReceiptFee,CentralBankPaymentIncome,PaymentsOnBehalf,SuspensePayments,PaymentFees payment fees / fees paid 35 PaymentFees,ReceiptFee,CentralBankPaymentExpense,CentralBankPaymentIncome,MembershipFees,Products,ReserveDepositReceivable,GovernmentService,ReserveForDepreciation,DepositPayable+payment to national treasury 33 CentralBankPaymentExpense,LongTermNationalBonds,ShortTermNationalBonds,Products,StockInvestment,CapitalStock,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,NationalBondInterestEarned,GrossProfit paymentfees 2 ReceiptFee,PaymentFees payments 2 PaymentsOnBehalf,SuspensePayments-payments made on behalf 98 PaymentsOnBehalf,SuspensePayments,LongTermNationalBonds,ShortTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,ReserveForDepreciation,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,Depreciation+payments made on behalf 95 PaymentsOnBehalf,SuspensePayments,LongTermNationalBonds,ShortTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,ReserveForDepreciation,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,Depreciation paymentsonbehalf 1 PaymentsOnBehalf pension 1 PrepaidPensionCost periodic/3-account 1 MerchandiseInventory@@ -1376,7 +1380,7 @@ pettycash 1 PettyCash prepaid 4 PrepaidExpenses,PrepaidCorporateIncomeTaxes,LongTermPrepaidExpenses,PrepaidPensionCost prepaid corporate income taxes 22 PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,IncomeTaxesRefundReceivable,AdditionalIncomeTaxesForPriorPeriods,RefundOfIncomeTaxes,IncomeTaxesAdjustment,TaxesExpense,NetIncome,SubsidyIncome-prepaid expenses 27 PrepaidExpenses,LongTermPrepaidExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidCorporateIncomeTaxes,AccruedExpenses,CommunicationExpenses,PrepaidPensionCost+prepaid expenses 26 PrepaidExpenses,LongTermPrepaidExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidCorporateIncomeTaxes,AccruedExpenses,CommunicationExpenses,PrepaidPensionCost,OperatingExpenses prepaid pension costs 6 PrepaidPensionCost,PrepaidExpenses,PrepaidCorporateIncomeTaxes,LongTermPrepaidExpenses,StockIssuanceCosts,StorageExpenses prepaidcorporateincometaxes 1 PrepaidCorporateIncomeTaxes prepaidexpenses 2 PrepaidExpenses,LongTermPrepaidExpenses@@ -1388,16 +1392,15 @@ process 1 WorkInProcess products 2 Products,MerchandiseInventory profit 3 GrossProfit,OrdinaryProfit,NetIncomeAttributableToNCI-profit attributable to non-controlling interests 24 NetIncomeAttributableToNCI,NetLossAttributableToNCI,GrossProfit,OrdinaryProfit,NonControllingInterests,Products,StockInvestment,CapitalStock,CentralBankPaymentExpense,CentralBankPaymentIncome+profit attributable to non-controlling interests 24 NetIncomeAttributableToNCI,NetLossAttributableToNCI,GrossProfit,OrdinaryProfit,NonControllingInterests,Products,StockInvestment,CapitalStock,CentralBankPaymentExpense,MerchandiseInventory progress 2 ConstructionInProgress,SoftwareInProgress property tax payable 32 PropertyTaxPayable,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,CentralBankNotePayable,TaxesExpense propertytaxpayable 1 PropertyTaxPayable-provision 11 ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties-provision for bonuses 34 AllowanceForBonuses,ProvisionForBonuses,ReversalOfAllowanceForBonuses,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs-provision for doubtful accounts 37 ProvisionForDoubtfulAccounts,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs-provision for repairs 33 AllowanceForRepairs,ReversalOfAllowanceForRepairs,ProvisionForRepairs,ProvisionForDoubtfulAccounts,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,RepairFundReserve,ReversalOfAllowanceForProductWarranties,ProvisionForBonuses-provision for retirement benefits 36 AllowanceForRetirementBenefits,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties-provision for warranties 32 AllowanceForProductWarranties,ReversalOfAllowanceForProductWarranties,ProvisionForProductWarranties,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ProvisionForRepairs,ProvisionForBonuses+provision for bonuses 35 ProvisionForBonuses,ProvisionForDoubtfulAccounts,AllowanceForBonuses,AllowanceForRetirementBenefits,ProvisionForRepairs,ProvisionForProductWarranties,ReversalOfAllowanceForBonuses,RetainedEarnings,ReserveForDepreciation,AmortizationExpense+provision for doubtful accounts 38 ProvisionForDoubtfulAccounts,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRetirementBenefits,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,AccountsReceivable,RetainedEarnings,ReserveForDepreciation+provision for repairs 34 ProvisionForRepairs,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForRetirementBenefits,RepairFundReserve,ReversalOfAllowanceForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,RetainedEarnings,ReserveForDepreciation+provision for retirement benefits 37 AllowanceForRetirementBenefits,ProvisionForDoubtfulAccounts,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,RetainedEarnings,ReserveForDepreciation,AmortizationExpense,MerchandiseInventory,SuspensePayments+provision for warranties 33 ProvisionForProductWarranties,ProvisionForDoubtfulAccounts,AllowanceForProductWarranties,AllowanceForRetirementBenefits,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs,ProvisionForBonuses,RetainedEarnings,ReserveForDepreciation,AmortizationExpense provisionforbonuses 1 ProvisionForBonuses provisionfordoubtfulaccounts 1 ProvisionForDoubtfulAccounts provisionforproductwarranties 1 ProvisionForProductWarranties@@ -1411,7 +1414,6 @@ purpose 1 LossOnReductionOfFixedAssets raw materials 1 RawMaterials rawmaterials 1 RawMaterials-real estate 1 Building rebates 2 SalesRebates,PurchaseRebates receipt 5 ReceiptFee,SuspenseReceipts,PaymentFees,GainOnDonationOfFixedAssets,GainOnNationalSubsidies receipt fee 6 ReceiptFee,PaymentFees,SuspenseReceipts,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,MembershipFees@@ -1420,10 +1422,10 @@ receivable 19 LongTermLoansReceivable,AccountsReceivable,ShortTermLoansReceivable,ReserveDepositReceivable,NotesReceivable,ElectronicallyRecordedReceivable,CreditCardReceivable,NotesLoansReceivable,OtherReceivables,AllowanceForDoubtfulAccounts receivables 4 OtherReceivables,AllowanceForDoubtfulAccounts,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables receivables. 1 AllowanceForDoubtfulAccounts-received 10 DepositPayable,AdvancesReceived,DepositsReceived,ConsumptionTaxReceived,GiftCertificatesReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants,LandRentReceived,DepositsReceivedFromOfficers+received 11 DepositPayable,CentralBankPaymentIncome,AdvancesReceived,DepositsReceived,ConsumptionTaxReceived,GiftCertificatesReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants,LandRentReceived recorded 5 ElectronicallyRecordedReceivable,ElectronicallyRecordedObligations,NonOperatingElectronicallyRecordedReceivable,NonOperatingElectronicallyRecordedObligations,LossOnSalesOfElectronicallyRecordedReceivables records 1 MerchandiseInventory-recovery of bad debts written off 43 RecoveryOfBadDebts,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,BranchCurrentAccount,HeadOfficeCurrentAccount,DepositsReceivedFromOfficers,SalesCost+recovery of bad debts written off 43 RecoveryOfBadDebts,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,BranchCurrentAccount,HeadOfficeCurrentAccount,DepositsReceivedFromOfficers,DirectorsCompensations recoveryofbaddebts 1 RecoveryOfBadDebts reduction 1 LossOnReductionOfFixedAssets refund 4 IncomeTaxesRefundReceivable,RefundLiabilities,RefundOfIncomeTaxes,ConsumptionTaxRefundReceivable@@ -1434,43 +1436,45 @@ related 1 AccumulatedDepreciation released). 1 ReversalOfAllowanceForDoubtfulAccounts remain 2 BranchCurrentAccount,HeadOfficeCurrentAccount+remuneration for directors (and other officers) 37 DirectorsCompensations,ValuationDifferenceOnOtherSecurities,RetainedEarnings,ReserveForDepreciation,AmortizationExpense,MerchandiseInventory,OtherReceivables,SuspensePayments,OtherPayables,SuspenseReceipts rent 10 CurrentDeposits,RentExpense,RentalIncome,GainOnDonationOfFixedAssets,LandRentReceived,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LandRentPaid,BranchCurrentAccount,HeadOfficeCurrentAccount-rent expenses on land 126 LandRentPaid,Commutation,CommunicationExpenses,LongTermPrepaidExpenses,GainOnDonationOfFixedAssets,LandRentReceived,IncorporationExpenses,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,CurrentDeposits+rent expenses on land 123 LandRentPaid,CommunicationExpenses,LongTermPrepaidExpenses,GainOnDonationOfFixedAssets,LandRentReceived,IncorporationExpenses,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,CurrentDeposits,LongTermNationalBonds rental income 17 RentalIncome,LandRentReceived,NetIncome,SubsidyIncome,WageEarned,CentralBankPaymentIncome,PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,MiscellaneousIncome rental income from land 23 LandRentReceived,RentalIncome,NetIncome,SubsidyIncome,WageEarned,CentralBankPaymentIncome,PrepaidCorporateIncomeTaxes,Land,AccruedCorporateIncomeTaxes,AllowanceForDoubtfulAccounts rentalincome 1 RentalIncome rentexpense 1 RentExpense-repair expenses 29 RepairsExpense,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,AllowanceForRepairs+repair expenses 28 RepairsExpense,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,AllowanceForRepairs,RepairFundReserve repairfundreserve 1 RepairFundReserve repairs 5 AllowanceForRepairs,RepairFundReserve,ReversalOfAllowanceForRepairs,ProvisionForRepairs,RepairsExpense repairsexpense 1 RepairsExpense require 3 SuspensePayments,SuspenseReceipts,SuspenseAccount-research and development expenses 40 ResearchAndDevelopmentExpenses,DevelopmentExpenses,LandRentPaid,NewspaperBooksExpenses,Products,Machinery,BusinessTrip,Commutation,DeliveryExpenses,SuppliesExpenses+research and development expenses 40 ResearchAndDevelopmentExpenses,DevelopmentExpenses,LandRentPaid,NewspaperBooksExpenses,Products,Machinery,BusinessTrip,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses researchanddevelopmentexpenses 1 ResearchAndDevelopmentExpenses reserve 9 ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,AccumulatedDepreciation,LegalRetainedEarnings,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve,GeneralReserve reserve deposits, asset side 87 ReserveDepositReceivable,ReserveDepositPayable,AccumulatedDepreciation,AllowanceForDoubtfulAccounts,Cash,Deposits,CurrentDeposits,Securities,InvestmentSecurities,InvestmentInAssociate reserve deposits, liability side 48 ReserveDepositPayable,ReserveDepositReceivable,ReserveForDepreciation,AccumulatedDepreciation,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable-reserve for depreciation 37 ReserveForDepreciation,AccumulatedDepreciation,AmortizationExpense,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve,ReserveDepositReceivable,ReserveDepositPayable,Depreciation,MerchandiseInventory-reserve for dividend equalization 38 DividendEqualizationReserve,ReserveForDepreciation,AccumulatedDepreciation,RepairFundReserve,ConstructionFundReserve,ReserveDepositReceivable,ReserveDepositPayable,AmortizationExpense,MerchandiseInventory,SuspensePayments-reserve for new construction 38 ConstructionFundReserve,ReserveForDepreciation,AccumulatedDepreciation,DividendEqualizationReserve,RepairFundReserve,GainOnConstructionGrants,ReserveDepositReceivable,ReserveDepositPayable,AmortizationExpense,MerchandiseInventory-reserve for repairs 37 RepairFundReserve,ReserveForDepreciation,AccumulatedDepreciation,AllowanceForRepairs,DividendEqualizationReserve,ConstructionFundReserve,ReversalOfAllowanceForRepairs,ProvisionForRepairs,ReserveDepositReceivable,ReserveDepositPayable+reserve for depreciation 38 ReserveForDepreciation,AccumulatedDepreciation,AmortizationExpense,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve,ReserveDepositReceivable,RetainedEarnings,ReserveDepositPayable,Depreciation+reserve for dividend equalization 39 DividendEqualizationReserve,ReserveForDepreciation,AccumulatedDepreciation,RepairFundReserve,ConstructionFundReserve,ReserveDepositReceivable,RetainedEarnings,ReserveDepositPayable,AmortizationExpense,MerchandiseInventory+reserve for new construction 39 ConstructionFundReserve,ReserveForDepreciation,AccumulatedDepreciation,DividendEqualizationReserve,RepairFundReserve,GainOnConstructionGrants,ReserveDepositReceivable,RetainedEarnings,ReserveDepositPayable,AmortizationExpense+reserve for repairs 38 RepairFundReserve,ReserveForDepreciation,AccumulatedDepreciation,AllowanceForRepairs,DividendEqualizationReserve,ConstructionFundReserve,ReversalOfAllowanceForRepairs,ProvisionForRepairs,ReserveDepositReceivable,RetainedEarnings reservedepositpayable 1 ReserveDepositPayable reservedepositreceivable 1 ReserveDepositReceivable reservefordepreciation 2 ReserveForDepreciation,AccumulatedDepreciation result: 5 NetIncome,EquityInEarningsOfInvestee,NetLoss,NetIncomeAttributableToNCI,NetLossAttributableToNCI-retained 5 RetainedEarnings,AccumulatedDepreciation,LegalRetainedEarnings,CommunicationExpenses,EarnedSurplus-retained earnings 6 RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,EquityInEarningsOfInvestee,AccumulatedDepreciation,CommunicationExpenses+retained 4 RetainedEarnings,AccumulatedDepreciation,LegalRetainedEarnings,EarnedSurplus+retained earnings 5 RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,EquityInEarningsOfInvestee,AccumulatedDepreciation+retained earnings brought forward 5 RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,EquityInEarningsOfInvestee,AccumulatedDepreciation retainedearnings 2 RetainedEarnings,LegalRetainedEarnings retirement 5 NetDefinedBenefitAsset,AllowanceForRetirementBenefits,NetDefinedBenefitLiability,RetirementBenefitExpenses,LossOnRetirementOfFixedAssets retirement benefit asset 83 NetDefinedBenefitAsset,AllowanceForRetirementBenefits,NetDefinedBenefitLiability,RetirementBenefitExpenses,LossOnRetirementOfFixedAssets,Cash,Deposits,CurrentDeposits,Securities,InvestmentSecurities-retirement benefit expenses 29 RetirementBenefitExpenses,NetDefinedBenefitAsset,AllowanceForRetirementBenefits,NetDefinedBenefitLiability,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses+retirement benefit expenses 28 RetirementBenefitExpenses,NetDefinedBenefitAsset,AllowanceForRetirementBenefits,NetDefinedBenefitLiability,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses retirement benefit liability 43 AllowanceForRetirementBenefits,NetDefinedBenefitLiability,NetDefinedBenefitAsset,RetirementBenefitExpenses,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,ReserveForDepreciation,DepositPayable,LongTermNationalBondsPayable retirementbenefitexpenses 1 RetirementBenefitExpenses revenue 40 ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome,WageEarned-reversal of allowance for doubtful accounts 74 ReversalOfAllowanceForDoubtfulAccounts,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses,ProvisionForDoubtfulAccounts,MerchandiseInventory,CommunicationExpenses,AllowanceForRepairs,AllowanceForProductWarranties-reversal of provision for bonuses 69 ReversalOfAllowanceForBonuses,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForBonuses,ProvisionForBonuses,MerchandiseInventory,ProvisionForDoubtfulAccounts,CommunicationExpenses,AllowanceForRepairs-reversal of provision for repairs 68 ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,ProvisionForRepairs,MerchandiseInventory,ProvisionForDoubtfulAccounts,CommunicationExpenses,AllowanceForProductWarranties-reversal of provision for warranties 67 ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForBonuses,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForProductWarranties,ProvisionForProductWarranties,MerchandiseInventory,ProvisionForDoubtfulAccounts,CommunicationExpenses,AllowanceForRepairs+reversal of allowance for bonuses 72 ReversalOfAllowanceForBonuses,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,AllowanceForBonuses,MerchandiseInventory,AllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForRetirementBenefits+reversal of allowance for doubtful accounts 75 ReversalOfAllowanceForDoubtfulAccounts,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses,ProvisionForDoubtfulAccounts,MerchandiseInventory,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses+reversal of allowance for repairs 71 ReversalOfAllowanceForRepairs,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses,AllowanceForRepairs,MerchandiseInventory,AllowanceForDoubtfulAccounts,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits+reversal of allowance for warranties 70 ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForBonuses,AllowanceForProductWarranties,MerchandiseInventory,AllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForBonuses,AllowanceForRetirementBenefits reversalofallowanceforbonuses 1 ReversalOfAllowanceForBonuses reversalofallowancefordoubtfulaccounts 1 ReversalOfAllowanceForDoubtfulAccounts reversalofallowanceforproductwarranties 1 ReversalOfAllowanceForProductWarranties@@ -1499,8 +1503,8 @@ short 5 ShortTermNationalBonds,ShortTermLoansReceivable,ShortTermLoansPayable,ShortTermNationalBondsPayable,CashOverShort short-term loans payable 21 ShortTermLoansPayable,ShortTermLoansReceivable,LongTermLoansPayable,LoansPayable,ShortTermNationalBondsPayable,NotesLoansPayable,ShortTermNationalBonds,LongTermLoansReceivable,DepositPayable,LongTermNationalBondsPayable short-term loans receivable 25 ShortTermLoansReceivable,LongTermLoansReceivable,ShortTermLoansPayable,NotesLoansReceivable,LoansReceivable,ShortTermNationalBonds,AccountsReceivable,ReserveDepositReceivable,LongTermLoansPayable,LoansPayable-short-term national bonds 9 ShortTermNationalBonds,ShortTermNationalBondsPayable,LongTermNationalBonds,LongTermNationalBondsPayable,ShortTermLoansReceivable,ShortTermLoansPayable,NationalBondInterestEarned,GainOnNationalSubsidies,HeldToMaturityBonds-short-term national bonds payable 22 ShortTermNationalBondsPayable,ShortTermNationalBonds,LongTermNationalBondsPayable,LongTermNationalBonds,ShortTermLoansPayable,ShortTermLoansReceivable,LongTermLoansPayable,LoansPayable,DepositPayable,ReserveDepositPayable+short-term national bonds 10 ShortTermNationalBonds,ShortTermNationalBondsPayable,LongTermNationalBonds,LongTermNationalBondsPayable,ShortTermLoansReceivable,ShortTermLoansPayable,CentralBankPaymentExpense,NationalBondInterestEarned,GainOnNationalSubsidies,HeldToMaturityBonds+short-term national bonds payable 23 ShortTermNationalBondsPayable,ShortTermNationalBonds,LongTermNationalBondsPayable,LongTermNationalBonds,ShortTermLoansPayable,ShortTermLoansReceivable,LongTermLoansPayable,LoansPayable,DepositPayable,ReserveDepositPayable shorttermloanspayable 1 ShortTermLoansPayable shorttermloansreceivable 1 ShortTermLoansReceivable shorttermnationalbonds 2 ShortTermNationalBonds,ShortTermNationalBondsPayable@@ -1509,7 +1513,7 @@ side 4 ReserveDepositReceivable,ReserveDepositPayable,AllowanceForDoubtfulAccounts,AccumulatedDepreciation smaller 1 ReversalOfAllowanceForDoubtfulAccounts software 3 Software,SoftwareInProgress,AmortizationOfSoftware-software in progress 90 SoftwareInProgress,ConstructionInProgress,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment+software in progress 89 SoftwareInProgress,ConstructionInProgress,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment softwareinprogress 1 SoftwareInProgress special 1 DepositsInSpecialAccounts statement 3 GrossProfit,OrdinaryProfit,CashOverShort@@ -1534,8 +1538,10 @@ subsidyexpense 1 SubsidyExpense subsidyincome 1 SubsidyIncome subtotal 2 GrossProfit,OrdinaryProfit+subtotal: 2 GrossProfit,OrdinaryProfit summary 1 IncomeSummary-supplies 2 SuppliesExpenses,SuppliesOnHand+supplies expense 74 SuppliesExpenses,Depreciation,AmortizationExpense,SalesCost,BusinessTrip,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses,MiscellaneousExpenses+supplies on hand 98 SuppliesOnHand,MerchandiseInventory,LossOnValuationOfMerchandise,LongTermNationalBonds,ShortTermNationalBonds,Products,LongTermLoansReceivable,LongTermLoansPayable,ReserveForDepreciation,LongTermNationalBondsPayable suppliesexpenses 1 SuppliesExpenses suppliesonhand 1 SuppliesOnHand surplus 4 LegalCapitalSurplus,OtherCapitalSurplus,CapitalSurplus,EarnedSurplus@@ -1555,8 +1561,8 @@ the 19 InvestmentInAssociate,NetIncome,GrossProfit,OrdinaryProfit,NetLoss,MerchandiseInventory,OtherReceivables,OtherPayables,AllowanceForDoubtfulAccounts,AccumulatedDepreciation time deposits 12 TimeDeposits,Deposits,CurrentDeposits,ReserveDepositReceivable,DepositPayable,ReserveDepositPayable,DepositsReceived,SecurityDepositsPaid,DepositsInSpecialAccounts,GuaranteeDepositsReceived timedeposits 1 TimeDeposits-to 22 Products,StockInvestment,CapitalStock,CentralBankPaymentExpense,GrossProfit,OrdinaryProfit,CentralBankPaymentIncome,MerchandiseInventory,ToolsAndInstruments,StockSubscriptionDeposits-tools and instruments 18 ToolsAndInstruments,Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand+to 22 Products,StockInvestment,CapitalStock,CentralBankPaymentExpense,GrossProfit,OrdinaryProfit,MerchandiseInventory,ToolsAndInstruments,StockSubscriptionDeposits,InterestOnSecurities+tools and instruments 19 ToolsAndInstruments,Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand toolsandinstruments 1 ToolsAndInstruments trademark 1 Trademark trading securities 12 TradingSecurities,Securities,InvestmentSecurities,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnValuationOfSecurities,InterestOnSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnValuationOfSecurities@@ -1564,8 +1570,8 @@ transit 1 GoodsInTransit translation 1 CumulativeTranslationAdjustment transportation 1 BusinessTrip-travel and transportation 18 BusinessTrip,Products,Machinery,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand,ToolsAndInstruments-treasury 2 CentralBankPaymentExpense,CentralBankPaymentIncome+travel and transportation 19 BusinessTrip,Products,Machinery,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand,ToolsAndInstruments+treasury 1 CentralBankPaymentExpense under 3 InvestmentInAssociate,MerchandiseInventory,AccumulatedDepreciation unearned revenue 40 UnearnedRevenue,ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome unearnedrevenue 1 UnearnedRevenue@@ -1577,8 +1583,8 @@ utilities 1 UtilitiesExpense utilitiesexpense 1 UtilitiesExpense valuation 6 AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities,LossOnValuationOfMerchandise,LossOnValuationOfSecurities-valuation difference on available-for-sale securities 102 ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities,LossOnValuationOfSecurities,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,GainOnSalesOfSecurities,InterestOnSecurities,GainOnSalesOfInvestmentSecurities,LossOnValuationOfMerchandise,LossOnSalesOfSecurities-valuation loss on goods 103 LossOnValuationOfMerchandise,LossOnValuationOfSecurities,NetLoss,MerchandiseInventory,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities+valuation difference on available-for-sale securities 99 ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities,LossOnValuationOfSecurities,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,GainOnSalesOfSecurities,InterestOnSecurities,GainOnSalesOfInvestmentSecurities,LossOnValuationOfMerchandise,LossOnSalesOfSecurities+valuation loss on goods 100 LossOnValuationOfMerchandise,LossOnValuationOfSecurities,NetLoss,MerchandiseInventory,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities valuationdifferenceonothersecurities 1 ValuationDifferenceOnOtherSecurities value 12 NetIncome,ValueAdded,GrossProfit,OrdinaryProfit,NetLoss,SuspensePayments,SuspenseReceipts,AllowanceForDoubtfulAccounts,IncomeSummary,SuspenseAccount value added 12 ValueAdded,NetIncome,GrossProfit,OrdinaryProfit,NetLoss,SuspensePayments,SuspenseReceipts,AllowanceForDoubtfulAccounts,IncomeSummary,SuspenseAccount@@ -1592,26 +1598,26 @@ wages 1 WageExpenditure warranties 3 AllowanceForProductWarranties,ReversalOfAllowanceForProductWarranties,ProvisionForProductWarranties welfare 2 WelfareExpenses,StatutoryWelfareExpenses-welfare expenses 25 WelfareExpenses,StatutoryWelfareExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses+welfare expenses 24 WelfareExpenses,StatutoryWelfareExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses welfareexpenses 2 WelfareExpenses,StatutoryWelfareExpenses when 3 ReversalOfAllowanceForDoubtfulAccounts,BranchCurrentAccount,HeadOfficeCurrentAccount which 1 MerchandiseInventory-work in process 88 WorkInProcess,EquityInEarningsOfInvestee,CumulativeTranslationAdjustment,NetIncomeAttributableToNCI,NetLossAttributableToNCI,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery+work in process 87 WorkInProcess,EquityInEarningsOfInvestee,CumulativeTranslationAdjustment,NetIncomeAttributableToNCI,NetLossAttributableToNCI,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery workinprocess 1 WorkInProcess worksheets. 2 EquityInEarningsOfInvestee,CumulativeTranslationAdjustment worksheets; 2 NetIncomeAttributableToNCI,NetLossAttributableToNCI written 1 RecoveryOfBadDebts-— 6 ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,AmortizationExpense,Commutation+— 5 ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,AmortizationExpense が本科目を買掛金の代用にしていた経緯あり) 1 ReserveDepositPayable その他有価証券 2 ValuationDifferenceOnOtherSecurities,AvailableForSaleSecurities その他有価証券評価差額金 1 ValuationDifferenceOnOtherSecurities その他資本剰余金 1 OtherCapitalSurplus-では 2 Products,Commutation+では 1 Products と区別される) 1 AmortizationExpense のれん 3 Goodwill,GainOnBargainPurchase,AmortizationOfGoodwill のれん償却 1 AmortizationOfGoodwill-を使う 4 Products,ReserveForDepreciation,ReserveDepositPayable,Commutation-を使う) 2 ReserveForDepreciation,Commutation+を使う 3 Products,ReserveForDepreciation,ReserveDepositPayable+を使う) 1 ReserveForDepreciation を使うこと 1 ReserveDepositPayable クレジット売掛金 1 CreditCardReceivable ソフトウェア 4 AmortizationExpense,Software,SoftwareInProgress,AmortizationOfSoftware@@ -1718,6 +1724,7 @@ 当期純損失 2 NetLoss,NetLossAttributableToNCI 役務原価 1 CostOfServices 役務収益 1 ServiceRevenue+役員報酬 1 DirectorsCompensations 役員預り金 1 DepositsReceivedFromOfficers 手形借入金 1 NotesLoansPayable 手形売却損 1 LossOnSalesOfNotesReceivable@@ -1738,7 +1745,6 @@ 新築積立金 1 ConstructionFundReserve 新聞図書費 1 NewspaperBooksExpenses 旅費交通費 1 BusinessTrip-旧称。新規コードでは 1 Commutation 普通預金 1 Deposits 有価証券 12 Securities,InvestmentSecurities,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnValuationOfSecurities,InterestOnSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities 有価証券利息 1 InterestOnSecurities@@ -1833,7 +1839,7 @@ 退職給付に係る資産 1 NetDefinedBenefitAsset 退職給付引当金 1 AllowanceForRetirementBenefits 退職給付費用 1 RetirementBenefitExpenses-通信費 2 Commutation,CommunicationExpenses+通信費 1 CommunicationExpenses 還付法人税等 2 IncomeTaxesRefundReceivable,RefundOfIncomeTaxes 配当平均積立金 1 DividendEqualizationReserve 金 75 Cash,Deposits,CurrentDeposits,LongTermLoansReceivable,AccountsReceivable,ShortTermLoansReceivable,ReserveDepositReceivable,Gold,CapitalStock,RetainedEarnings
+ test/fixtures/export-surface-p2/ExchangeAlgebra.Accounting.Account.Jcci.txt view
@@ -0,0 +1,234 @@+AccountsPayable+AccountsReceivable+AccruedConsumptionTax+AccruedCorporateIncomeTaxes+AccruedExpenses+AccruedRevenue+AccumulatedDepreciation+AdditionalIncomeTaxesForPriorPeriods+AdvancesPaid+AdvancesReceived+AdvertisingExpense+AffiliateStocks+AllowanceForBonuses+AllowanceForDoubtfulAccounts+AllowanceForProductWarranties+AllowanceForRepairs+AllowanceForRetirementBenefits+AmortizationExpense+AmortizationOfGoodwill+AmortizationOfPatents+AmortizationOfSoftware+AnyJcci+AvailableForSaleSecurities+BadDebtLoss+BankOverdraft+Bonuses+BonusesPayable+BranchCurrentAccount+Building+BusinessCommencementExpenses+BusinessTrip+CapitalStock+CapitalSurplus+Cash+CashOverShort+CommunicationExpenses+ConstructionFundReserve+ConstructionInProgress+ConsumptionTaxPaid+ConsumptionTaxReceived+ConsumptionTaxRefundReceivable+ContraAccountForGuaranteeObligations+ContractAssets+CorporateIncomeTaxes+CostOfServices+CreditCardReceivable+CumulativeTranslationAdjustment+CurrentDeposits+DeferredTaxAssets+DeferredTaxLiabilities+DeliveryExpenses+DepositInterestEarned+Deposits+DepositsInSpecialAccounts+DepositsReceived+DepositsReceivedFromOfficers+Depreciation+DevelopmentExpenses+DirectorsCompensations+DishonoredNotesReceivable+DividendEqualizationReserve+DividendsReceived+EarnedSurplus+ElectronicallyRecordedObligations+ElectronicallyRecordedReceivable+EntertainmentExpenses+EquipmentInvestment+EquityInEarningsOfInvestee+Fixtures+ForeignExchangeGains+ForeignExchangeLosses+GainOnBargainPurchase+GainOnConstructionGrants+GainOnDonationOfFixedAssets+GainOnNationalSubsidies+GainOnSalesOfFixedAssets+GainOnSalesOfInvestmentSecurities+GainOnSalesOfSecurities+GainOnValuationOfSecurities+GeneralReserve+GiftCertificatesReceived+Gold+GoodsInTransit+Goodwill+GrossProfit+GuaranteeDepositsReceived+GuaranteeObligations+HeadOfficeCurrentAccount+HeldToMaturityBonds+IncomeSummary+IncomeTaxesAdjustment+IncomeTaxesRefundReceivable+IncorporationExpenses+InsuranceExpense+InsuranceGain+InterestEarned+InterestExpense+InterestOnSecurities+InventoryShrinkageLoss+InvestmentInAssociate+InvestmentSecurities+JcciTitles+Land+LandRentPaid+LandRentReceived+LeaseExpenses+LeaseObligations+LeasedAssets+LeaseholdRights+LegalCapitalSurplus+LegalRetainedEarnings+LoansPayable+LoansReceivable+LongTermLoansPayable+LongTermLoansReceivable+LongTermNationalBonds+LongTermNationalBondsPayable+LongTermOtherPayables+LongTermPrepaidExpenses+LossOnFire+LossOnReductionOfFixedAssets+LossOnRetirementOfFixedAssets+LossOnSalesOfElectronicallyRecordedReceivables+LossOnSalesOfFixedAssets+LossOnSalesOfInvestmentSecurities+LossOnSalesOfNotesReceivable+LossOnSalesOfReceivables+LossOnSalesOfSecurities+LossOnValuationOfMerchandise+LossOnValuationOfSecurities+Machinery+MaintenanceExpenses+MeetingExpenses+MembershipFees+MerchandiseInventory+MiscellaneousExpenses+MiscellaneousIncome+MiscellaneousLoss+NationalBondInterestEarned+NetDefinedBenefitAsset+NetDefinedBenefitLiability+NetIncome+NetIncomeAttributableToNCI+NetLoss+NetLossAttributableToNCI+NewspaperBooksExpenses+NonControllingInterests+NonOperatingElectronicallyRecordedObligations+NonOperatingElectronicallyRecordedReceivable+NonOperatingNotesPayable+NonOperatingNotesReceivable+NotesLoansPayable+NotesLoansReceivable+NotesPayable+NotesReceivable+OperatingExpenses+OperatingRevenue+OrdinaryProfit+OtherCapitalSurplus+OtherPayables+OtherReceivables+Patent+PaymentFees+PaymentsOnBehalf+PettyCash+PrepaidCorporateIncomeTaxes+PrepaidExpenses+PrepaidPensionCost+Products+PropertyTaxPayable+ProvisionForBonuses+ProvisionForDoubtfulAccounts+ProvisionForProductWarranties+ProvisionForRepairs+PurchaseAllowances+PurchaseRebates+Purchases+RawMaterials+ReceiptFee+RecoveryOfBadDebts+RefundLiabilities+RefundOfIncomeTaxes+RentExpense+RentalIncome+RepairFundReserve+RepairsExpense+ResearchAndDevelopmentExpenses+RetainedEarnings+RetirementBenefitExpenses+ReversalOfAllowanceForBonuses+ReversalOfAllowanceForDoubtfulAccounts+ReversalOfAllowanceForProductWarranties+ReversalOfAllowanceForRepairs+Sales+SalesAllowances+SalesCost+SalesRebates+Securities+SecurityDepositsPaid+ServiceRevenue+ShortTermLoansPayable+ShortTermLoansReceivable+ShortTermNationalBonds+ShortTermNationalBondsPayable+Software+SoftwareInProgress+StatutoryWelfareExpenses+StockInvestment+StockIssuanceCosts+StockSubscriptionDeposits+StorageExpenses+Structures+SubsidiaryStocks+SuppliesExpenses+SuppliesOnHand+SuspenseAccount+SuspensePayments+SuspenseReceipts+TaxesExpense+TimeDeposits+ToolsAndInstruments+Trademark+TradingSecurities+UnearnedRevenue+UnpaidDividends+UtilitiesExpense+ValuationDifferenceOnOtherSecurities+Vehicle+WageExpenditure+WelfareExpenses+WorkInProcess+narrow+narrowAlg+widen
− test/fixtures/export-surface-p2/ExchangeAlgebra.Accounting.PostingPolicy.txt
@@ -1,7 +0,0 @@-ClosingProcess-ConsolidationWorksheet-EngineComputation-OrdinaryJournal-ProcessingContext-postingAllowedIn-postingCapabilityFor
test/fixtures/export-surface-p2/ExchangeAlgebra.Accounting.txt view
@@ -44,11 +44,17 @@ CentralBankNotePayable CentralBankPaymentExpense CentralBankPaymentIncome+ClosingError ClosingFlip ClosingKeep ClosingSide+ClosingTargetIsContra+ClosingTargetIsWildcard+ClosingTargetNotEquity+ClosingTargetViolation+ClosingTargetWithoutSpec+ClosingTransferError CommunicationExpenses-Commutation ConstructionFundReserve ConstructionInProgress ConsumptionExpenditure@@ -77,8 +83,8 @@ DepositsReceivedFromOfficers Depreciation DevelopmentExpenses+DirectorsCompensations DishonoredNotesReceivable-DivBy DividendEqualizationReserve DividendsReceived EarnedSurplus@@ -124,9 +130,10 @@ InterestEarned InterestExpense InterestOnSecurities-InvalidCoefficient+InvalidClosingTarget InvalidPortion InvalidPosting+InvalidSettleTarget InventoryShrinkageLoss InvestmentInAssociate InvestmentSecurities@@ -168,7 +175,6 @@ MiscellaneousExpenses MiscellaneousIncome MiscellaneousLoss-MulBy NationalBondInterestEarned NetDefinedBenefitAsset NetDefinedBenefitLiability@@ -257,6 +263,7 @@ SignedNet Software SoftwareInProgress+StandardBase StatutoryWelfareExpenses StockInvestment StockIssuanceCosts@@ -274,6 +281,7 @@ TaxesExpense TaxesRevenue TimeDeposits+TitleOf ToolsAndInstruments Trademark TradingSecurities@@ -309,6 +317,7 @@ classifyAccountDivision closingEntries closingSide+closingTargetViolation collapseEntries collapseNetEntries decL@@ -318,7 +327,6 @@ defaultSide diffRL diffRLWithin-divideBy fixedCurrent getAccountTitle isContra@@ -327,7 +335,6 @@ pimoFlip pimoFromDivision projByAccountTitle-projCapitalStock projContra projContraAssets projCredit@@ -337,13 +344,12 @@ projDeferredAssets projFixedAssets projFixedLiability-relabel+projNonContraCreditEquity retainedEarningsRule ruleFrom ruleScale ruleTo rulesToList-scaleBy setAccountTitle settleEntries settlementSteps
− test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Base.Account.JcciAliases.txt
@@ -1,1 +0,0 @@-jcciAliases
− test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Base.Account.Registry.txt
@@ -1,23 +0,0 @@-AccountSemantics-AccountSpec-accountAliases-accountDescriptions-accountSemantics-accountSpec-accountSpecMap-asAliases-asClosing-asDescription-asDivision-asFixedCurrent-asIsContra-asLabelJa-asNameEn-asNameJa-asemDivisionSemantics-asemHomeSideSemantics-asemPostingCapability-asemReportingEligibility-asemRoles-classifyAccountContra-concreteAccountTitles
− test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Base.Account.Types.txt
@@ -1,46 +0,0 @@-AccountDivision-AccountRole-Assets-AttributionAccount-BookkeepingControlClass-CloseByDivision-ClosingDevice-ClosingOnly-ClosingRule-ConsolidationOnly-ContextDependentHomeSide-ContextualPresentation-ContraAccount-Cost-Credit-Current-Debit-DerivedPresentation-DirectionEncoding-DivisionSemantics-EngineGeneratedOnly-Equity-Fixed-FixedCurrent-FixedHomeSide-HomeSideSemantics-Liability-NoClose-NoFixedHomeSide-NoPostingSide-NoStatementDivision-NotPostable-NotPresented-OrdinaryAccount-OrdinaryPosting-Other-PeriodResult-PostingCapability-ReciprocalAccount-ReportingEligibility-ReportingSubtotal-Revenue-Side-StatementDivision-StatementEligible-SuspenseOrClearingAccount
− test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Base.Element.txt
@@ -1,277 +0,0 @@-.#-./=-.<-.<=-.==-.>-.>=-AccountTitle-AccountTitles-AccountsPayable-AccountsReceivable-AccruedConsumptionTax-AccruedCorporateIncomeTaxes-AccruedExpenses-AccruedRevenue-AccumulatedDepreciation-AdditionalIncomeTaxesForPriorPeriods-AdvancesPaid-AdvancesReceived-AdvertisingExpense-AffiliateStocks-AllowanceForBonuses-AllowanceForDoubtfulAccounts-AllowanceForProductWarranties-AllowanceForRepairs-AllowanceForRetirementBenefits-AmortizationExpense-AmortizationOfGoodwill-AmortizationOfPatents-AmortizationOfSoftware-Amount-AvailableForSaleSecurities-AxisDecompose-AxisKey-BadDebtLoss-BankOverdraft-Bonuses-BonusesPayable-BranchCurrentAccount-Building-BusinessCommencementExpenses-BusinessTrip-CNY-CapitalStock-CapitalSurplus-Cash-CashOverShort-CentralBankNotePayable-CentralBankPaymentExpense-CentralBankPaymentIncome-CommunicationExpenses-Commutation-ConstructionFundReserve-ConstructionInProgress-ConsumptionExpenditure-ConsumptionTaxPaid-ConsumptionTaxReceived-ConsumptionTaxRefundReceivable-ContraAccountForGuaranteeObligations-ContractAssets-CorporateIncomeTaxes-CostOfServices-CountUnit-CreditCardReceivable-CumulativeTranslationAdjustment-CurrentDeposits-DeferredTaxAssets-DeferredTaxLiabilities-DeliveryExpenses-DepositInterestEarned-DepositPayable-Deposits-DepositsInSpecialAccounts-DepositsReceived-DepositsReceivedFromOfficers-Depreciation-DevelopmentExpenses-DishonoredNotesReceivable-DividendEqualizationReserve-DividendsReceived-Dollar-EarnedSurplus-ElectronicallyRecordedObligations-ElectronicallyRecordedReceivable-Element-EntertainmentExpenses-EquipmentInvestment-EquityInEarningsOfInvestee-Euro-Fixtures-ForeignExchangeGains-ForeignExchangeLosses-GainOnBargainPurchase-GainOnConstructionGrants-GainOnDonationOfFixedAssets-GainOnNationalSubsidies-GainOnSalesOfFixedAssets-GainOnSalesOfInvestmentSecurities-GainOnSalesOfSecurities-GainOnValuationOfSecurities-GeneralReserve-Generic-GiftCertificatesReceived-Gold-GoodsInTransit-Goodwill-GovernmentService-GrossProfit-GuaranteeDepositsReceived-GuaranteeObligations-Hashable-HeadOfficeCurrentAccount-HeldToMaturityBonds-IncomeSummary-IncomeTaxesAdjustment-IncomeTaxesRefundReceivable-IncorporationExpenses-InsuranceExpense-InsuranceGain-InterestEarned-InterestExpense-InterestOnSecurities-InventoryShrinkageLoss-InvestmentInAssociate-InvestmentSecurities-Land-LandRentPaid-LandRentReceived-LeaseExpenses-LeaseObligations-LeasedAssets-LeaseholdRights-LegalCapitalSurplus-LegalRetainedEarnings-LoansPayable-LoansReceivable-LongTermLoansPayable-LongTermLoansReceivable-LongTermNationalBonds-LongTermNationalBondsPayable-LongTermOtherPayables-LongTermPrepaidExpenses-LossOnFire-LossOnReductionOfFixedAssets-LossOnRetirementOfFixedAssets-LossOnSalesOfElectronicallyRecordedReceivables-LossOnSalesOfFixedAssets-LossOnSalesOfInvestmentSecurities-LossOnSalesOfNotesReceivable-LossOnSalesOfReceivables-LossOnSalesOfSecurities-LossOnValuationOfMerchandise-LossOnValuationOfSecurities-Machinery-MaintenanceExpenses-MeetingExpenses-MembershipFees-MerchandiseInventory-MiscellaneousExpenses-MiscellaneousIncome-MiscellaneousLoss-Name-NationalBondInterestEarned-NetDefinedBenefitAsset-NetDefinedBenefitLiability-NetIncome-NetIncomeAttributableToNCI-NetLoss-NetLossAttributableToNCI-NewspaperBooksExpenses-NonControllingInterests-NonOperatingElectronicallyRecordedObligations-NonOperatingElectronicallyRecordedReceivable-NonOperatingNotesPayable-NonOperatingNotesReceivable-NotesLoansPayable-NotesLoansReceivable-NotesPayable-NotesReceivable-OperatingExpenses-OperatingRevenue-OrdinaryProfit-OtherCapitalSurplus-OtherPayables-OtherReceivables-Patent-PaymentFees-PaymentsOnBehalf-PettyCash-PrepaidCorporateIncomeTaxes-PrepaidExpenses-PrepaidPensionCost-Products-PropertyTaxPayable-ProvisionForBonuses-ProvisionForDoubtfulAccounts-ProvisionForProductWarranties-ProvisionForRepairs-PurchaseAllowances-PurchaseRebates-Purchases-RawMaterials-ReceiptFee-RecoveryOfBadDebts-RefundLiabilities-RefundOfIncomeTaxes-RentExpense-RentalIncome-RepairFundReserve-RepairsExpense-ResearchAndDevelopmentExpenses-ReserveDepositPayable-ReserveDepositReceivable-ReserveForDepreciation-RetainedEarnings-RetirementBenefitExpenses-ReversalOfAllowanceForBonuses-ReversalOfAllowanceForDoubtfulAccounts-ReversalOfAllowanceForProductWarranties-ReversalOfAllowanceForRepairs-Sales-SalesAllowances-SalesCost-SalesRebates-Securities-SecurityDepositsPaid-ServiceRevenue-ShortTermLoansPayable-ShortTermLoansReceivable-ShortTermNationalBonds-ShortTermNationalBondsPayable-Software-SoftwareInProgress-StatutoryWelfareExpenses-StockInvestment-StockIssuanceCosts-StockSubscriptionDeposits-StorageExpenses-Structures-Subject-SubsidiaryStocks-SubsidyExpense-SubsidyIncome-SuppliesExpenses-SuppliesOnHand-SuspenseAccount-SuspensePayments-SuspenseReceipts-TaxesExpense-TaxesRevenue-TimeDeposits-ToolsAndInstruments-Trademark-TradingSecurities-UnearnedRevenue-UnpaidDividends-UtilitiesExpense-ValuationDifferenceOnOtherSecurities-ValueAdded-Vehicle-WageEarned-WageExpenditure-WelfareExpenses-WorkInProcess-Yen-axisIsWildcard-compareElement-equal-hash-hashWithSalt-haveWildcard-ignoreWildcard-isWildcard-maxElement-minElement-toAxisKeys-wildcard
test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Base.txt view
@@ -7,8 +7,6 @@ .>= :< Amount-AxisDecompose-AxisKey BaseClass BaseForSingleHat BasePart@@ -16,9 +14,11 @@ CountUnit Dollar Element+ElementKey Euro Exactly Generic+HasElementKeys Hashable Hat HatBase@@ -31,12 +31,12 @@ Yen _base _hat-axisIsWildcard base compareBase compareElement compareHatBase customError+elementKeyIsWildcard equal hash hashWithSalt@@ -50,7 +50,7 @@ merge minElement revHat-toAxisKeys+toElementKeys toHat toNot wildcard
test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Internal.txt view
@@ -17,8 +17,6 @@ Accum Alg Amount-AxisDecompose-AxisKey BaseClass BaseForSingleHat BasePart@@ -26,20 +24,25 @@ CountUnit Dollar Element+ElementKey Euro Exactly Generic+HasElementKeys Hashable Hat HatBase HatBaseClass HatNot+HatOne HatVal Liner Name Nearly Not+NotOne Pair+PairSeq Redundant Single Subject@@ -59,7 +62,6 @@ _realg _val addAccum-axisIsWildcard balanceBy balanceMapBy bar@@ -72,6 +74,7 @@ compress customError decBy+elementKeyIsWildcard emptyAccum equal exactAccum@@ -118,7 +121,7 @@ signAccum splitAccum toASCList-toAxisKeys+toElementKeys toHat toList toNot
− test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Transfer.Rule.txt
@@ -1,36 +0,0 @@-ClosingFlip-ClosingKeep-ClosingSide-DivBy-InvalidCoefficient-MulBy-NonFiniteBalance-NonFiniteNet-NonFiniteResult-OverlappingRules-Relabel-SettleError-SettleRule-SettlementBatch-SignedNet-TransferApplyError-TransferRule-TransferRuleError-TransferRules-TransferScale-closingEntries-closingSide-collapseEntries-collapseNetEntries-divideBy-mkTransferRules-relabel-retainedEarningsRule-ruleFrom-ruleScale-ruleTo-rulesToList-scaleBy-settleEntries-settlementSteps-transferEntries
test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.Transfer.txt view
@@ -1,4 +1,3 @@-InvalidCoefficient NonFiniteBalance NonFiniteResult OverlappingRules
test/fixtures/export-surface-p2/ExchangeAlgebra.Algebra.txt view
@@ -17,8 +17,6 @@ Accum Alg Amount-AxisDecompose-AxisKey BaseClass BaseForSingleHat BasePart@@ -26,9 +24,11 @@ CountUnit Dollar Element+ElementKey Euro Exactly Generic+HasElementKeys Hashable Hat HatBase@@ -56,7 +56,6 @@ _val absTol addAccum-axisIsWildcard balanceBy balanceMapBy bar@@ -70,6 +69,7 @@ customError decBy defaultTolerance+elementKeyIsWildcard emptyAccum equal exactAccum@@ -119,7 +119,7 @@ splitAccum sumValues toASCList-toAxisKeys+toElementKeys toHat toList toNot
− test/fixtures/export-surface-p2/ExchangeAlgebra.Assist.Descriptions.txt
@@ -1,1 +0,0 @@-accountDescriptions
− test/fixtures/export-surface-p2/ExchangeAlgebra.Assist.txt
@@ -1,16 +0,0 @@-AccountInfo-aiDesc-aiDivisionSemantics-aiHomeSideSemantics-aiNameEn-aiNameJa-aiPostingCapability-aiReportingEligibility-aiRoles-aiTitle-allAccountInfos-describeAccount-explainEntryError-explainJournalErrors-explainSourceErrors-suggestAccounts
− test/fixtures/export-surface-p2/ExchangeAlgebra.Bookkeeping.txt
@@ -1,19 +0,0 @@-MkBase-accruedExpenseEntry-accruedRevenueEntry-allowanceReplenishmentEntry-allowanceResetEntries-cogsAdjustmentEntries-consumptionTaxSettlementEntry-corporateTaxInterimEntry-corporateTaxSettlementEntries-depreciationDirectEntry-depreciationIndirectEntry-equityMethodBalance-equityMethodDividendEntry-equityMethodEarningsEntry-equityMethodEntries-prepaidExpenseEntry-priorPeriodErrorCorrection-reversingEntry-unearnedRevenueEntry
− test/fixtures/export-surface-p2/ExchangeAlgebra.Consolidation.Worksheet.txt
@@ -1,73 +0,0 @@-AccountBalance-AdjustmentPostingNotAllowed-BalanceSheetNonControllingInterests-BalanceSheetNonControllingInterestsMismatch-BalanceSheetRetainedEarnings-BalanceSheetRetainedEarningsMismatch-CreditBalance-DebitBalance-DuplicateAdjustmentId-DuplicateAdjustmentSource-DuplicateSourceId-EmptyAdjustment-InvalidAdjustmentValue-InvalidLinkAmount-InvalidSourceValue-LinkField-NetIncomeAttributionMismatch-NoBalance-NonControllingInterestsDividends-NonControllingInterestsPeriodShare-NonControllingInterestsRollForwardMismatch-OpeningNonControllingInterests-OpeningRetainedEarnings-OwnersPeriodResultLinkMismatch-PeriodBreakEven-PeriodLoss-PeriodProfit-PeriodResult-ProfitOrLossNetIncome-ProfitOrLossNetIncomeAttributableToOwners-RetainedEarningsDividends-RetainedEarningsRollForwardMismatch-StatementOfChangesClosingNonControllingInterests-StatementOfChangesClosingRetainedEarnings-StatementOfChangesNetIncomeAttributableToOwners-TrialBalanceSource-UnbalancedAdjustment-UnbalancedSourceTrialBalance-UnknownAdjustmentSource-ValidatedWorksheet-WildcardAdjustmentAccount-WildcardAdjustmentSide-WildcardSourceAccount-WildcardSourceSide-WorksheetAdjustment-WorksheetError-WorksheetInput-WorksheetLinkage-_adjustmentElement-_adjustmentId-_adjustmentSourceIds-_balanceSheetNonControllingInterests-_balanceSheetRetainedEarnings-_nonControllingInterestsDividends-_nonControllingInterestsPeriodShare-_openingNonControllingInterests-_openingRetainedEarnings-_profitOrLossNetIncome-_profitOrLossNetIncomeAttributableToOwners-_retainedEarningsDividends-_sourceId-_sourceTrialBalance-_statementOfChangesClosingNonControllingInterests-_statementOfChangesClosingRetainedEarnings-_statementOfChangesNetIncomeAttributableToOwners-_worksheetAdjustments-_worksheetLinkage-_worksheetSources-combinedWorksheet-validateConsolidationWorksheet-validatedAdjustments-validatedLinkage-validatedSources
− test/fixtures/export-surface-p2/ExchangeAlgebra.Convert.Checked.txt
@@ -1,40 +0,0 @@-AmountMismatch-BalancedUnresolved-ClosingProcess-ConsolidationWorksheet-DuplicateTxId-EmptyEntry-EngineComputation-EntryError-EntryErrors-EntryParse-FullyResolved-Imbalanced-JournalCert-JournalError-MissingSource-NonPositiveAmount-OrdinaryJournal-PostingNotAllowed-ProcessingContext-Rejected-SourceError-UnknownSource-WildcardAccount-WildcardSide-_certCreditTotal-_certDebitTotal-_certResolved-_certUnresolved-_creditTotal-_debitTotal-certifyJournalText-certifyJournalTextIn-checkedEntry-checkedEntryIn-checkedEntryText-checkedEntryTextIn-checkedJournal-checkedJournalIn-postingAllowedIn-reconcileSources
− test/fixtures/export-surface-p2/ExchangeAlgebra.Convert.Csv.txt
@@ -1,5 +0,0 @@-parseJournalCsv-parseJournalCsvWith-parseNotedJournalCsv-scientificAmount-splitTrim
− test/fixtures/export-surface-p2/ExchangeAlgebra.Convert.txt
@@ -1,13 +0,0 @@-AmbiguousAccount-BadAmount-ConvError-MalformedCsv-UnknownAccount-UnknownSide-concreteAccountTitles-journalFromSides-markerForSide-normalizeTitle-parseAccountTitle-parseSide-postingFromSide
test/fixtures/export-surface-p2/ExchangeAlgebra.Journal.Transfer.Rule.txt view
@@ -10,4 +10,3 @@ notTotal sideTotal sideTotalsBy-transferEntries
test/fixtures/export-surface-p2/ExchangeAlgebra.Journal.txt view
@@ -16,8 +16,6 @@ <+ Accum Amount-AxisDecompose-AxisKey BaseClass BaseForSingleHat BasePart@@ -25,9 +23,11 @@ CountUnit Dollar Element+ElementKey Euro Exactly Generic+HasElementKeys Hashable Hat HatBase@@ -38,8 +38,8 @@ Name Not Note-NoteAxisKey-NoteAxisPosting+NoteFieldIndex+NoteFieldKey Redundant Subject Wild@@ -48,7 +48,6 @@ _base _hat addAccum-axisIsWildcard bar barWithin base@@ -58,10 +57,11 @@ compress customError decTo+elementKeyIsWildcard emptyAccum equal exactAccum-filterByAxis+filterByNoteField filterWithNote fromList fromMap@@ -105,11 +105,11 @@ signAccum splitAccum toAlg-toAxisKeys+toElementKeys toHat toMap toNot-toNoteAxisKeys+toNoteFieldKeys valueError wildcard zeroValue
− test/fixtures/export-surface-p2/ExchangeAlgebra.Posting.txt
@@ -1,13 +0,0 @@-AboveBound-HatSide-InvalidValue-NotSide-PostSide-Posted-PostedError-Posting-entry-posted-postingAlg-sideHat-unPosted
− test/fixtures/export-surface-p2/ExchangeAlgebra.Render.Bookkeeping.txt
@@ -1,12 +0,0 @@-accountLedgerRows-accountLedgerRowsJournal-compoundTrialBalanceRows-journalRows-postClosingTrialBalanceRows-worksheetRows-writeAccountOf-writeAccountOfJournal-writeCompoundTrialBalance-writeJournal-writePostClosingTrialBalance-writeWorksheet
− test/fixtures/export-surface-p2/ExchangeAlgebra.Render.Csv.txt
@@ -1,2 +0,0 @@-csvTranspose-writeCSV
− test/fixtures/export-surface-p2/ExchangeAlgebra.Reporting.Group.txt
@@ -1,36 +0,0 @@-DeductionRow-DepreciableAssetsGroup-GrossRow-GroupRow-GroupRowKind-GroupedPresentation-IncomeTaxesGroup-NetPurchasesGroup-NetRow-NetSalesGroup-PresentationGroup-PresentationGroupDef-RelativeAmount-SubgroupRow-TradeReceivablesGroup-addGross-defaultPresentationGrouping-gpBlocks-gpConsumed-gpRootTotals-grAmount-grKind-groupNormalSide-groupingForDivisions-lookupGroupDef-pgDeductions-pgDivision-pgGross-pgKey-pgLabel-pgParent-presentGroups-presentationGroupOf-raBelowZero-raMagnitude-relativeTo
− test/fixtures/export-surface-p2/ExchangeAlgebra.Reporting.Metric.txt
@@ -1,22 +0,0 @@-CustomMetric-DerivedMetric-GrossProfitMetric-InvalidMetricValue-MetricError-MetricId-MetricNotAvailableAtStage-OrdinaryProfitMetric-PeriodBreakEven-PeriodLoss-PeriodProfit-PeriodResult-PeriodResultMetric-ResidualDerivedCoordinate-WildcardMetricAccount-WildcardMetricSide-legacyTitlesForMetric-metricForLegacyTitle-metricIdText-mkMetricId-periodResultOf-periodResultOfAlg
− test/fixtures/export-surface-p2/ExchangeAlgebra.Reporting.Presentation.txt
@@ -1,111 +0,0 @@-AccountRelabeled-AccountingFramework-BalanceAllocated-BlankPresentationEvidence-BlankPresentationRationale-CanonicalEnglish-CanonicalJapanese-Combined-ConflictingPresentationInstruction-ContextualCreditSection-ContextualDebitSection-ContraPresentationApplied-ContraPresentationRule-CurrentAssetsSection-CurrentLiabilitiesSection-CustomMetricLabel-DuplicateMetricIdentity-DuplicatePresentationAllocation-EquitySection-ExpenseSection-FinancialStatements-InvalidPresentationAllocation-InvalidStatementValue-InvalidSubtotalDefinition-JGAAP-JcciSecondGradeReport-LabelOverridden-MaterialityApplied-MaterialityDecision-MaterialityTreatment-MissingPresentationAccount-MissingPresentationAllocation-NetAgainst-NetContraAgainst-NoncurrentAssetsSection-NoncurrentLiabilitiesSection-PeriodResultUnavailable-PresentContraSeparately-PresentGross-PresentSeparately-PresentationAllocation-PresentationAuditEvent-PresentationIssue-PresentationProfile-PresentationRelabel-ReciprocalAccountsEliminated-ReportingContext-ReportingScope-RequireAllTitlesPresent-RevenueSection-Standalone-StatementLine-StatementSection-StatementSubtotal-SubtotalCalculated-SubtotalCoverage-SubtotalDefinition-TreatAbsentAsZero-UnbalancedStatementInput-UnexpectedPresentationAllocation-UnlabelledCustomMetric-UnpresentableBalance-UnreconciledPresentation-WildcardStatementBase-_allocationAccount-_allocationCurrent-_allocationEvidence-_allocationNoncurrent-_contraPresentationRules-_customMetricIdentity-_customMetricLabelEnglish-_customMetricLabelJapanese-_customMetricLabels-_lineAccount-_lineAmount-_lineIsDeduction-_lineLabel-_lineSection-_lineSide-_materialityAccount-_materialityDecisions-_materialityRationale-_materialityTreatment-_maturitySensitiveTitles-_presentationAllocations-_presentationAudit-_presentationProfile-_presentationRelabels-_relabelRationale-_relabelSource-_relabelTarget-_reportingFramework-_reportingScope-_statementFramework-_statementLines-_statementProfile-_statementScope-_statementSubtotalBalance-_statementSubtotalLabel-_statementSubtotalMetric-_statementSubtotals-_statementTrialBalanceStage-_subtotalCoverage-_subtotalCreditTitles-_subtotalDebitTitles-_subtotalDefinitions-_subtotalMetric-jcciSecondGradeContext-metricLabel-present-presentationLabel
test/fixtures/export-surface-p2/ExchangeAlgebra.Simulate.Policy.txt view
@@ -1,16 +1,16 @@ Compaction CompressClosedTerms FullAudit-HasTermAxis+HasNotePeriod LedgerPolicy+PeriodOf RetainAll RetainRecent Retention-TermOf compaction defaultLedgerPolicy+periodOf policySpillOptions restoreLedger retain spillTo-termOf
− test/fixtures/export-surface-p2/ExchangeAlgebra.TrialBalance.Balance.txt
@@ -1,12 +0,0 @@-AccountBalance-CreditBalance-DebitBalance-NoBalance-accountBalances-addPair-balanceAmount-balanceFor-balancePair-balanceSide-combineBalances-netPair
− test/fixtures/export-surface-p2/ExchangeAlgebra.TrialBalance.Validation.txt
@@ -1,35 +0,0 @@-AbnormalBalanceWithReclassificationRule-AccountBalance-AfterClosing-AmbiguousReclassification-BeforeClosing-BlankTemporaryExplanation-ClosingDeviceResidual-CreditBalance-DebitBalance-DerivedCoordinateResidual-ExplainedTemporaryBalance-InapplicableReclassificationRule-InvalidTrialBalanceValue-MaturityEvidenceRequired-MissingMaturityEvidence-NoBalance-ReciprocalMismatch-ReclassificationRule-SideReclassificationRule-StandaloneReciprocalBalance-TBFinding-TrialBalanceInput-TrialBalanceStage-UnbalancedTrialBalance-UnclosedNominalBalance-UnexplainedAbnormalBalance-UnresolvedTemporaryBalance-WildcardTrialBalanceAccount-WildcardTrialBalanceSide-_maturityEvidenceTitles-_reclassificationRules-_temporaryBalanceExplanations-_trialBalanceElement-_trialBalanceStage-trialBalanceFindings
− test/fixtures/export-surface-p2/ExchangeAlgebra.Value.txt
@@ -1,13 +0,0 @@-MalformedMoney-MoneyDecimal-MoneyDouble-MoneyExponentOutOfRange-MoneyParseError-MoneyScaleOutOfRange-NegativeMoney-bankersRound-ceilingRound-moneyDecimalFromScientific-moneyDecimalFromText-toDecimal-toDouble
test/fixtures/export-surface-p2/ExchangeAlgebra.txt view
@@ -17,7 +17,6 @@ <+ <=> <@-AbnormalBalanceWithReclassificationRule AccountBalance AccountBase AccountDivision@@ -46,7 +45,6 @@ AllowanceForProductWarranties AllowanceForRepairs AllowanceForRetirementBenefits-AmbiguousReclassification AmortizationExpense AmortizationOfGoodwill AmortizationOfPatents@@ -55,8 +53,6 @@ Assets AttributionAccount AvailableForSaleSecurities-AxisDecompose-AxisKey BackwardFlow BadDebtLoss BankOverdraft@@ -66,7 +62,6 @@ BeforeClosing BlankPresentationEvidence BlankPresentationRationale-BlankTemporaryExplanation Bonuses BonusesPayable BookkeepingControlClass@@ -84,15 +79,20 @@ CentralBankPaymentIncome CloseByDivision ClosingDevice-ClosingDeviceResidual+ClosingError ClosingFlip ClosingKeep ClosingOnly ClosingRule ClosingSide+ClosingTargetIsContra+ClosingTargetIsWildcard+ClosingTargetNotEquity+ClosingTargetViolation+ClosingTargetWithoutSpec+ClosingTransferError Combined CommunicationExpenses-Commutation ConflictingPresentationInstruction ConsolidationOnly ConstructionFundReserve@@ -132,12 +132,11 @@ DepositsReceived DepositsReceivedFromOfficers Depreciation-DerivedCoordinateResidual DerivedPresentation DevelopmentExpenses DirectionEncoding+DirectorsCompensations DishonoredNotesReceivable-DivBy DividendEqualizationReserve DividendsReceived DivisionSemantics@@ -148,6 +147,7 @@ ElectronicallyRecordedObligations ElectronicallyRecordedReceivable Element+ElementKey EngineGeneratedOnly EntertainmentExpenses EquipmentInvestment@@ -159,8 +159,8 @@ Exactly Exchange ExpenseSection-ExplainedTemporaryBalance FinancialStatements+FinancialStatementsOf Fixed FixedCurrent FixedHomeSide@@ -185,6 +185,7 @@ GrossProfit GuaranteeDepositsReceived GuaranteeObligations+HasElementKeys Hashable Hat HatBase@@ -195,7 +196,6 @@ HeldToMaturityBonds HomeSideSemantics IN-InapplicableReclassificationRule IncomeSummary IncomeTaxesAdjustment IncomeTaxesRefundReceivable@@ -205,13 +205,13 @@ InterestEarned InterestExpense InterestOnSecurities-InvalidCoefficient+InvalidClosingTarget InvalidPortion InvalidPosting InvalidPresentationAllocation+InvalidSettleTarget InvalidStatementValue InvalidSubtotalDefinition-InvalidTrialBalanceValue InventoryShrinkageLoss InvestmentInAssociate InvestmentSecurities@@ -248,14 +248,12 @@ Machinery MaintenanceExpenses MalformedMoney-MaturityEvidenceRequired MeetingExpenses MembershipFees MerchandiseInventory MiscellaneousExpenses MiscellaneousIncome MiscellaneousLoss-MissingMaturityEvidence MissingPresentationAccount MissingPresentationAllocation MoneyDecimal@@ -263,7 +261,6 @@ MoneyExponentOutOfRange MoneyParseError MoneyScaleOutOfRange-MulBy Name NationalBondInterestEarned Nearest@@ -327,6 +324,7 @@ PrepaidExpenses PrepaidPensionCost PresentationIssue+PresentationIssueOf Products PropertyTaxPayable ProvisionForBonuses@@ -340,8 +338,6 @@ RawMaterials ReceiptFee ReciprocalAccount-ReciprocalMismatch-ReclassificationRule RecoveryOfBadDebts Redundant RefundLiabilities@@ -352,6 +348,7 @@ RepairFundReserve RepairsExpense ReportingContext+ReportingContextOf ReportingEligibility ReportingScope ReportingSubtotal@@ -383,15 +380,15 @@ ShortTermNationalBonds ShortTermNationalBondsPayable Side-SideReclassificationRule SignedNet Software SoftwareInProgress Standalone-StandaloneReciprocalBalance+StandardBase StatementDivision StatementEligible StatementLine+StatementLineOf StatementRowsError StatementSection StatutoryWelfareExpenses@@ -410,10 +407,10 @@ SuspenseOrClearingAccount SuspensePayments SuspenseReceipts-TBFinding TaxesExpense TaxesRevenue TimeDeposits+TitleOf ToMultipleOf Tolerance ToolsAndInstruments@@ -433,20 +430,15 @@ TransferShare TransferTable TransferTableError-TrialBalanceInput TrialBalanceStage UnbalancedStatementInput-UnbalancedTrialBalance UnclassifiedAccount-UnclosedNominalBalance UnearnedRevenue UnexpectedPresentationAllocation-UnexplainedAbnormalBalance UnlabelledCustomMetric UnpaidDividends UnpresentableBalance UnreconciledPresentation-UnresolvedTemporaryBalance UnroundableAmount UtilitiesExpense ValuationDifferenceOnOtherSecurities@@ -459,8 +451,6 @@ Wild WildcardPosting WildcardStatementBase-WildcardTrialBalanceAccount-WildcardTrialBalanceSide WorkInProcess Yen Zero@@ -469,6 +459,7 @@ _customMetricLabels _hat _hatBase+_labelOverrides _lineAccount _lineAmount _lineIsDeduction@@ -476,13 +467,11 @@ _lineSection _lineSide _materialityDecisions-_maturityEvidenceTitles _maturitySensitiveTitles _presentationAllocations _presentationAudit _presentationProfile _presentationRelabels-_reclassificationRules _reportingFramework _reportingScope _statementFramework@@ -492,9 +481,6 @@ _statementSubtotals _statementTrialBalanceStage _subtotalDefinitions-_temporaryBalanceExplanations-_trialBalanceElement-_trialBalanceStage _val absTol accountAliases@@ -520,7 +506,6 @@ asemPostingCapability asemReportingEligibility asemRoles-axisIsWildcard balance balanceAmount balanceBy@@ -538,6 +523,7 @@ classifyAccountDivision closingEntries closingSide+closingTargetViolation collapseEntries collapseNetEntries compareBase@@ -557,7 +543,7 @@ defaultTolerance diffRL diffRLWithin-divideBy+elementKeyIsWildcard emptyAccum equal exactAccum@@ -608,7 +594,6 @@ present proj projByAccountTitle-projCapitalStock projContra projContraAssets projCredit@@ -619,10 +604,11 @@ projFixedAssets projFixedLiability projNetNorm+projNonContraCreditEquity rationalAddAccum rationalRoundAccum relTol-relabel+reportingContext retainedEarningsRule revHat roundAccum@@ -632,7 +618,6 @@ ruleScale ruleTo rulesToList-scaleBy setAccountTitle settleEntries settlementSteps@@ -646,9 +631,9 @@ switchSide tableRows toASCList-toAxisKeys toDecimal toDouble+toElementKeys toHat toList toNot@@ -656,7 +641,6 @@ transferEntriesBy transferEntriesByWith transferEntriesWith-trialBalanceFindings unionsMerge vals valueError
test/fixtures/export-surface-p2/counts.tsv view
@@ -1,36 +1,17 @@ module names-ExchangeAlgebra.Accounting.PostingPolicy 7-ExchangeAlgebra.Accounting 359-ExchangeAlgebra.Algebra.Base.Account.JcciAliases 1-ExchangeAlgebra.Algebra.Base.Account.Registry 23-ExchangeAlgebra.Algebra.Base.Account.Types 46-ExchangeAlgebra.Algebra.Base.Element 277+ExchangeAlgebra.Accounting 365 ExchangeAlgebra.Algebra.Base 56-ExchangeAlgebra.Algebra.Internal 129-ExchangeAlgebra.Algebra.Transfer.Rule 36-ExchangeAlgebra.Algebra.Transfer 18+ExchangeAlgebra.Algebra.Internal 132+ExchangeAlgebra.Algebra.Transfer 17 ExchangeAlgebra.Algebra 130-ExchangeAlgebra.Assist.Descriptions 1-ExchangeAlgebra.Assist 16-ExchangeAlgebra.Bookkeeping 19-ExchangeAlgebra.Consolidation.Worksheet 73-ExchangeAlgebra.Convert.Checked 40-ExchangeAlgebra.Convert.Csv 5-ExchangeAlgebra.Convert 13 ExchangeAlgebra.IO.Input.Admission 19-ExchangeAlgebra.Journal.Transfer.Rule 13+ExchangeAlgebra.Journal.Transfer.Rule 12 ExchangeAlgebra.Journal.Transfer 12 ExchangeAlgebra.Journal 115 ExchangeAlgebra.Optimize.Annealing 10 ExchangeAlgebra.Optimize.GA 14 ExchangeAlgebra.Optimize 8-ExchangeAlgebra.Posting 13-ExchangeAlgebra.Render.Bookkeeping 12-ExchangeAlgebra.Render.Csv 2 ExchangeAlgebra.Render.Simulation 5-ExchangeAlgebra.Reporting.Group 36-ExchangeAlgebra.Reporting.Metric 22-ExchangeAlgebra.Reporting.Presentation 111 ExchangeAlgebra.Simulate.Analysis 2 ExchangeAlgebra.Simulate.Engine 49 ExchangeAlgebra.Simulate.Lite 37@@ -40,7 +21,5 @@ ExchangeAlgebra.Simulate.Spill 37 ExchangeAlgebra.Simulate.Visualize 15 ExchangeAlgebra.Simulate 89-ExchangeAlgebra.TrialBalance.Balance 12-ExchangeAlgebra.TrialBalance.Validation 35-ExchangeAlgebra.Value 13-ExchangeAlgebra 677+ExchangeAlgebra 661+ExchangeAlgebra.Accounting.Account.Jcci 234
test/fixtures/export-surface-p2/orphans.txt view
@@ -1,19 +1,24 @@ examples/basic/elementaryBookkeepingEx4.hs: instance Note Day examples/basic/elementaryBookkeepingEx5.hs: instance Element Company examples/basic/elementaryBookkeepingEx5.hs: instance ExBaseClass HatBaseC+examples/basic/elementaryBookkeepingEx5.hs: type instance TitleOf HatBaseC = AccountTitles -- Defined at basic/elementaryBookkeepingEx5.hs:15:1 examples/basic/fixedPriceIO.hs: instance BaseClass Company examples/basic/fixedPriceIO.hs: instance Element Company examples/basic/fixedPriceIO.hs: instance ExBaseClass HatBase2 examples/basic/fixedPriceIO.hs: instance StateTime Term+examples/basic/fixedPriceIO.hs: type instance TitleOf HatBase2 = AccountTitles -- Defined at basic/fixedPriceIO.hs:134:1 examples/basic/fixedPriceIOSpill.hs: instance BaseClass Company examples/basic/fixedPriceIOSpill.hs: instance Element Company examples/basic/fixedPriceIOSpill.hs: instance ExBaseClass HatBase2 examples/basic/fixedPriceIOSpill.hs: instance StateTime Term+examples/basic/fixedPriceIOSpill.hs: type instance TitleOf HatBase2 = AccountTitles -- Defined at basic/fixedPriceIOSpill.hs:150:1 examples/optimization/CGE/CGE.hs: instance StateTime Term-src/ExchangeAlgebra/Algebra/Base/Element.hs: instance Hashable Day-src/ExchangeAlgebra/Algebra/Base/Element.hs: instance Hashable TimeOfDay+src/ExchangeAlgebra/Algebra/Element/Representation.hs: instance Hashable Day+src/ExchangeAlgebra/Algebra/Element/Representation.hs: instance Hashable TimeOfDay test/Spec.hs: instance BaseClass SimCompany test/Spec.hs: instance Element SimCompany test/Spec.hs: instance ExBaseClass SimHatBase2 test/Spec.hs: instance StateTime SimTerm+test/Support.hs: type instance TitleOf SimHatBase2 = AccountTitles -- Defined at test/Support.hs:122:1 test/Transfer/RuleSpec.hs: instance ExBaseClass TestBase+test/Transfer/RuleSpec.hs: type instance TitleOf TestBase = AccountTitles -- Defined at test/Transfer/RuleSpec.hs:49:1
test/fixtures/jcci-2022/README.md view
@@ -21,14 +21,13 @@ query after `normalizeTitle`: `right` for a unique constructor and `ambiguous` for a deliberate candidate set. Its candidates describe the complete parser contract: JCCI-derived aliases combined with pre-existing EA aliases. Therefore-an A name can remain ambiguous when the same spelling is also a B name, and-legacy constructors such as `Securities`, `InvestmentSecurities`, and-`Commutation` remain visible rather than being silently removed. Shared names-and generic gain/loss names are never resolved by first-match order.+an A name can remain ambiguous when the same spelling is also a B name.+`通信費` resolves to `CommunicationExpenses`. Shared names and generic+gain/loss names are never resolved by first-match order. -The 21 frozen ambiguities are: `銀行預金`, `〇〇商店`, `貸付金`, `仮払金`,+The 20 remaining ambiguities are: `銀行預金`, `〇〇商店`, `貸付金`, `仮払金`, `有価証券`, `投資有価証券`, `関係会社株式`, `借入金`, `未払金`, `仮受金`,-`営業収益`, `有価証券運用益`, `通信費`, `地代家賃`, `支払賃借料`,+`営業収益`, `有価証券運用益`, `地代家賃`, `支払賃借料`, `支払不動産賃借料`, `営業費用`, `有価証券運用損`, `為替差損益`, `有価証券評価損益`, and `有価証券運用損益`. `〇〇商店` is a literal counterparty placeholder in the source; real counterparty names do not become@@ -46,6 +45,7 @@ (accessed 2026-08-16; SHA-256 `ad1691da158429dd5c4ec9a7721bb41ad2ecf55f9e6f27eb483b3722e0d0eb7e`) -The checked fixture is a transcription and mapping decision, not a modified-copy of the source PDF. `tools/gen-jcci-aliases.py` deterministically generates-the Haskell alias overlay from `queries.tsv`.+The test suite compares every `(candidate, query)` pair in `queries.tsv` with+the pairs returned by `jcciAliases` and reports missing or extra pairs. It also+checks that each title's aliases follow the order in which they first occur in+the fixture.
test/fixtures/jcci-2022/queries.tsv view
@@ -212,7 +212,7 @@ 3 費用 A 減価償却費 right Depreciation 減価償却費 3 費用 B 建物減価償却費 right Depreciation 減価償却費 3 費用 B 備品減価償却費 right Depreciation 減価償却費-3 費用 A 通信費 ambiguous CommunicationExpenses|Commutation 通信費+3 費用 A 通信費 right CommunicationExpenses 通信費 3 費用 A 消耗品費 right SuppliesExpenses 消耗品費 3 費用 B 事務用消耗品費 right SuppliesExpenses 消耗品費 3 費用 A 水道光熱費 right UtilitiesExpense 水道光熱費
test/fixtures/jcci-2022/source.tsv view
@@ -156,7 +156,7 @@ 3 費用 貸倒引当金繰入 貸倒引当金繰入額 ProvisionForDoubtfulAccounts EXISTS 3 費用 貸倒損失 BadDebtLoss EXISTS 3 費用 減価償却費 建物減価償却費|備品減価償却費 Depreciation EXISTS-3 費用 通信費 CommunicationExpenses|Commutation AMBIGUOUS_LEGACY+3 費用 通信費 CommunicationExpenses EXISTS 3 費用 消耗品費 事務用消耗品費 SuppliesExpenses EXISTS 3 費用 水道光熱費 光熱水費 UtilitiesExpense EXISTS 3 費用 支払家賃 地代家賃|支払賃借料|支払不動産賃借料 RentExpense EXISTS
test/fixtures/post-vocab/README.md view
@@ -1,8 +1,8 @@ # Post-V-Land-3 vocabulary golden fixtures -These schema-1 TSV files freeze the complete 235-constructor vocabulary after-V-Land 3: Enum ordinals, registry semantics, assistance metadata, and fuzzy-suggestions. They are generated from the Haskell registry, not hand-edited.+These schema-1 TSV files record registry semantics, assistance metadata,+and fuzzy suggestions for the built-in vocabulary. Generate them from+the Haskell registry. Regenerate into a temporary directory and compare before replacing a fixture: @@ -14,4 +14,5 @@ `DumpPostVocabGolden.hs` is intentionally runnable through the root Stack package without a separate installed executable. `testPostVocabGolden` derives-the same rows independently during the test suite and requires byte equality.+the registry semantics, metadata, and suggestions independently during the+test suite and requires byte equality.
test/fixtures/post-vocab/account-info.tsv view
@@ -9,7 +9,7 @@ ShortTermNationalBonds Assets Debit Short-term national bonds 短期国債 Asset: Short-term national bonds (短期国債) Products Assets Debit Products 商品 Asset: Products (商品)。分記法用。3 分法 (仕入/売上/繰越商品) では 'MerchandiseInventory' を使う Machinery Assets Debit Machinery and equipment 機械装置 Asset: Machinery and equipment (機械装置)-Building Assets Debit Real estate 建物 Asset: Real estate (建物)+Building Assets Debit Buildings 建物 Asset: Buildings (建物) Vehicle Assets Debit Vehicles 車両運搬具 Asset: Vehicles (車両運搬具) StockInvestment Assets Debit Stock investment 株式投資 Asset: Stock investment (株式投資) EquipmentInvestment Assets Debit Equipment investment 設備投資 Asset: Equipment investment (設備投資)@@ -20,7 +20,7 @@ Gold Assets Debit Gold 金 Asset: Gold (金) GovernmentService Assets Debit Government service 政府サービス。SNA/マクロ系 Asset: Government service (政府サービス。SNA/マクロ系) CapitalStock Equity Credit Capital stock 資本金 Equity: Capital stock (資本金)-RetainedEarnings Equity Credit Retained earnings 繰越利益剰余金 Equity: Retained earnings (繰越利益剰余金)+RetainedEarnings Equity Credit Retained earnings brought forward 繰越利益剰余金 Equity: Retained earnings brought forward (繰越利益剰余金) LongTermLoansPayable Liability Credit Long-term loans payable 長期借入金 Liability: Long-term loans payable (長期借入金) ShortTermLoansPayable Liability Credit Short-term loans payable 短期借入金 Liability: Short-term loans payable (短期借入金) LoansPayable Liability Credit Loans payable 借入金 Liability: Loans payable (借入金)@@ -34,19 +34,18 @@ AmortizationExpense Cost Debit Amortization expense for intangibles 無形固定資産償却費 — 特許権・商標権・ソフトウェア等の無形資産の償却費。有形の 'Depreciation' (減価償却費) と区別される Expense: Amortization expense for intangibles (無形固定資産償却費 — 特許権・商標権・ソフトウェア等の無形資産の償却費。有形の 'Depreciation' (減価償却費) と区別される) SalesCost Cost Debit Cost of sales 売上原価 Expense: Cost of sales (売上原価) BusinessTrip Cost Debit Travel and transportation 旅費交通費 Expense: Travel and transportation (旅費交通費)-Commutation Cost Debit Communication 通信費 — 旧称。新規コードでは 'CommunicationExpenses' を使う Expense: Communication (通信費 — 旧称。新規コードでは 'CommunicationExpenses' を使う) UtilitiesExpense Cost Debit Utilities 水道光熱費 Expense: Utilities (水道光熱費) RentExpense Cost Debit Rent 支払家賃 Expense: Rent (支払家賃) AdvertisingExpense Cost Debit Advertising 広告宣伝費 Expense: Advertising (広告宣伝費) DeliveryExpenses Cost Debit Delivery 発送費 Expense: Delivery (発送費)-SuppliesExpenses Cost Debit Supplies 消耗品費 Expense: Supplies (消耗品費)+SuppliesExpenses Cost Debit Supplies expense 消耗品費 Expense: Supplies expense (消耗品費) MiscellaneousExpenses Cost Debit Miscellaneous 雑費 Expense: Miscellaneous (雑費) WageExpenditure Cost Debit Wages 給料 Expense: Wages (給料) InterestExpense Cost Debit Interest expense 支払利息 Expense: Interest expense (支払利息) TaxesExpense Cost Debit Taxes 租税公課 Expense: Taxes (租税公課) ConsumptionExpenditure Cost Debit Consumption expenditure 消費支出。SNA/マクロ系 Expense: Consumption expenditure (消費支出。SNA/マクロ系) SubsidyExpense Cost Debit Subsidy expenditure 補助金支出。SNA/マクロ系 Expense: Subsidy expenditure (補助金支出。SNA/マクロ系)-CentralBankPaymentExpense Cost Debit Central bank payment to treasury 国庫納付金支出。SNA/マクロ系 Expense: Central bank payment to treasury (国庫納付金支出。SNA/マクロ系)+CentralBankPaymentExpense Cost Debit Payment to national treasury 国庫納付金支出。SNA/マクロ系 Expense: Payment to national treasury (国庫納付金支出。SNA/マクロ系) Purchases Cost Debit Purchases 仕入 Expense: Purchases (仕入) NetIncome Cost Debit Net income 当期純利益 — 決算振替用。借方側に立つため Expense 区分 Expense: Net income (当期純利益 — 決算振替用。借方側に立つため Expense 区分) ValueAdded Revenue Credit Value added 付加価値。SNA/マクロ系 Revenue: Value added (付加価値。SNA/マクロ系)@@ -60,7 +59,7 @@ RentalIncome Revenue Credit Rental income 受取家賃 Revenue: Rental income (受取家賃) WageEarned Revenue Credit Wage income 賃金収入。SNA/マクロ系 Revenue: Wage income (賃金収入。SNA/マクロ系) TaxesRevenue Revenue Credit Tax revenue 租税収入。SNA/マクロ系 Revenue: Tax revenue (租税収入。SNA/マクロ系)-CentralBankPaymentIncome Revenue Credit Central bank payment to treasury 国庫納付金収入。SNA/マクロ系 Revenue: Central bank payment to treasury (国庫納付金収入。SNA/マクロ系)+CentralBankPaymentIncome Revenue Credit Central bank payment received 国庫納付金収入。SNA/マクロ系 Revenue: Central bank payment received (国庫納付金収入。SNA/マクロ系) Sales Revenue Credit Sales 売上 Revenue: Sales (売上) EquityInEarningsOfInvestee Revenue Credit Equity in earnings of investee 持分法による投資利益 Revenue: Equity in earnings of investee (持分法による投資利益). Recognized under the equity method. NetLoss Revenue Credit Net loss 当期純損失 — 決算振替用。貸方側に立つため Revenue 区分 Revenue: Net loss (当期純損失 — 決算振替用。貸方側に立つため Revenue 区分)@@ -110,7 +109,7 @@ PaymentFees Cost Debit Payment fees / fees paid 支払手数料 Expense: Payment fees / fees paid (支払手数料), the debit counterpart of 'ReceiptFee' MiscellaneousLoss Cost Debit Miscellaneous loss 雑損 Expense: Miscellaneous loss (雑損) CorporateIncomeTaxes Cost Debit Corporate income taxes 法人税等 Expense: Corporate income taxes (法人税等)-CommunicationExpenses Cost Debit Communication expenses 通信費 Expense: Communication expenses (通信費). Explicitly named counterpart of the legacy 'Commutation' (also "Communication"); 'Commutation' is retained for backward compatibility.+CommunicationExpenses Cost Debit Communication expenses 通信費 Expense: Communication expenses (通信費) GainOnSalesOfFixedAssets Revenue Credit Gain on sales of fixed assets 固定資産売却益 Revenue: Gain on sales of fixed assets (固定資産売却益) RecoveryOfBadDebts Revenue Credit Recovery of bad debts written off 償却債権取立益 Revenue: Recovery of bad debts written off (償却債権取立益) MiscellaneousIncome Revenue Credit Miscellaneous income 雑益 Revenue: Miscellaneous income (雑益)@@ -119,7 +118,7 @@ LoansReceivable Assets Debit Loans receivable 貸付金 Asset: Loans receivable (貸付金) GiftCertificatesReceived Assets Debit Gift certificates received 受取商品券 Asset: Gift certificates received (受取商品券) SecurityDepositsPaid Assets Debit Guarantee deposits 差入保証金 Asset: Guarantee deposits (差入保証金)-SuppliesOnHand Assets Debit Supplies 貯蔵品 Asset: Supplies (貯蔵品)+SuppliesOnHand Assets Debit Supplies on hand 貯蔵品 Asset: Supplies on hand (貯蔵品) ContractAssets Assets Debit Contract assets 契約資産 Asset: Contract assets (契約資産) IncomeTaxesRefundReceivable Assets Debit Income taxes refund receivable 未収還付法人税等 Asset: Income taxes refund receivable (未収還付法人税等) WorkInProcess Assets Debit Work in process 仕掛品 Asset: Work in process (仕掛品)@@ -142,9 +141,9 @@ NonOperatingNotesPayable Liability Credit Non-operating notes payable 営業外支払手形 Liability: Non-operating notes payable (営業外支払手形) NonOperatingElectronicallyRecordedObligations Liability Credit Electronically recorded obligations - non-operating 営業外電子記録債務 Liability: Electronically recorded obligations - non-operating (営業外電子記録債務) BonusesPayable Liability Credit Accrued bonuses 未払賞与 Liability: Accrued bonuses (未払賞与)-AllowanceForRepairs Liability Credit Provision for repairs 修繕引当金 Liability: Provision for repairs (修繕引当金)-AllowanceForProductWarranties Liability Credit Provision for warranties 商品保証引当金 Liability: Provision for warranties (商品保証引当金)-AllowanceForBonuses Liability Credit Provision for bonuses 賞与引当金 Liability: Provision for bonuses (賞与引当金)+AllowanceForRepairs Liability Credit Allowance for repairs 修繕引当金 Liability: Allowance for repairs (修繕引当金)+AllowanceForProductWarranties Liability Credit Allowance for warranties 商品保証引当金 Liability: Allowance for warranties (商品保証引当金)+AllowanceForBonuses Liability Credit Allowance for bonuses 賞与引当金 Liability: Allowance for bonuses (賞与引当金) DeferredTaxLiabilities Liability Credit Deferred tax liabilities 繰延税金負債 Liability: Deferred tax liabilities (繰延税金負債) LeaseObligations Liability Credit Lease liabilities リース債務 Liability: Lease liabilities (リース債務) GuaranteeDepositsReceived Liability Credit Guarantee deposits received 預り保証金 Liability: Guarantee deposits received (預り保証金)@@ -171,8 +170,8 @@ GainOnSalesOfInvestmentSecurities Revenue Credit Gain on sale of investment securities 投資有価証券売却益 Revenue: Gain on sale of investment securities (投資有価証券売却益) InsuranceGain Revenue Credit Gain on insurance claims 保険差益 Revenue: Gain on insurance claims (保険差益) GainOnBargainPurchase Revenue Credit Gain on bargain purchase 負ののれん発生益 Revenue: Gain on bargain purchase (負ののれん発生益)-ReversalOfAllowanceForRepairs Revenue Credit Reversal of provision for repairs 修繕引当金戻入 Revenue: Reversal of provision for repairs (修繕引当金戻入)-ReversalOfAllowanceForProductWarranties Revenue Credit Reversal of provision for warranties 商品保証引当金戻入 Revenue: Reversal of provision for warranties (商品保証引当金戻入)+ReversalOfAllowanceForRepairs Revenue Credit Reversal of allowance for repairs 修繕引当金戻入 Revenue: Reversal of allowance for repairs (修繕引当金戻入)+ReversalOfAllowanceForProductWarranties Revenue Credit Reversal of allowance for warranties 商品保証引当金戻入 Revenue: Reversal of allowance for warranties (商品保証引当金戻入) GainOnDonationOfFixedAssets Revenue Credit Gain on receipt of donated non-current assets 固定資産受贈益 Revenue: Gain on receipt of donated non-current assets (固定資産受贈益) GainOnNationalSubsidies Revenue Credit Gain on receipt of national subsidies 国庫補助金受贈益 Revenue: Gain on receipt of national subsidies (国庫補助金受贈益) GainOnConstructionGrants Revenue Credit Gain on contribution received for construction 工事負担金受贈益 Revenue: Gain on contribution received for construction (工事負担金受贈益)@@ -241,4 +240,5 @@ GoodsInTransit Assets Debit Goods in transit 未着品 Asset: Goods in transit (未着品) SalesAllowances Revenue Debit Sales allowances 売上値引 Revenue: Sales allowances (売上値引) PurchaseAllowances Cost Credit Purchase allowances 仕入値引 Expense: Purchase allowances (仕入値引)-ReversalOfAllowanceForBonuses Revenue Credit Reversal of provision for bonuses 賞与引当金戻入 Revenue: Reversal of provision for bonuses (賞与引当金戻入)+ReversalOfAllowanceForBonuses Revenue Credit Reversal of allowance for bonuses 賞与引当金戻入 Revenue: Reversal of allowance for bonuses (賞与引当金戻入)+DirectorsCompensations Cost Debit Remuneration for directors (and other officers) 役員報酬 Expense: Remuneration for directors (役員報酬)
− test/fixtures/post-vocab/ordinals.tsv
@@ -1,245 +0,0 @@-# post-vocab Enum ordinals (constructor, fromEnum); schema 1-Cash 0-Deposits 1-CurrentDeposits 2-Securities 3-InvestmentSecurities 4-InvestmentInAssociate 5-LongTermNationalBonds 6-ShortTermNationalBonds 7-Products 8-Machinery 9-Building 10-Vehicle 11-StockInvestment 12-EquipmentInvestment 13-LongTermLoansReceivable 14-AccountsReceivable 15-ShortTermLoansReceivable 16-ReserveDepositReceivable 17-Gold 18-GovernmentService 19-CapitalStock 20-RetainedEarnings 21-LongTermLoansPayable 22-ShortTermLoansPayable 23-LoansPayable 24-ReserveForDepreciation 25-DepositPayable 26-LongTermNationalBondsPayable 27-ShortTermNationalBondsPayable 28-ReserveDepositPayable 29-CentralBankNotePayable 30-Depreciation 31-AmortizationExpense 32-SalesCost 33-BusinessTrip 34-Commutation 35-UtilitiesExpense 36-RentExpense 37-AdvertisingExpense 38-DeliveryExpenses 39-SuppliesExpenses 40-MiscellaneousExpenses 41-WageExpenditure 42-InterestExpense 43-TaxesExpense 44-ConsumptionExpenditure 45-SubsidyExpense 46-CentralBankPaymentExpense 47-Purchases 48-NetIncome 49-ValueAdded 50-SubsidyIncome 51-NationalBondInterestEarned 52-DepositInterestEarned 53-GrossProfit 54-OrdinaryProfit 55-InterestEarned 56-ReceiptFee 57-RentalIncome 58-WageEarned 59-TaxesRevenue 60-CentralBankPaymentIncome 61-Sales 62-EquityInEarningsOfInvestee 63-NetLoss 64-PettyCash 65-NotesReceivable 66-ElectronicallyRecordedReceivable 67-CreditCardReceivable 68-NotesLoansReceivable 69-MerchandiseInventory 70-AdvancesPaid 71-PrepaidExpenses 72-AccruedRevenue 73-OtherReceivables 74-PaymentsOnBehalf 75-SuspensePayments 76-ConsumptionTaxPaid 77-PrepaidCorporateIncomeTaxes 78-Land 79-Fixtures 80-Patent 81-Trademark 82-Software 83-CashOverShort 84-AccountsPayable 85-NotesPayable 86-ElectronicallyRecordedObligations 87-NotesLoansPayable 88-BankOverdraft 89-AdvancesReceived 90-UnearnedRevenue 91-AccruedExpenses 92-OtherPayables 93-DepositsReceived 94-SuspenseReceipts 95-ConsumptionTaxReceived 96-AccruedConsumptionTax 97-AccruedCorporateIncomeTaxes 98-UnpaidDividends 99-AllowanceForDoubtfulAccounts 100-AccumulatedDepreciation 101-LegalRetainedEarnings 102-CumulativeTranslationAdjustment 103-ProvisionForDoubtfulAccounts 104-BadDebtLoss 105-LossOnSalesOfFixedAssets 106-LossOnSalesOfNotesReceivable 107-PaymentFees 108-MiscellaneousLoss 109-CorporateIncomeTaxes 110-CommunicationExpenses 111-GainOnSalesOfFixedAssets 112-RecoveryOfBadDebts 113-MiscellaneousIncome 114-ReversalOfAllowanceForDoubtfulAccounts 115-TimeDeposits 116-LoansReceivable 117-GiftCertificatesReceived 118-SecurityDepositsPaid 119-SuppliesOnHand 120-ContractAssets 121-IncomeTaxesRefundReceivable 122-WorkInProcess 123-DeferredTaxAssets 124-LeasedAssets 125-ToolsAndInstruments 126-ConstructionInProgress 127-Goodwill 128-SoftwareInProgress 129-LongTermPrepaidExpenses 130-DishonoredNotesReceivable 131-PrepaidPensionCost 132-NetDefinedBenefitAsset 133-DepositsInSpecialAccounts 134-Structures 135-LeaseholdRights 136-NonOperatingNotesReceivable 137-NonOperatingElectronicallyRecordedReceivable 138-RefundLiabilities 139-NonOperatingNotesPayable 140-NonOperatingElectronicallyRecordedObligations 141-BonusesPayable 142-AllowanceForRepairs 143-AllowanceForProductWarranties 144-AllowanceForBonuses 145-DeferredTaxLiabilities 146-LeaseObligations 147-GuaranteeDepositsReceived 148-AllowanceForRetirementBenefits 149-LongTermOtherPayables 150-NetDefinedBenefitLiability 151-StockSubscriptionDeposits 152-LegalCapitalSurplus 153-OtherCapitalSurplus 154-DividendEqualizationReserve 155-RepairFundReserve 156-ConstructionFundReserve 157-GeneralReserve 158-ValuationDifferenceOnOtherSecurities 159-NonControllingInterests 160-CapitalSurplus 161-EarnedSurplus 162-ServiceRevenue 163-OperatingRevenue 164-GainOnSalesOfSecurities 165-GainOnValuationOfSecurities 166-DividendsReceived 167-InterestOnSecurities 168-GainOnSalesOfInvestmentSecurities 169-InsuranceGain 170-GainOnBargainPurchase 171-ReversalOfAllowanceForRepairs 172-ReversalOfAllowanceForProductWarranties 173-GainOnDonationOfFixedAssets 174-GainOnNationalSubsidies 175-GainOnConstructionGrants 176-LandRentReceived 177-SalesRebates 178-CostOfServices 179-OperatingExpenses 180-InventoryShrinkageLoss 181-LossOnValuationOfMerchandise 182-Bonuses 183-RetirementBenefitExpenses 184-ProvisionForRepairs 185-ProvisionForBonuses 186-ProvisionForProductWarranties 187-ResearchAndDevelopmentExpenses 188-AmortizationOfGoodwill 189-AmortizationOfSoftware 190-AmortizationOfPatents 191-LeaseExpenses 192-IncorporationExpenses 193-StockIssuanceCosts 194-BusinessCommencementExpenses 195-DevelopmentExpenses 196-LossOnSalesOfElectronicallyRecordedReceivables 197-LossOnSalesOfReceivables 198-LossOnSalesOfSecurities 199-LossOnValuationOfSecurities 200-LossOnSalesOfInvestmentSecurities 201-LossOnFire 202-LossOnRetirementOfFixedAssets 203-LossOnReductionOfFixedAssets 204-AdditionalIncomeTaxesForPriorPeriods 205-RefundOfIncomeTaxes 206-PurchaseRebates 207-WelfareExpenses 208-MaintenanceExpenses 209-StatutoryWelfareExpenses 210-LandRentPaid 211-InsuranceExpense 212-RepairsExpense 213-StorageExpenses 214-MembershipFees 215-IncomeSummary 216-SuspenseAccount 217-ForeignExchangeGains 218-ForeignExchangeLosses 219-ContraAccountForGuaranteeObligations 220-GuaranteeObligations 221-IncomeTaxesAdjustment 222-BranchCurrentAccount 223-HeadOfficeCurrentAccount 224-NetIncomeAttributableToNCI 225-NetLossAttributableToNCI 226-TradingSecurities 227-HeldToMaturityBonds 228-SubsidiaryStocks 229-AffiliateStocks 230-AvailableForSaleSecurities 231-ConsumptionTaxRefundReceivable 232-PropertyTaxPayable 233-DepositsReceivedFromOfficers 234-EntertainmentExpenses 235-MeetingExpenses 236-NewspaperBooksExpenses 237-RawMaterials 238-GoodsInTransit 239-SalesAllowances 240-PurchaseAllowances 241-ReversalOfAllowanceForBonuses 242-AccountTitle 243
test/fixtures/post-vocab/semantics.tsv view
@@ -34,7 +34,6 @@ AmortizationExpense Cost False Debit Credit OUT Other Flip SalesCost Cost False Debit Credit OUT Other Flip BusinessTrip Cost False Debit Credit OUT Other Flip-Commutation Cost False Debit Credit OUT Other Flip UtilitiesExpense Cost False Debit Credit OUT Other Flip RentExpense Cost False Debit Credit OUT Other Flip AdvertisingExpense Cost False Debit Credit OUT Other Flip@@ -242,3 +241,4 @@ SalesAllowances Revenue True Debit Credit OUT Other Flip PurchaseAllowances Cost True Credit Debit IN Other Keep ReversalOfAllowanceForBonuses Revenue False Credit Debit IN Other Keep+DirectorsCompensations Cost False Debit Credit OUT Other Flip
test/fixtures/post-vocab/suggest.tsv view
@@ -1,10 +1,7 @@ # post-vocab suggestAccounts (query, total matches, top-10 titles); schema 1-"Communication"); 1 CommunicationExpenses 'AccountsPayable' 1 ReserveDepositPayable 'AccumulatedDepreciation' 1 ReserveForDepreciation 'AllowanceForDoubtfulAccounts' 1 ReversalOfAllowanceForDoubtfulAccounts-'CommunicationExpenses' 1 Commutation-'Commutation' 1 CommunicationExpenses 'DepositsReceived') 1 DepositPayable 'Depreciation' 1 AmortizationExpense 'MerchandiseInventory' 1 Products@@ -13,7 +10,6 @@ 'ReceiptFee' 1 PaymentFees 'ReserveForDepreciation' 1 AccumulatedDepreciation (3 1 MerchandiseInventory-(also 1 CommunicationExpenses (appropriated) 1 LegalRetainedEarnings (contra): 2 AllowanceForDoubtfulAccounts,AccumulatedDepreciation (isContra). 1 AccumulatedDepreciation@@ -126,6 +122,7 @@ (当期純損失 1 NetLoss (役務原価) 1 CostOfServices (役務収益) 1 ServiceRevenue+(役員報酬) 1 DirectorsCompensations (役員預り金) 1 DepositsReceivedFromOfficers (手形借入金) 1 NotesLoansPayable (手形売却損) 1 LossOnSalesOfNotesReceivable@@ -242,8 +239,7 @@ (退職給付に係る資産) 1 NetDefinedBenefitAsset (退職給付引当金) 1 AllowanceForRetirementBenefits (退職給付費用) 1 RetirementBenefitExpenses-(通信費 2 Commutation,CommunicationExpenses-(通信費). 1 CommunicationExpenses+(通信費) 1 CommunicationExpenses (還付法人税等) 1 RefundOfIncomeTaxes (配当平均積立金) 1 DividendEqualizationReserve (金) 1 Gold@@ -281,7 +277,7 @@ Accrued (unpaid) consumption tax 21 AccruedConsumptionTax,AccruedCorporateIncomeTaxes,ConsumptionTaxPaid,ConsumptionTaxReceived,ConsumptionTaxRefundReceivable,TaxesExpense,ConsumptionExpenditure,TaxesRevenue,AccruedRevenue,PrepaidCorporateIncomeTaxes Accrued (unpaid) corporate income taxes 24 AccruedCorporateIncomeTaxes,PrepaidCorporateIncomeTaxes,CorporateIncomeTaxes,AccruedConsumptionTax,IncomeTaxesRefundReceivable,AdditionalIncomeTaxesForPriorPeriods,RefundOfIncomeTaxes,IncomeTaxesAdjustment,TaxesExpense,NetIncome Accrued bonuses 9 BonusesPayable,AccruedRevenue,AccruedExpenses,AccruedConsumptionTax,AccruedCorporateIncomeTaxes,AllowanceForBonuses,Bonuses,ProvisionForBonuses,ReversalOfAllowanceForBonuses-Accrued expenses 29 AccruedExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedRevenue,AccruedConsumptionTax,AccruedCorporateIncomeTaxes,CommunicationExpenses+Accrued expenses 28 AccruedExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedRevenue,AccruedConsumptionTax,AccruedCorporateIncomeTaxes,CommunicationExpenses,LongTermPrepaidExpenses Accrued revenue 45 AccruedRevenue,ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome AccruedConsumptionTax 1 AccruedConsumptionTax AccruedCorporateIncomeTaxes 1 AccruedCorporateIncomeTaxes@@ -291,25 +287,28 @@ Accumulated depreciation 4 ReserveForDepreciation,AccumulatedDepreciation,Depreciation,AmortizationExpense AccumulatedDepreciation 2 ReserveForDepreciation,AccumulatedDepreciation Additional 1 AdditionalIncomeTaxesForPriorPeriods-Additional income taxes for prior periods 48 AdditionalIncomeTaxesForPriorPeriods,PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,IncomeTaxesRefundReceivable,RefundOfIncomeTaxes,IncomeTaxesAdjustment,ReserveForDepreciation,AmortizationExpense,TaxesExpense+Additional income taxes for prior periods 49 AdditionalIncomeTaxesForPriorPeriods,PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,IncomeTaxesRefundReceivable,RefundOfIncomeTaxes,IncomeTaxesAdjustment,RetainedEarnings,ReserveForDepreciation,AmortizationExpense AdditionalIncomeTaxesForPriorPeriods 1 AdditionalIncomeTaxesForPriorPeriods Advances 2 AdvancesPaid,AdvancesReceived Advances paid 13 AdvancesPaid,PrepaidExpenses,ConsumptionTaxPaid,PrepaidCorporateIncomeTaxes,AdvancesReceived,AccruedConsumptionTax,AccruedCorporateIncomeTaxes,UnpaidDividends,PaymentFees,SecurityDepositsPaid-Advances received 11 AdvancesReceived,DepositPayable,AdvancesPaid,DepositsReceived,ConsumptionTaxReceived,GiftCertificatesReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants,LandRentReceived+Advances received 12 AdvancesReceived,DepositPayable,CentralBankPaymentIncome,AdvancesPaid,DepositsReceived,ConsumptionTaxReceived,GiftCertificatesReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants AdvancesPaid 1 AdvancesPaid AdvancesReceived 1 AdvancesReceived Advertising 1 AdvertisingExpense AdvertisingExpense 1 AdvertisingExpense AffiliateStocks 1 AffiliateStocks Allowance 11 AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,SalesAllowances,PurchaseAllowances-Allowance for doubtful accounts 36 AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses+Allowance for bonuses 34 AllowanceForBonuses,ReversalOfAllowanceForBonuses,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForBonuses+Allowance for doubtful accounts 37 AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses+Allowance for repairs 33 AllowanceForRepairs,ReversalOfAllowanceForRepairs,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,RepairFundReserve,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs+Allowance for warranties 32 AllowanceForProductWarranties,ReversalOfAllowanceForProductWarranties,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ProvisionForProductWarranties,ReversalOfAllowanceForBonuses AllowanceForBonuses 2 AllowanceForBonuses,ReversalOfAllowanceForBonuses AllowanceForDoubtfulAccounts 2 AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts AllowanceForProductWarranties 2 AllowanceForProductWarranties,ReversalOfAllowanceForProductWarranties AllowanceForRepairs 2 AllowanceForRepairs,ReversalOfAllowanceForRepairs AllowanceForRetirementBenefits 1 AllowanceForRetirementBenefits Amortization 4 AmortizationExpense,AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationOfPatents-Amortization expense for intangibles 95 AmortizationExpense,ProvisionForDoubtfulAccounts,CommunicationExpenses,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationOfPatents,AdditionalIncomeTaxesForPriorPeriods+Amortization expense for intangibles 96 AmortizationExpense,ProvisionForDoubtfulAccounts,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationOfPatents,AdditionalIncomeTaxesForPriorPeriods,ForeignExchangeLosses Amortization of goodwill 43 AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationOfPatents,AmortizationExpense,SalesCost,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee,MerchandiseInventory,Software Amortization of patent rights 44 AmortizationOfPatents,AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationExpense,SalesCost,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee,MerchandiseInventory,Patent Amortization of software 42 AmortizationOfSoftware,Software,SoftwareInProgress,AmortizationOfGoodwill,AmortizationOfPatents,AmortizationExpense,SalesCost,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee@@ -337,8 +336,9 @@ Branch current account 23 BranchCurrentAccount,HeadOfficeCurrentAccount,CurrentDeposits,AccountsReceivable,ReserveDepositPayable,MerchandiseInventory,PrepaidExpenses,AccruedRevenue,CashOverShort,AccountsPayable BranchCurrentAccount 1 BranchCurrentAccount Building 1 Building+Buildings 1 Building Business 2 BusinessTrip,BusinessCommencementExpenses-Business commencement expenses 26 BusinessCommencementExpenses,BusinessTrip,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses+Business commencement expenses 25 BusinessCommencementExpenses,BusinessTrip,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses BusinessCommencementExpenses 1 BusinessCommencementExpenses BusinessTrip 1 BusinessTrip Capital 4 CapitalStock,LegalCapitalSurplus,OtherCapitalSurplus,CapitalSurplus@@ -348,33 +348,32 @@ CapitalSurplus 3 LegalCapitalSurplus,OtherCapitalSurplus,CapitalSurplus Carrying 1 InvestmentInAssociate Cash 3 Cash,PettyCash,CashOverShort-Cash over and short 26 CashOverShort,Cash,ShortTermNationalBonds,Products,Machinery,ShortTermLoansReceivable,GovernmentService,ShortTermLoansPayable,ShortTermNationalBondsPayable,BusinessTrip+Cash over and short 27 CashOverShort,Cash,ShortTermNationalBonds,Products,Machinery,ShortTermLoansReceivable,GovernmentService,ShortTermLoansPayable,ShortTermNationalBondsPayable,BusinessTrip CashOverShort 1 CashOverShort Central 3 CentralBankNotePayable,CentralBankPaymentExpense,CentralBankPaymentIncome Central bank notes 12 CentralBankNotePayable,CentralBankPaymentExpense,CentralBankPaymentIncome,NotesReceivable,NotesLoansReceivable,NotesPayable,NotesLoansPayable,BankOverdraft,LossOnSalesOfNotesReceivable,DishonoredNotesReceivable-Central bank payment to treasury 28 CentralBankPaymentExpense,CentralBankPaymentIncome,CentralBankNotePayable,Products,StockInvestment,CapitalStock,ReceiptFee,MerchandiseInventory,PaymentsOnBehalf,SuspensePayments+Central bank payment received 18 CentralBankPaymentIncome,CentralBankPaymentExpense,CentralBankNotePayable,DepositPayable,ReceiptFee,PaymentsOnBehalf,SuspensePayments,BankOverdraft,AdvancesReceived,DepositsReceived CentralBankNotePayable 1 CentralBankNotePayable CentralBankPaymentExpense 1 CentralBankPaymentExpense CentralBankPaymentIncome 1 CentralBankPaymentIncome-Communication 2 Commutation,CommunicationExpenses-Communication expenses 25 Commutation,CommunicationExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses-CommunicationExpenses 2 Commutation,CommunicationExpenses-Commutation 2 Commutation,CommunicationExpenses+Communication 1 CommunicationExpenses+Communication expenses 24 CommunicationExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses,ResearchAndDevelopmentExpenses+CommunicationExpenses 1 CommunicationExpenses Construction 3 ConstructionInProgress,ConstructionFundReserve,GainOnConstructionGrants-Construction in progress 82 ConstructionInProgress,SoftwareInProgress,GainOnConstructionGrants,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment+Construction in progress 81 ConstructionInProgress,SoftwareInProgress,GainOnConstructionGrants,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment ConstructionFundReserve 1 ConstructionFundReserve ConstructionInProgress 1 ConstructionInProgress Consumption 5 ConsumptionExpenditure,ConsumptionTaxPaid,ConsumptionTaxReceived,AccruedConsumptionTax,ConsumptionTaxRefundReceivable Consumption expenditure 7 ConsumptionExpenditure,WageExpenditure,SubsidyExpense,ConsumptionTaxPaid,ConsumptionTaxReceived,AccruedConsumptionTax,ConsumptionTaxRefundReceivable Consumption tax paid 26 ConsumptionTaxPaid,AccruedConsumptionTax,PrepaidCorporateIncomeTaxes,ConsumptionTaxReceived,AccruedCorporateIncomeTaxes,ConsumptionTaxRefundReceivable,TaxesExpense,ConsumptionExpenditure,TaxesRevenue,AdvancesPaid-Consumption tax received 27 ConsumptionTaxReceived,ConsumptionTaxPaid,AccruedConsumptionTax,ConsumptionTaxRefundReceivable,DepositPayable,TaxesExpense,ConsumptionExpenditure,TaxesRevenue,PrepaidCorporateIncomeTaxes,AdvancesReceived+Consumption tax received 28 ConsumptionTaxReceived,ConsumptionTaxPaid,AccruedConsumptionTax,ConsumptionTaxRefundReceivable,DepositPayable,TaxesExpense,ConsumptionExpenditure,TaxesRevenue,CentralBankPaymentIncome,PrepaidCorporateIncomeTaxes Consumption tax refund receivable 36 ConsumptionTaxRefundReceivable,IncomeTaxesRefundReceivable,ConsumptionTaxPaid,ConsumptionTaxReceived,AccruedConsumptionTax,RefundOfIncomeTaxes,LongTermLoansReceivable,AccountsReceivable,ShortTermLoansReceivable,ReserveDepositReceivable ConsumptionExpenditure 1 ConsumptionExpenditure ConsumptionTaxPaid 1 ConsumptionTaxPaid ConsumptionTaxReceived 1 ConsumptionTaxReceived ConsumptionTaxRefundReceivable 1 ConsumptionTaxRefundReceivable Contra 4 AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ContractAssets,ContraAccountForGuaranteeObligations-Contra account for guarantee obligations 49 ContraAccountForGuaranteeObligations,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,MerchandiseInventory,ProvisionForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,GuaranteeObligations,AccountsReceivable,ReserveForDepreciation,ReserveDepositPayable+Contra account for guarantee obligations 50 ContraAccountForGuaranteeObligations,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,MerchandiseInventory,ProvisionForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,GuaranteeObligations,AccountsReceivable,RetainedEarnings,ReserveForDepreciation ContraAccountForGuaranteeObligations 1 ContraAccountForGuaranteeObligations Contract 1 ContractAssets Contract assets 10 ContractAssets,AccumulatedDepreciation,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,DeferredTaxAssets,LeasedAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,IncomeSummary@@ -408,17 +407,18 @@ DepositPayable 2 DepositPayable,ReserveDepositPayable Deposits 12 Deposits,CurrentDeposits,ReserveDepositReceivable,DepositPayable,ReserveDepositPayable,DepositsReceived,TimeDeposits,SecurityDepositsPaid,DepositsInSpecialAccounts,GuaranteeDepositsReceived Deposits accepted 12 DepositPayable,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,DepositsReceived,TimeDeposits,SecurityDepositsPaid,DepositsInSpecialAccounts,GuaranteeDepositsReceived-Deposits for subscriptions of shares 73 StockSubscriptionDeposits,MerchandiseInventory,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,SubsidiaryStocks,AffiliateStocks,DepositsReceivedFromOfficers,ReversalOfAllowanceForBonuses-Deposits in special accounts 95 DepositsInSpecialAccounts,Deposits,ReserveDepositPayable,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,CurrentDeposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery-Deposits received 18 DepositPayable,DepositsReceived,GuaranteeDepositsReceived,DepositsReceivedFromOfficers,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,AdvancesReceived,ConsumptionTaxReceived-Deposits received from officers 20 DepositsReceivedFromOfficers,DepositPayable,DepositsReceived,GuaranteeDepositsReceived,LandRentReceived,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,AdvancesReceived+Deposits for subscriptions of shares 74 StockSubscriptionDeposits,MerchandiseInventory,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,SubsidiaryStocks,AffiliateStocks,DepositsReceivedFromOfficers,ReversalOfAllowanceForBonuses,DirectorsCompensations+Deposits in special accounts 94 DepositsInSpecialAccounts,Deposits,ReserveDepositPayable,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,CurrentDeposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery+Deposits received 19 DepositPayable,DepositsReceived,GuaranteeDepositsReceived,DepositsReceivedFromOfficers,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,CentralBankPaymentIncome,AdvancesReceived+Deposits received from officers 22 DepositsReceivedFromOfficers,DepositPayable,DepositsReceived,GuaranteeDepositsReceived,LandRentReceived,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,CentralBankPaymentIncome DepositsInSpecialAccounts 1 DepositsInSpecialAccounts DepositsReceived 4 DepositPayable,DepositsReceived,GuaranteeDepositsReceived,DepositsReceivedFromOfficers DepositsReceivedFromOfficers 1 DepositsReceivedFromOfficers Depreciation 4 ReserveForDepreciation,Depreciation,AmortizationExpense,AccumulatedDepreciation Development 2 ResearchAndDevelopmentExpenses,DevelopmentExpenses-Development expenses 25 ResearchAndDevelopmentExpenses,DevelopmentExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses+Development expenses 24 ResearchAndDevelopmentExpenses,DevelopmentExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses DevelopmentExpenses 2 ResearchAndDevelopmentExpenses,DevelopmentExpenses+DirectorsCompensations 1 DirectorsCompensations Dishonored 1 DishonoredNotesReceivable Dishonored notes receivable 23 DishonoredNotesReceivable,NotesReceivable,NotesLoansReceivable,LossOnSalesOfNotesReceivable,NonOperatingNotesReceivable,LongTermLoansReceivable,AccountsReceivable,ShortTermLoansReceivable,ReserveDepositReceivable,CentralBankNotePayable DishonoredNotesReceivable 1 DishonoredNotesReceivable@@ -435,37 +435,36 @@ ElectronicallyRecordedObligations 2 ElectronicallyRecordedObligations,NonOperatingElectronicallyRecordedObligations ElectronicallyRecordedReceivable 3 ElectronicallyRecordedReceivable,NonOperatingElectronicallyRecordedReceivable,LossOnSalesOfElectronicallyRecordedReceivables Entertainment 1 EntertainmentExpenses-Entertainment expenses 25 EntertainmentExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses+Entertainment expenses 24 EntertainmentExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses EntertainmentExpenses 1 EntertainmentExpenses Equipment 3 Machinery,EquipmentInvestment,Fixtures Equipment investment 8 EquipmentInvestment,InvestmentSecurities,InvestmentInAssociate,Machinery,StockInvestment,Fixtures,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities EquipmentInvestment 1 EquipmentInvestment Equity 17 InvestmentInAssociate,CapitalStock,RetainedEarnings,EquityInEarningsOfInvestee,LegalRetainedEarnings,CumulativeTranslationAdjustment,StockSubscriptionDeposits,LegalCapitalSurplus,OtherCapitalSurplus,DividendEqualizationReserve-Equity in earnings of investee 116 EquityInEarningsOfInvestee,RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,InvestmentInAssociate,OrdinaryProfit,MerchandiseInventory,CommunicationExpenses,GainOnSalesOfFixedAssets,ReversalOfAllowanceForDoubtfulAccounts+Equity in earnings of investee 116 EquityInEarningsOfInvestee,RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,InvestmentInAssociate,OrdinaryProfit,MerchandiseInventory,GainOnSalesOfFixedAssets,ReversalOfAllowanceForDoubtfulAccounts,SoftwareInProgress Equity: 15 CapitalStock,RetainedEarnings,LegalRetainedEarnings,CumulativeTranslationAdjustment,StockSubscriptionDeposits,LegalCapitalSurplus,OtherCapitalSurplus,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve EquityInEarningsOfInvestee 1 EquityInEarningsOfInvestee ExchangeAlgebra.IO.Output 1 AllowanceForDoubtfulAccounts-Expense 74 Depreciation,AmortizationExpense,SalesCost,BusinessTrip,Commutation,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses,SuppliesExpenses-Expense: 71 Depreciation,AmortizationExpense,SalesCost,BusinessTrip,Commutation,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses,SuppliesExpenses-Explicitly 1 CommunicationExpenses+Expense 74 Depreciation,AmortizationExpense,SalesCost,BusinessTrip,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses+Expense: 71 Depreciation,AmortizationExpense,SalesCost,BusinessTrip,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses Fixtures 1 Fixtures-Fixtures and equipment 18 Fixtures,Machinery,Products,EquipmentInvestment,BusinessTrip,MerchandiseInventory,Land,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand-For 29 ReserveForDepreciation,AmortizationExpense,MerchandiseInventory,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ProvisionForDoubtfulAccounts,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties+Fixtures and equipment 19 Fixtures,Machinery,Products,EquipmentInvestment,BusinessTrip,MerchandiseInventory,Land,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand+For 30 RetainedEarnings,ReserveForDepreciation,AmortizationExpense,MerchandiseInventory,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ProvisionForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties Foreign 2 ForeignExchangeGains,ForeignExchangeLosses Foreign exchange gains 3 ForeignExchangeGains,ForeignExchangeLosses,AllowanceForDoubtfulAccounts Foreign exchange losses 3 ForeignExchangeLosses,ForeignExchangeGains,AllowanceForDoubtfulAccounts ForeignExchangeGains 1 ForeignExchangeGains ForeignExchangeLosses 1 ForeignExchangeLosses Gain 11 MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,InsuranceGain,GainOnBargainPurchase,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,GainOnConstructionGrants-Gain on bargain purchase 93 GainOnBargainPurchase,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,InsuranceGain,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,GainOnConstructionGrants-Gain on contribution received for construction 102 GainOnConstructionGrants,MerchandiseInventory,ConstructionFundReserve,ReserveForDepreciation,AmortizationExpense,ConsumptionTaxReceived,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ProvisionForDoubtfulAccounts,CommunicationExpenses-Gain on insurance claims 91 InsuranceGain,ElectronicallyRecordedReceivable,MerchandiseInventory,GainOnSalesOfFixedAssets,NonOperatingElectronicallyRecordedReceivable,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,GainOnBargainPurchase,GainOnDonationOfFixedAssets-Gain on receipt of donated non-current assets 110 GainOnDonationOfFixedAssets,GainOnSalesOfFixedAssets,GainOnNationalSubsidies,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,MerchandiseInventory,LossOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities-Gain on receipt of national subsidies 107 GainOnNationalSubsidies,GainOnDonationOfFixedAssets,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable-Gain on sale of investment securities 115 GainOnSalesOfInvestmentSecurities,GainOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnValuationOfSecurities,LossOnSalesOfSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities-Gain on sale of securities 112 GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnValuationOfSecurities,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities-Gain on sales of fixed assets 112 GainOnSalesOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,MerchandiseInventory,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnValuationOfSecurities-Gain on valuation of securities 109 GainOnValuationOfSecurities,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnValuationOfSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,ValuationDifferenceOnOtherSecurities,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,LossOnValuationOfMerchandise+Gain on bargain purchase 90 GainOnBargainPurchase,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,InsuranceGain,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,GainOnConstructionGrants+Gain on contribution received for construction 105 GainOnConstructionGrants,MerchandiseInventory,ConstructionFundReserve,ReserveForDepreciation,AmortizationExpense,ConsumptionTaxReceived,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ProvisionForDoubtfulAccounts,GainOnSalesOfFixedAssets+Gain on insurance claims 88 InsuranceGain,ElectronicallyRecordedReceivable,MerchandiseInventory,GainOnSalesOfFixedAssets,NonOperatingElectronicallyRecordedReceivable,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,GainOnBargainPurchase,GainOnDonationOfFixedAssets+Gain on receipt of donated non-current assets 109 GainOnDonationOfFixedAssets,GainOnSalesOfFixedAssets,GainOnNationalSubsidies,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,MerchandiseInventory,LossOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities+Gain on receipt of national subsidies 106 GainOnNationalSubsidies,GainOnDonationOfFixedAssets,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable+Gain on sale of investment securities 114 GainOnSalesOfInvestmentSecurities,GainOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnValuationOfSecurities,LossOnSalesOfSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities+Gain on sale of securities 111 GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnValuationOfSecurities,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities+Gain on sales of fixed assets 111 GainOnSalesOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,MerchandiseInventory,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnValuationOfSecurities+Gain on valuation of securities 108 GainOnValuationOfSecurities,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnValuationOfSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,ValuationDifferenceOnOtherSecurities,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,LossOnValuationOfMerchandise GainOnBargainPurchase 1 GainOnBargainPurchase GainOnConstructionGrants 1 GainOnConstructionGrants GainOnDonationOfFixedAssets 1 GainOnDonationOfFixedAssets@@ -478,11 +477,11 @@ General reserve 9 GeneralReserve,ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,AccumulatedDepreciation,LegalRetainedEarnings,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve GeneralReserve 1 GeneralReserve Gift 1 GiftCertificatesReceived-Gift certificates received 10 GiftCertificatesReceived,DepositPayable,AdvancesReceived,DepositsReceived,ConsumptionTaxReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants,LandRentReceived,DepositsReceivedFromOfficers+Gift certificates received 11 GiftCertificatesReceived,DepositPayable,CentralBankPaymentIncome,AdvancesReceived,DepositsReceived,ConsumptionTaxReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants,LandRentReceived GiftCertificatesReceived 1 GiftCertificatesReceived Gold 1 Gold Goods 3 MerchandiseInventory,LossOnValuationOfMerchandise,GoodsInTransit-Goods in transit 82 GoodsInTransit,MerchandiseInventory,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment+Goods in transit 81 GoodsInTransit,MerchandiseInventory,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment GoodsInTransit 1 GoodsInTransit Goodwill 2 Goodwill,AmortizationOfGoodwill Government 1 GovernmentService@@ -493,13 +492,13 @@ GrossProfit 1 GrossProfit Guarantee 4 SecurityDepositsPaid,GuaranteeDepositsReceived,ContraAccountForGuaranteeObligations,GuaranteeObligations Guarantee deposits 14 SecurityDepositsPaid,GuaranteeDepositsReceived,Deposits,CurrentDeposits,ReserveDepositReceivable,DepositPayable,ReserveDepositPayable,DepositsReceived,TimeDeposits,DepositsInSpecialAccounts-Guarantee deposits received 20 GuaranteeDepositsReceived,DepositPayable,DepositsReceived,SecurityDepositsPaid,DepositsReceivedFromOfficers,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,AdvancesReceived+Guarantee deposits received 21 GuaranteeDepositsReceived,DepositPayable,DepositsReceived,SecurityDepositsPaid,DepositsReceivedFromOfficers,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,CentralBankPaymentIncome Guarantee obligations 7 ContraAccountForGuaranteeObligations,GuaranteeObligations,ElectronicallyRecordedObligations,SecurityDepositsPaid,NonOperatingElectronicallyRecordedObligations,LeaseObligations,GuaranteeDepositsReceived GuaranteeDepositsReceived 1 GuaranteeDepositsReceived GuaranteeObligations 2 ContraAccountForGuaranteeObligations,GuaranteeObligations Hat/Not 1 AllowanceForDoubtfulAccounts Head 1 HeadOfficeCurrentAccount-Head office current account 24 HeadOfficeCurrentAccount,BranchCurrentAccount,CurrentDeposits,AccountsReceivable,ReserveDepositPayable,MerchandiseInventory,PrepaidExpenses,AccruedRevenue,CashOverShort,AccountsPayable+Head office current account 25 HeadOfficeCurrentAccount,BranchCurrentAccount,CurrentDeposits,AccountsReceivable,ReserveDepositPayable,MerchandiseInventory,PrepaidExpenses,AccruedRevenue,CashOverShort,AccountsPayable HeadOfficeCurrentAccount 1 HeadOfficeCurrentAccount Held-to-maturity 1 HeldToMaturityBonds Held-to-maturity bonds 5 HeldToMaturityBonds,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable@@ -514,13 +513,13 @@ IncomeTaxesRefundReceivable 1 IncomeTaxesRefundReceivable IncorporationExpenses 1 IncorporationExpenses Insurance 2 InsuranceGain,InsuranceExpense-Insurance expenses 26 InsuranceExpense,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,InsuranceGain+Insurance expenses 25 InsuranceExpense,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,InsuranceGain,OperatingExpenses InsuranceExpense 1 InsuranceExpense InsuranceGain 1 InsuranceGain Interest 9 InterestExpense,NationalBondInterestEarned,DepositInterestEarned,InterestEarned,LeaseholdRights,NonControllingInterests,InterestOnSecurities,NetIncomeAttributableToNCI,NetLossAttributableToNCI Interest earned 12 NationalBondInterestEarned,DepositInterestEarned,InterestEarned,InterestExpense,WageEarned,UnearnedRevenue,LeaseholdRights,NonControllingInterests,EarnedSurplus,InterestOnSecurities-Interest expense 81 InterestExpense,NetIncomeAttributableToNCI,Depreciation,AmortizationExpense,SalesCost,BusinessTrip,Commutation,UtilitiesExpense,RentExpense,AdvertisingExpense-Interest on securities 97 InterestOnSecurities,NationalBondInterestEarned,ValuationDifferenceOnOtherSecurities,NonControllingInterests,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities+Interest expense 81 InterestExpense,NetIncomeAttributableToNCI,Depreciation,AmortizationExpense,SalesCost,BusinessTrip,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses+Interest on securities 94 InterestOnSecurities,NationalBondInterestEarned,ValuationDifferenceOnOtherSecurities,NonControllingInterests,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities InterestEarned 3 NationalBondInterestEarned,DepositInterestEarned,InterestEarned InterestExpense 1 InterestExpense InterestOnSecurities 1 InterestOnSecurities@@ -528,7 +527,7 @@ Inventory shrinkage loss 20 InventoryShrinkageLoss,Products,NetLoss,MerchandiseInventory,CashOverShort,BadDebtLoss,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,MiscellaneousLoss,LossOnValuationOfMerchandise InventoryShrinkageLoss 1 InventoryShrinkageLoss Investment 6 InvestmentSecurities,InvestmentInAssociate,StockInvestment,EquipmentInvestment,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities-Investment in associate 82 InvestmentInAssociate,InvestmentSecurities,StockInvestment,EquipmentInvestment,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities,Deposits,Products,Machinery,Building+Investment in associate 81 InvestmentInAssociate,InvestmentSecurities,StockInvestment,EquipmentInvestment,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities,Deposits,Products,Machinery,Building Investment securities 15 InvestmentSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities,Securities,InvestmentInAssociate,StockInvestment,EquipmentInvestment,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnValuationOfSecurities InvestmentInAssociate 1 InvestmentInAssociate InvestmentSecurities 3 InvestmentSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities@@ -536,7 +535,7 @@ LandRentPaid 1 LandRentPaid LandRentReceived 1 LandRentReceived Lease 5 ReversalOfAllowanceForDoubtfulAccounts,LeasedAssets,LeaseholdRights,LeaseObligations,LeaseExpenses-Lease expenses 29 LeaseExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts,LeasedAssets+Lease expenses 28 LeaseExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts,LeasedAssets,LongTermPrepaidExpenses Lease liabilities 7 LeaseObligations,ReversalOfAllowanceForDoubtfulAccounts,LeasedAssets,LeaseholdRights,RefundLiabilities,DeferredTaxLiabilities,LeaseExpenses LeaseExpenses 1 LeaseExpenses LeaseObligations 1 LeaseObligations@@ -544,29 +543,29 @@ Leased assets 11 LeasedAssets,AccumulatedDepreciation,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,ReversalOfAllowanceForDoubtfulAccounts,ContractAssets,DeferredTaxAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets LeasedAssets 1 LeasedAssets Leasehold 1 LeaseholdRights-Leasehold interests in land 83 LeaseholdRights,NonControllingInterests,LandRentReceived,NetIncomeAttributableToNCI,NetLossAttributableToNCI,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery+Leasehold interests in land 82 LeaseholdRights,NonControllingInterests,LandRentReceived,NetIncomeAttributableToNCI,NetLossAttributableToNCI,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery LeaseholdRights 1 LeaseholdRights Legal 3 LegalRetainedEarnings,LegalCapitalSurplus,StatutoryWelfareExpenses-Legal (appropriated) retained earnings reserve 15 LegalRetainedEarnings,RetainedEarnings,AccumulatedDepreciation,EarnedSurplus,ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,EquityInEarningsOfInvestee,CommunicationExpenses,LegalCapitalSurplus+Legal (appropriated) retained earnings reserve 14 LegalRetainedEarnings,RetainedEarnings,AccumulatedDepreciation,EarnedSurplus,ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,EquityInEarningsOfInvestee,LegalCapitalSurplus,DividendEqualizationReserve Legal capital surplus 7 LegalCapitalSurplus,OtherCapitalSurplus,CapitalSurplus,CapitalStock,LegalRetainedEarnings,EarnedSurplus,StatutoryWelfareExpenses-Legal welfare expenses 27 StatutoryWelfareExpenses,WelfareExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,LegalRetainedEarnings,CommunicationExpenses+Legal welfare expenses 26 StatutoryWelfareExpenses,WelfareExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,LegalRetainedEarnings,CommunicationExpenses,LongTermPrepaidExpenses LegalCapitalSurplus 1 LegalCapitalSurplus LegalRetainedEarnings 1 LegalRetainedEarnings Liability: 41 LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,ReserveForDepreciation,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,CentralBankNotePayable,AccountsPayable Loans 8 LongTermLoansReceivable,ShortTermLoansReceivable,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,NotesLoansReceivable,NotesLoansPayable,LoansReceivable Loans payable 20 LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,NotesLoansPayable,LongTermLoansReceivable,ShortTermLoansReceivable,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,ReserveDepositPayable-Loans payable on notes 101 NotesLoansPayable,LongTermLoansPayable,NotesLoansReceivable,NonOperatingNotesPayable,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,CentralBankNotePayable+Loans payable on notes 98 NotesLoansPayable,LongTermLoansPayable,NotesLoansReceivable,NonOperatingNotesPayable,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,CentralBankNotePayable Loans receivable 23 LongTermLoansReceivable,ShortTermLoansReceivable,NotesLoansReceivable,LoansReceivable,AccountsReceivable,ReserveDepositReceivable,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,NotesReceivable-Loans receivable on notes 101 NotesLoansReceivable,LongTermLoansReceivable,NotesLoansPayable,LossOnSalesOfNotesReceivable,DishonoredNotesReceivable,NonOperatingNotesReceivable,ShortTermLoansReceivable,LongTermLoansPayable,NotesReceivable,ElectronicallyRecordedReceivable+Loans receivable on notes 98 NotesLoansReceivable,LongTermLoansReceivable,NotesLoansPayable,LossOnSalesOfNotesReceivable,DishonoredNotesReceivable,NonOperatingNotesReceivable,ShortTermLoansReceivable,LongTermLoansPayable,NotesReceivable,ElectronicallyRecordedReceivable LoansPayable 4 LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,NotesLoansPayable LoansReceivable 4 LongTermLoansReceivable,ShortTermLoansReceivable,NotesLoansReceivable,LoansReceivable Long-term 6 LongTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,LongTermNationalBondsPayable,LongTermPrepaidExpenses,LongTermOtherPayables-Long-term accounts payable - other 45 LongTermOtherPayables,LongTermLoansPayable,LongTermNationalBondsPayable,LongTermNationalBonds,LongTermLoansReceivable,ShortTermLoansPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,AccountsPayable,OtherPayables+Long-term accounts payable - other 46 LongTermOtherPayables,LongTermLoansPayable,LongTermNationalBondsPayable,LongTermNationalBonds,LongTermLoansReceivable,ShortTermLoansPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,AccountsPayable,OtherPayables Long-term loans payable 22 LongTermLoansPayable,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,LongTermNationalBondsPayable,NotesLoansPayable,LongTermOtherPayables,LongTermNationalBonds,ShortTermLoansReceivable,DepositPayable Long-term loans receivable 27 LongTermLoansReceivable,ShortTermLoansReceivable,LongTermLoansPayable,NotesLoansReceivable,LoansReceivable,LongTermNationalBonds,AccountsReceivable,ReserveDepositReceivable,ShortTermLoansPayable,LoansPayable-Long-term national bonds 11 LongTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBonds,ShortTermNationalBondsPayable,LongTermLoansReceivable,LongTermLoansPayable,NationalBondInterestEarned,LongTermPrepaidExpenses,LongTermOtherPayables,GainOnNationalSubsidies-Long-term national bonds payable 23 LongTermNationalBondsPayable,LongTermNationalBonds,ShortTermNationalBondsPayable,ShortTermNationalBonds,LongTermLoansPayable,LongTermOtherPayables,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,DepositPayable-Long-term prepaid expenses 32 LongTermPrepaidExpenses,PrepaidExpenses,LongTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,LongTermNationalBondsPayable,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses+Long-term national bonds 12 LongTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBonds,ShortTermNationalBondsPayable,LongTermLoansReceivable,LongTermLoansPayable,CentralBankPaymentExpense,NationalBondInterestEarned,LongTermPrepaidExpenses,LongTermOtherPayables+Long-term national bonds payable 24 LongTermNationalBondsPayable,LongTermNationalBonds,ShortTermNationalBondsPayable,ShortTermNationalBonds,LongTermLoansPayable,LongTermOtherPayables,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,DepositPayable+Long-term prepaid expenses 31 LongTermPrepaidExpenses,PrepaidExpenses,LongTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,LongTermNationalBondsPayable,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidCorporateIncomeTaxes LongTermLoansPayable 1 LongTermLoansPayable LongTermLoansReceivable 1 LongTermLoansReceivable LongTermNationalBonds 2 LongTermNationalBonds,LongTermNationalBondsPayable@@ -575,16 +574,16 @@ LongTermPrepaidExpenses 1 LongTermPrepaidExpenses Loss 18 NetLoss,CashOverShort,BadDebtLoss,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,MiscellaneousLoss,InventoryShrinkageLoss,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables Loss attributable to non-controlling interests 38 NetLossAttributableToNCI,NetIncomeAttributableToNCI,CashOverShort,NonControllingInterests,InventoryShrinkageLoss,LossOnRetirementOfFixedAssets,Products,StockInvestment,CapitalStock,CentralBankPaymentExpense-Loss on fire 95 LossOnFire,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnRetirementOfFixedAssets-Loss on retirement of non-current assets 116 LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfFixedAssets,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities-Loss on sale of electronically recorded monetary claims 114 LossOnSalesOfElectronicallyRecordedReceivables,ElectronicallyRecordedReceivable,NonOperatingElectronicallyRecordedReceivable,ElectronicallyRecordedObligations,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory-Loss on sale of investment securities 120 LossOnSalesOfInvestmentSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnValuationOfSecurities,MerchandiseInventory-Loss on sale of receivables 115 LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities-Loss on sale of securities 117 LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnValuationOfSecurities,MerchandiseInventory-Loss on sales of fixed assets 117 LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnDonationOfFixedAssets,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities-Loss on sales of notes receivable 124 LossOnSalesOfNotesReceivable,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfFixedAssets,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,NotesLoansReceivable,MerchandiseInventory,GainOnSalesOfFixedAssets,DishonoredNotesReceivable-Loss on tax purpose reduction entry of non-current assets 122 LossOnReductionOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfFixedAssets,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities-Loss on valuation of securities 114 LossOnValuationOfSecurities,GainOnValuationOfSecurities,LossOnValuationOfMerchandise,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities+Loss on fire 92 LossOnFire,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnRetirementOfFixedAssets+Loss on retirement of non-current assets 115 LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfFixedAssets,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities+Loss on sale of electronically recorded monetary claims 113 LossOnSalesOfElectronicallyRecordedReceivables,ElectronicallyRecordedReceivable,NonOperatingElectronicallyRecordedReceivable,ElectronicallyRecordedObligations,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory+Loss on sale of investment securities 119 LossOnSalesOfInvestmentSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnValuationOfSecurities,MerchandiseInventory+Loss on sale of receivables 114 LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities+Loss on sale of securities 116 LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnValuationOfSecurities,MerchandiseInventory+Loss on sales of fixed assets 116 LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnDonationOfFixedAssets,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities+Loss on sales of notes receivable 123 LossOnSalesOfNotesReceivable,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfFixedAssets,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,NotesLoansReceivable,MerchandiseInventory,GainOnSalesOfFixedAssets,DishonoredNotesReceivable+Loss on tax purpose reduction entry of non-current assets 121 LossOnReductionOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfFixedAssets,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities+Loss on valuation of securities 113 LossOnValuationOfSecurities,GainOnValuationOfSecurities,LossOnValuationOfMerchandise,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities LossOnFire 1 LossOnFire LossOnReductionOfFixedAssets 1 LossOnReductionOfFixedAssets LossOnRetirementOfFixedAssets 1 LossOnRetirementOfFixedAssets@@ -597,12 +596,12 @@ LossOnValuationOfMerchandise 1 LossOnValuationOfMerchandise LossOnValuationOfSecurities 1 LossOnValuationOfSecurities Machinery 1 Machinery-Machinery and equipment 18 Machinery,Fixtures,Products,EquipmentInvestment,BusinessTrip,MerchandiseInventory,Land,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand+Machinery and equipment 19 Machinery,Fixtures,Products,EquipmentInvestment,BusinessTrip,MerchandiseInventory,Land,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand Maintenance 1 MaintenanceExpenses-Maintenance expenses 25 MaintenanceExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses+Maintenance expenses 24 MaintenanceExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses MaintenanceExpenses 1 MaintenanceExpenses Meeting 1 MeetingExpenses-Meeting expenses 25 MeetingExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses+Meeting expenses 24 MeetingExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses MeetingExpenses 1 MeetingExpenses Membership 1 MembershipFees Membership fees 3 MembershipFees,ReceiptFee,PaymentFees@@ -617,8 +616,8 @@ MiscellaneousIncome 2 CashOverShort,MiscellaneousIncome MiscellaneousIncome/MiscellaneousLoss 1 CashOverShort MiscellaneousLoss 2 CashOverShort,MiscellaneousLoss-National 6 LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,NationalBondInterestEarned,GainOnNationalSubsidies-National bond interest earned 18 NationalBondInterestEarned,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,DepositInterestEarned,InterestEarned,InterestExpense,WageEarned,UnearnedRevenue+National 7 LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,CentralBankPaymentExpense,NationalBondInterestEarned,GainOnNationalSubsidies+National bond interest earned 19 NationalBondInterestEarned,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,DepositInterestEarned,InterestEarned,InterestExpense,CentralBankPaymentExpense,WageEarned NationalBondInterestEarned 1 NationalBondInterestEarned Net 11 NetIncome,NetLoss,ElectronicallyRecordedReceivable,ElectronicallyRecordedObligations,AllowanceForDoubtfulAccounts,NetDefinedBenefitAsset,NonOperatingElectronicallyRecordedReceivable,NetDefinedBenefitLiability,LossOnSalesOfElectronicallyRecordedReceivables,NetIncomeAttributableToNCI Net income 27 NetIncome,NetIncomeAttributableToNCI,SubsidyIncome,RentalIncome,WageEarned,CentralBankPaymentIncome,NetLoss,ElectronicallyRecordedReceivable,PrepaidCorporateIncomeTaxes,CashOverShort@@ -631,7 +630,7 @@ NetLossAttributableToNCI 1 NetLossAttributableToNCI NewspaperBooksExpenses 1 NewspaperBooksExpenses Newspapers 1 NewspaperBooksExpenses-Newspapers and books 18 NewspaperBooksExpenses,Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand+Newspapers and books 19 NewspaperBooksExpenses,Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand NoClose: 2 NetIncomeAttributableToNCI,NetLossAttributableToNCI Non-controlling 3 NonControllingInterests,NetIncomeAttributableToNCI,NetLossAttributableToNCI Non-controlling interests 4 NonControllingInterests,NetIncomeAttributableToNCI,NetLossAttributableToNCI,LeaseholdRights@@ -652,7 +651,7 @@ NotesReceivable 4 NotesReceivable,LossOnSalesOfNotesReceivable,DishonoredNotesReceivable,NonOperatingNotesReceivable OCI/資本の部の項目) 1 CumulativeTranslationAdjustment Operating 6 NonOperatingNotesReceivable,NonOperatingElectronicallyRecordedReceivable,NonOperatingNotesPayable,NonOperatingElectronicallyRecordedObligations,OperatingRevenue,OperatingExpenses-Operating expenses 30 OperatingExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,NonOperatingNotesReceivable+Operating expenses 29 OperatingExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,NonOperatingNotesReceivable,NonOperatingElectronicallyRecordedReceivable Operating revenue 46 OperatingRevenue,ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome OperatingExpenses 1 OperatingExpenses OperatingRevenue 1 OperatingRevenue@@ -660,43 +659,44 @@ Ordinary profit 3 OrdinaryProfit,GrossProfit,NetIncomeAttributableToNCI OrdinaryProfit 1 OrdinaryProfit Organization 1 IncorporationExpenses-Organization expenses 25 IncorporationExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses-Other 5 OtherReceivables,OtherPayables,LongTermOtherPayables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities-Other capital surplus 9 OtherCapitalSurplus,LegalCapitalSurplus,CapitalSurplus,CapitalStock,OtherReceivables,OtherPayables,LongTermOtherPayables,ValuationDifferenceOnOtherSecurities,EarnedSurplus-Other payables 5 OtherPayables,LongTermOtherPayables,OtherReceivables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities-Other receivables 8 OtherReceivables,OtherPayables,AllowanceForDoubtfulAccounts,LongTermOtherPayables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables+Organization expenses 24 IncorporationExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses+Other 6 OtherReceivables,OtherPayables,LongTermOtherPayables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities,DirectorsCompensations+Other capital surplus 10 OtherCapitalSurplus,LegalCapitalSurplus,CapitalSurplus,CapitalStock,OtherReceivables,OtherPayables,LongTermOtherPayables,ValuationDifferenceOnOtherSecurities,EarnedSurplus,DirectorsCompensations+Other payables 6 OtherPayables,LongTermOtherPayables,OtherReceivables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities,DirectorsCompensations+Other receivables 9 OtherReceivables,OtherPayables,AllowanceForDoubtfulAccounts,LongTermOtherPayables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,DirectorsCompensations OtherCapitalSurplus 1 OtherCapitalSurplus OtherPayables 2 OtherPayables,LongTermOtherPayables OtherReceivables 1 OtherReceivables Patent 2 Patent,AmortizationOfPatents Payment 6 CentralBankPaymentExpense,ReceiptFee,CentralBankPaymentIncome,PaymentsOnBehalf,SuspensePayments,PaymentFees Payment fees / fees paid 38 PaymentFees,ReceiptFee,CentralBankPaymentExpense,CentralBankPaymentIncome,MembershipFees,Products,ReserveDepositReceivable,GovernmentService,ReserveForDepreciation,DepositPayable+Payment to national treasury 33 CentralBankPaymentExpense,LongTermNationalBonds,ShortTermNationalBonds,Products,StockInvestment,CapitalStock,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,NationalBondInterestEarned,ReceiptFee PaymentFees 2 ReceiptFee,PaymentFees Payments 2 PaymentsOnBehalf,SuspensePayments-Payments made on behalf 90 PaymentsOnBehalf,LongTermNationalBonds,ShortTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,ReserveForDepreciation,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,Depreciation,AmortizationExpense+Payments made on behalf 87 PaymentsOnBehalf,LongTermNationalBonds,ShortTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,ReserveForDepreciation,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,Depreciation,AmortizationExpense PaymentsOnBehalf 1 PaymentsOnBehalf Petty 1 PettyCash Petty cash 3 PettyCash,Cash,CashOverShort PettyCash 1 PettyCash Prepaid 4 PrepaidExpenses,PrepaidCorporateIncomeTaxes,LongTermPrepaidExpenses,PrepaidPensionCost Prepaid corporate income taxes 23 PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,IncomeTaxesRefundReceivable,AdditionalIncomeTaxesForPriorPeriods,RefundOfIncomeTaxes,IncomeTaxesAdjustment,TaxesExpense,NetIncome,SubsidyIncome-Prepaid expenses 27 PrepaidExpenses,LongTermPrepaidExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidCorporateIncomeTaxes,AccruedExpenses,CommunicationExpenses,PrepaidPensionCost+Prepaid expenses 26 PrepaidExpenses,LongTermPrepaidExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidCorporateIncomeTaxes,AccruedExpenses,CommunicationExpenses,PrepaidPensionCost,OperatingExpenses Prepaid pension costs 6 PrepaidPensionCost,PrepaidExpenses,PrepaidCorporateIncomeTaxes,LongTermPrepaidExpenses,StockIssuanceCosts,StorageExpenses PrepaidCorporateIncomeTaxes 1 PrepaidCorporateIncomeTaxes PrepaidExpenses 2 PrepaidExpenses,LongTermPrepaidExpenses PrepaidPensionCost 1 PrepaidPensionCost Products 2 Products,MerchandiseInventory Profit 3 GrossProfit,OrdinaryProfit,NetIncomeAttributableToNCI-Profit attributable to non-controlling interests 26 NetIncomeAttributableToNCI,NetLossAttributableToNCI,NonControllingInterests,Products,StockInvestment,CapitalStock,CentralBankPaymentExpense,GrossProfit,OrdinaryProfit,CentralBankPaymentIncome+Profit attributable to non-controlling interests 26 NetIncomeAttributableToNCI,NetLossAttributableToNCI,NonControllingInterests,Products,StockInvestment,CapitalStock,CentralBankPaymentExpense,GrossProfit,OrdinaryProfit,MerchandiseInventory Property 1 PropertyTaxPayable Property tax payable 32 PropertyTaxPayable,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,CentralBankNotePayable,TaxesExpense PropertyTaxPayable 1 PropertyTaxPayable-Provision 11 ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties-Provision for bonuses 31 AllowanceForBonuses,ProvisionForBonuses,ReversalOfAllowanceForBonuses,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs-Provision for doubtful accounts 34 ProvisionForDoubtfulAccounts,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs-Provision for repairs 30 AllowanceForRepairs,ReversalOfAllowanceForRepairs,ProvisionForRepairs,ProvisionForDoubtfulAccounts,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,RepairFundReserve,ReversalOfAllowanceForProductWarranties,ProvisionForBonuses-Provision for retirement benefits 33 AllowanceForRetirementBenefits,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties-Provision for warranties 29 AllowanceForProductWarranties,ReversalOfAllowanceForProductWarranties,ProvisionForProductWarranties,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ProvisionForRepairs,ProvisionForBonuses+Provision 5 ProvisionForDoubtfulAccounts,AllowanceForRetirementBenefits,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties+Provision for bonuses 32 ProvisionForBonuses,ProvisionForDoubtfulAccounts,AllowanceForBonuses,AllowanceForRetirementBenefits,ProvisionForRepairs,ProvisionForProductWarranties,ReversalOfAllowanceForBonuses,RetainedEarnings,ReserveForDepreciation,AmortizationExpense+Provision for doubtful accounts 35 ProvisionForDoubtfulAccounts,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRetirementBenefits,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,AccountsReceivable,RetainedEarnings,ReserveForDepreciation+Provision for repairs 31 ProvisionForRepairs,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForRetirementBenefits,RepairFundReserve,ReversalOfAllowanceForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,RetainedEarnings,ReserveForDepreciation+Provision for retirement benefits 34 AllowanceForRetirementBenefits,ProvisionForDoubtfulAccounts,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,RetainedEarnings,ReserveForDepreciation,AmortizationExpense,MerchandiseInventory,AllowanceForDoubtfulAccounts+Provision for warranties 30 ProvisionForProductWarranties,ProvisionForDoubtfulAccounts,AllowanceForProductWarranties,AllowanceForRetirementBenefits,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs,ProvisionForBonuses,RetainedEarnings,ReserveForDepreciation,AmortizationExpense ProvisionForBonuses 1 ProvisionForBonuses ProvisionForDoubtfulAccounts 1 ProvisionForDoubtfulAccounts ProvisionForProductWarranties 1 ProvisionForProductWarranties@@ -711,59 +711,60 @@ Raw 1 RawMaterials Raw materials 1 RawMaterials RawMaterials 1 RawMaterials-Real 1 Building-Real estate 1 Building Receipt 5 ReceiptFee,SuspenseReceipts,PaymentFees,GainOnDonationOfFixedAssets,GainOnNationalSubsidies Receipt fee 6 ReceiptFee,PaymentFees,SuspenseReceipts,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,MembershipFees ReceiptFee 2 ReceiptFee,PaymentFees Recognized 1 EquityInEarningsOfInvestee Recovery 1 RecoveryOfBadDebts-Recovery of bad debts written off 42 RecoveryOfBadDebts,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,HeadOfficeCurrentAccount,DepositsReceivedFromOfficers,SalesCost,GrossProfit+Recovery of bad debts written off 42 RecoveryOfBadDebts,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,HeadOfficeCurrentAccount,DepositsReceivedFromOfficers,DirectorsCompensations,SalesCost RecoveryOfBadDebts 1 RecoveryOfBadDebts Refund 4 IncomeTaxesRefundReceivable,RefundLiabilities,RefundOfIncomeTaxes,ConsumptionTaxRefundReceivable Refund liabilities 6 RefundLiabilities,IncomeTaxesRefundReceivable,DeferredTaxLiabilities,LeaseObligations,RefundOfIncomeTaxes,ConsumptionTaxRefundReceivable Refund of income taxes 61 RefundOfIncomeTaxes,IncomeTaxesRefundReceivable,PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,AdditionalIncomeTaxesForPriorPeriods,IncomeTaxesAdjustment,NetIncomeAttributableToNCI,SalesCost,TaxesExpense RefundLiabilities 1 RefundLiabilities RefundOfIncomeTaxes 1 RefundOfIncomeTaxes+Remuneration 1 DirectorsCompensations+Remuneration for directors (and other officers) 34 DirectorsCompensations,ValuationDifferenceOnOtherSecurities,RetainedEarnings,ReserveForDepreciation,AmortizationExpense,MerchandiseInventory,OtherReceivables,OtherPayables,AllowanceForDoubtfulAccounts,AccumulatedDepreciation Rent 10 CurrentDeposits,RentExpense,RentalIncome,GainOnDonationOfFixedAssets,LandRentReceived,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LandRentPaid,BranchCurrentAccount,HeadOfficeCurrentAccount-Rent expenses on land 117 LandRentPaid,Commutation,CommunicationExpenses,LongTermPrepaidExpenses,GainOnDonationOfFixedAssets,LandRentReceived,IncorporationExpenses,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,CurrentDeposits+Rent expenses on land 114 LandRentPaid,CommunicationExpenses,LongTermPrepaidExpenses,GainOnDonationOfFixedAssets,LandRentReceived,IncorporationExpenses,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,CurrentDeposits,LongTermNationalBonds RentExpense 1 RentExpense Rental 2 RentalIncome,LandRentReceived Rental income 18 RentalIncome,LandRentReceived,NetIncome,SubsidyIncome,WageEarned,CentralBankPaymentIncome,PrepaidCorporateIncomeTaxes,CashOverShort,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes Rental income from land 24 LandRentReceived,RentalIncome,NetIncome,SubsidyIncome,WageEarned,CentralBankPaymentIncome,PrepaidCorporateIncomeTaxes,Land,CashOverShort,AccruedCorporateIncomeTaxes RentalIncome 1 RentalIncome Repair 5 AllowanceForRepairs,RepairFundReserve,ReversalOfAllowanceForRepairs,ProvisionForRepairs,RepairsExpense-Repair expenses 29 RepairsExpense,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,AllowanceForRepairs+Repair expenses 28 RepairsExpense,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,AllowanceForRepairs,RepairFundReserve RepairFundReserve 1 RepairFundReserve RepairsExpense 1 RepairsExpense Research 1 ResearchAndDevelopmentExpenses-Research and development expenses 39 ResearchAndDevelopmentExpenses,DevelopmentExpenses,LandRentPaid,NewspaperBooksExpenses,Products,Machinery,BusinessTrip,Commutation,DeliveryExpenses,SuppliesExpenses+Research and development expenses 39 ResearchAndDevelopmentExpenses,DevelopmentExpenses,LandRentPaid,NewspaperBooksExpenses,Products,Machinery,BusinessTrip,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses ResearchAndDevelopmentExpenses 1 ResearchAndDevelopmentExpenses Reserve 9 ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,AccumulatedDepreciation,LegalRetainedEarnings,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve,GeneralReserve Reserve deposits, asset side 89 ReserveDepositReceivable,ReserveDepositPayable,AccumulatedDepreciation,AllowanceForDoubtfulAccounts,IncomeSummary,Cash,Deposits,CurrentDeposits,Securities,InvestmentSecurities Reserve deposits, liability side 50 ReserveDepositPayable,ReserveDepositReceivable,ReserveForDepreciation,AccumulatedDepreciation,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable-Reserve for depreciation 34 ReserveForDepreciation,AccumulatedDepreciation,AmortizationExpense,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve,ReserveDepositReceivable,ReserveDepositPayable,Depreciation,MerchandiseInventory-Reserve for dividend equalization 35 DividendEqualizationReserve,ReserveForDepreciation,AccumulatedDepreciation,RepairFundReserve,ConstructionFundReserve,ReserveDepositReceivable,ReserveDepositPayable,AmortizationExpense,MerchandiseInventory,UnpaidDividends-Reserve for new construction 35 ConstructionFundReserve,ReserveForDepreciation,AccumulatedDepreciation,DividendEqualizationReserve,RepairFundReserve,GainOnConstructionGrants,ReserveDepositReceivable,ReserveDepositPayable,AmortizationExpense,MerchandiseInventory-Reserve for repairs 34 RepairFundReserve,ReserveForDepreciation,AccumulatedDepreciation,AllowanceForRepairs,DividendEqualizationReserve,ConstructionFundReserve,ReversalOfAllowanceForRepairs,ProvisionForRepairs,ReserveDepositReceivable,ReserveDepositPayable+Reserve for depreciation 35 ReserveForDepreciation,AccumulatedDepreciation,AmortizationExpense,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve,ReserveDepositReceivable,RetainedEarnings,ReserveDepositPayable,Depreciation+Reserve for dividend equalization 36 DividendEqualizationReserve,ReserveForDepreciation,AccumulatedDepreciation,RepairFundReserve,ConstructionFundReserve,ReserveDepositReceivable,RetainedEarnings,ReserveDepositPayable,AmortizationExpense,MerchandiseInventory+Reserve for new construction 36 ConstructionFundReserve,ReserveForDepreciation,AccumulatedDepreciation,DividendEqualizationReserve,RepairFundReserve,GainOnConstructionGrants,ReserveDepositReceivable,RetainedEarnings,ReserveDepositPayable,AmortizationExpense+Reserve for repairs 35 RepairFundReserve,ReserveForDepreciation,AccumulatedDepreciation,AllowanceForRepairs,DividendEqualizationReserve,ConstructionFundReserve,ReversalOfAllowanceForRepairs,ProvisionForRepairs,ReserveDepositReceivable,RetainedEarnings ReserveDepositPayable 1 ReserveDepositPayable ReserveDepositReceivable 1 ReserveDepositReceivable ReserveForDepreciation 2 ReserveForDepreciation,AccumulatedDepreciation-Retained 5 RetainedEarnings,AccumulatedDepreciation,LegalRetainedEarnings,CommunicationExpenses,EarnedSurplus-Retained earnings 6 RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,EquityInEarningsOfInvestee,AccumulatedDepreciation,CommunicationExpenses+Retained 4 RetainedEarnings,AccumulatedDepreciation,LegalRetainedEarnings,EarnedSurplus+Retained earnings 5 RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,EquityInEarningsOfInvestee,AccumulatedDepreciation+Retained earnings brought forward 5 RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,EquityInEarningsOfInvestee,AccumulatedDepreciation RetainedEarnings 2 RetainedEarnings,LegalRetainedEarnings Retirement 5 NetDefinedBenefitAsset,AllowanceForRetirementBenefits,NetDefinedBenefitLiability,RetirementBenefitExpenses,LossOnRetirementOfFixedAssets Retirement benefit asset 85 NetDefinedBenefitAsset,AllowanceForRetirementBenefits,NetDefinedBenefitLiability,RetirementBenefitExpenses,LossOnRetirementOfFixedAssets,Cash,Deposits,CurrentDeposits,Securities,InvestmentSecurities-Retirement benefit expenses 29 RetirementBenefitExpenses,NetDefinedBenefitAsset,AllowanceForRetirementBenefits,NetDefinedBenefitLiability,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses+Retirement benefit expenses 28 RetirementBenefitExpenses,NetDefinedBenefitAsset,AllowanceForRetirementBenefits,NetDefinedBenefitLiability,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses Retirement benefit liability 44 AllowanceForRetirementBenefits,NetDefinedBenefitLiability,NetDefinedBenefitAsset,RetirementBenefitExpenses,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,ReserveForDepreciation,DepositPayable,LongTermNationalBondsPayable RetirementBenefitExpenses 1 RetirementBenefitExpenses Revenue 41 ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome,WageEarned Revenue: 39 ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome,WageEarned Reversal 4 ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses-Reversal of allowance for doubtful accounts 70 ReversalOfAllowanceForDoubtfulAccounts,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses,ProvisionForDoubtfulAccounts,MerchandiseInventory,CommunicationExpenses,AllowanceForRepairs,AllowanceForProductWarranties-Reversal of provision for bonuses 65 ReversalOfAllowanceForBonuses,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForBonuses,ProvisionForBonuses,MerchandiseInventory,ProvisionForDoubtfulAccounts,CommunicationExpenses,AllowanceForRepairs-Reversal of provision for repairs 64 ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,ProvisionForRepairs,MerchandiseInventory,ProvisionForDoubtfulAccounts,CommunicationExpenses,AllowanceForProductWarranties-Reversal of provision for warranties 63 ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForBonuses,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForProductWarranties,ProvisionForProductWarranties,MerchandiseInventory,ProvisionForDoubtfulAccounts,CommunicationExpenses,AllowanceForRepairs+Reversal of allowance for bonuses 68 ReversalOfAllowanceForBonuses,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,AllowanceForBonuses,MerchandiseInventory,AllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForRetirementBenefits+Reversal of allowance for doubtful accounts 71 ReversalOfAllowanceForDoubtfulAccounts,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses,ProvisionForDoubtfulAccounts,MerchandiseInventory,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses+Reversal of allowance for repairs 67 ReversalOfAllowanceForRepairs,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses,AllowanceForRepairs,MerchandiseInventory,AllowanceForDoubtfulAccounts,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits+Reversal of allowance for warranties 66 ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForBonuses,AllowanceForProductWarranties,MerchandiseInventory,AllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForBonuses,AllowanceForRetirementBenefits ReversalOfAllowanceForBonuses 1 ReversalOfAllowanceForBonuses ReversalOfAllowanceForDoubtfulAccounts 1 ReversalOfAllowanceForDoubtfulAccounts ReversalOfAllowanceForProductWarranties 1 ReversalOfAllowanceForProductWarranties@@ -791,14 +792,14 @@ Short-term 4 ShortTermNationalBonds,ShortTermLoansReceivable,ShortTermLoansPayable,ShortTermNationalBondsPayable Short-term loans payable 21 ShortTermLoansPayable,ShortTermLoansReceivable,LongTermLoansPayable,LoansPayable,ShortTermNationalBondsPayable,NotesLoansPayable,ShortTermNationalBonds,LongTermLoansReceivable,DepositPayable,LongTermNationalBondsPayable Short-term loans receivable 25 ShortTermLoansReceivable,LongTermLoansReceivable,ShortTermLoansPayable,NotesLoansReceivable,LoansReceivable,ShortTermNationalBonds,AccountsReceivable,ReserveDepositReceivable,LongTermLoansPayable,LoansPayable-Short-term national bonds 9 ShortTermNationalBonds,ShortTermNationalBondsPayable,LongTermNationalBonds,LongTermNationalBondsPayable,ShortTermLoansReceivable,ShortTermLoansPayable,NationalBondInterestEarned,GainOnNationalSubsidies,HeldToMaturityBonds-Short-term national bonds payable 22 ShortTermNationalBondsPayable,ShortTermNationalBonds,LongTermNationalBondsPayable,LongTermNationalBonds,ShortTermLoansPayable,ShortTermLoansReceivable,LongTermLoansPayable,LoansPayable,DepositPayable,ReserveDepositPayable+Short-term national bonds 10 ShortTermNationalBonds,ShortTermNationalBondsPayable,LongTermNationalBonds,LongTermNationalBondsPayable,ShortTermLoansReceivable,ShortTermLoansPayable,CentralBankPaymentExpense,NationalBondInterestEarned,GainOnNationalSubsidies,HeldToMaturityBonds+Short-term national bonds payable 23 ShortTermNationalBondsPayable,ShortTermNationalBonds,LongTermNationalBondsPayable,LongTermNationalBonds,ShortTermLoansPayable,ShortTermLoansReceivable,LongTermLoansPayable,LoansPayable,DepositPayable,ReserveDepositPayable ShortTermLoansPayable 1 ShortTermLoansPayable ShortTermLoansReceivable 1 ShortTermLoansReceivable ShortTermNationalBonds 2 ShortTermNationalBonds,ShortTermNationalBondsPayable ShortTermNationalBondsPayable 1 ShortTermNationalBondsPayable Software 3 Software,SoftwareInProgress,AmortizationOfSoftware-Software in progress 83 SoftwareInProgress,ConstructionInProgress,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment+Software in progress 82 SoftwareInProgress,ConstructionInProgress,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment SoftwareInProgress 1 SoftwareInProgress StatutoryWelfareExpenses 1 StatutoryWelfareExpenses Stock 6 StockInvestment,CapitalStock,StockSubscriptionDeposits,StockIssuanceCosts,SubsidiaryStocks,AffiliateStocks@@ -817,6 +818,8 @@ SubsidyExpense 1 SubsidyExpense SubsidyIncome 1 SubsidyIncome Supplies 2 SuppliesExpenses,SuppliesOnHand+Supplies expense 75 SuppliesExpenses,Depreciation,AmortizationExpense,SalesCost,BusinessTrip,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses,MiscellaneousExpenses+Supplies on hand 89 SuppliesOnHand,MerchandiseInventory,LossOnValuationOfMerchandise,LongTermNationalBonds,ShortTermNationalBonds,Products,LongTermLoansReceivable,LongTermLoansPayable,ReserveForDepreciation,LongTermNationalBondsPayable SuppliesExpenses 1 SuppliesExpenses SuppliesOnHand 1 SuppliesOnHand Suspense 4 SuspensePayments,CashOverShort,SuspenseReceipts,SuspenseAccount@@ -836,14 +839,14 @@ Time deposits 12 TimeDeposits,Deposits,CurrentDeposits,ReserveDepositReceivable,DepositPayable,ReserveDepositPayable,DepositsReceived,SecurityDepositsPaid,DepositsInSpecialAccounts,GuaranteeDepositsReceived TimeDeposits 1 TimeDeposits Tools 1 ToolsAndInstruments-Tools and instruments 17 ToolsAndInstruments,Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand+Tools and instruments 18 ToolsAndInstruments,Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand ToolsAndInstruments 1 ToolsAndInstruments Trademark 1 Trademark Trading 1 TradingSecurities Trading securities 12 TradingSecurities,Securities,InvestmentSecurities,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnValuationOfSecurities,InterestOnSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnValuationOfSecurities TradingSecurities 1 TradingSecurities Travel 1 BusinessTrip-Travel and transportation 17 BusinessTrip,Products,Machinery,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand,ToolsAndInstruments+Travel and transportation 18 BusinessTrip,Products,Machinery,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand,ToolsAndInstruments Unearned 1 UnearnedRevenue Unearned revenue 41 UnearnedRevenue,ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome UnearnedRevenue 1 UnearnedRevenue@@ -854,8 +857,8 @@ Utilities 1 UtilitiesExpense UtilitiesExpense 1 UtilitiesExpense Valuation 6 AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities,LossOnValuationOfMerchandise,LossOnValuationOfSecurities-Valuation difference on available-for-sale securities 93 ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities,LossOnValuationOfSecurities,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,GainOnSalesOfSecurities,InterestOnSecurities,GainOnSalesOfInvestmentSecurities,LossOnValuationOfMerchandise,LossOnSalesOfSecurities-Valuation loss on goods 96 LossOnValuationOfMerchandise,LossOnValuationOfSecurities,MerchandiseInventory,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities,LossOnSalesOfElectronicallyRecordedReceivables+Valuation difference on available-for-sale securities 90 ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities,LossOnValuationOfSecurities,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,GainOnSalesOfSecurities,InterestOnSecurities,GainOnSalesOfInvestmentSecurities,LossOnValuationOfMerchandise,LossOnSalesOfSecurities+Valuation loss on goods 93 LossOnValuationOfMerchandise,LossOnValuationOfSecurities,MerchandiseInventory,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities,LossOnSalesOfElectronicallyRecordedReceivables ValuationDifferenceOnOtherSecurities 1 ValuationDifferenceOnOtherSecurities Value 2 ValueAdded,AllowanceForDoubtfulAccounts Value added 2 ValueAdded,AllowanceForDoubtfulAccounts@@ -868,10 +871,10 @@ WageExpenditure 1 WageExpenditure Wages 1 WageExpenditure Welfare 2 WelfareExpenses,StatutoryWelfareExpenses-Welfare expenses 25 WelfareExpenses,StatutoryWelfareExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses+Welfare expenses 24 WelfareExpenses,StatutoryWelfareExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses WelfareExpenses 2 WelfareExpenses,StatutoryWelfareExpenses Work 1 WorkInProcess-Work in process 81 WorkInProcess,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment,RetainedEarnings+Work in process 80 WorkInProcess,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment,RetainedEarnings WorkInProcess 1 WorkInProcess a 221 Cash,Deposits,CurrentDeposits,Securities,InvestmentSecurities,InvestmentInAssociate,LongTermNationalBonds,ShortTermNationalBonds,Products,Machinery accepted 1 DepositPayable@@ -885,7 +888,7 @@ accrued (unpaid) consumption tax 21 AccruedConsumptionTax,AccruedCorporateIncomeTaxes,ConsumptionTaxPaid,ConsumptionTaxReceived,ConsumptionTaxRefundReceivable,TaxesExpense,ConsumptionExpenditure,TaxesRevenue,AccruedRevenue,PrepaidCorporateIncomeTaxes accrued (unpaid) corporate income taxes 24 AccruedCorporateIncomeTaxes,PrepaidCorporateIncomeTaxes,CorporateIncomeTaxes,AccruedConsumptionTax,IncomeTaxesRefundReceivable,AdditionalIncomeTaxesForPriorPeriods,RefundOfIncomeTaxes,IncomeTaxesAdjustment,TaxesExpense,NetIncome accrued bonuses 9 BonusesPayable,AccruedRevenue,AccruedExpenses,AccruedConsumptionTax,AccruedCorporateIncomeTaxes,AllowanceForBonuses,Bonuses,ProvisionForBonuses,ReversalOfAllowanceForBonuses-accrued expenses 29 AccruedExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedRevenue,AccruedConsumptionTax,AccruedCorporateIncomeTaxes,CommunicationExpenses+accrued expenses 28 AccruedExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedRevenue,AccruedConsumptionTax,AccruedCorporateIncomeTaxes,CommunicationExpenses,LongTermPrepaidExpenses accrued revenue 45 AccruedRevenue,ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome accruedconsumptiontax 1 AccruedConsumptionTax accruedcorporateincometaxes 1 AccruedCorporateIncomeTaxes@@ -895,25 +898,28 @@ accumulated depreciation 4 ReserveForDepreciation,AccumulatedDepreciation,Depreciation,AmortizationExpense accumulateddepreciation 2 ReserveForDepreciation,AccumulatedDepreciation added 1 ValueAdded-additional income taxes for prior periods 48 AdditionalIncomeTaxesForPriorPeriods,PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,IncomeTaxesRefundReceivable,RefundOfIncomeTaxes,IncomeTaxesAdjustment,ReserveForDepreciation,AmortizationExpense,TaxesExpense+additional income taxes for prior periods 49 AdditionalIncomeTaxesForPriorPeriods,PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,IncomeTaxesRefundReceivable,RefundOfIncomeTaxes,IncomeTaxesAdjustment,RetainedEarnings,ReserveForDepreciation,AmortizationExpense additionalincometaxesforpriorperiods 1 AdditionalIncomeTaxesForPriorPeriods adjustment 2 CumulativeTranslationAdjustment,IncomeTaxesAdjustment advances paid 13 AdvancesPaid,PrepaidExpenses,ConsumptionTaxPaid,PrepaidCorporateIncomeTaxes,AdvancesReceived,AccruedConsumptionTax,AccruedCorporateIncomeTaxes,UnpaidDividends,PaymentFees,SecurityDepositsPaid-advances received 11 AdvancesReceived,DepositPayable,AdvancesPaid,DepositsReceived,ConsumptionTaxReceived,GiftCertificatesReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants,LandRentReceived+advances received 12 AdvancesReceived,DepositPayable,CentralBankPaymentIncome,AdvancesPaid,DepositsReceived,ConsumptionTaxReceived,GiftCertificatesReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants advancespaid 1 AdvancesPaid advancesreceived 1 AdvancesReceived advertising 1 AdvertisingExpense advertisingexpense 1 AdvertisingExpense affiliatestocks 1 AffiliateStocks allowance 11 AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,SalesAllowances,PurchaseAllowances-allowance for doubtful accounts 36 AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses+allowance for bonuses 34 AllowanceForBonuses,ReversalOfAllowanceForBonuses,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForBonuses+allowance for doubtful accounts 37 AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses+allowance for repairs 33 AllowanceForRepairs,ReversalOfAllowanceForRepairs,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,RepairFundReserve,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs+allowance for warranties 32 AllowanceForProductWarranties,ReversalOfAllowanceForProductWarranties,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ProvisionForProductWarranties,ReversalOfAllowanceForBonuses allowanceforbonuses 2 AllowanceForBonuses,ReversalOfAllowanceForBonuses allowancefordoubtfulaccounts 2 AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts allowanceforproductwarranties 2 AllowanceForProductWarranties,ReversalOfAllowanceForProductWarranties allowanceforrepairs 2 AllowanceForRepairs,ReversalOfAllowanceForRepairs allowanceforretirementbenefits 1 AllowanceForRetirementBenefits allowances 2 SalesAllowances,PurchaseAllowances-amortization expense for intangibles 95 AmortizationExpense,ProvisionForDoubtfulAccounts,CommunicationExpenses,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationOfPatents,AdditionalIncomeTaxesForPriorPeriods+amortization expense for intangibles 96 AmortizationExpense,ProvisionForDoubtfulAccounts,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationOfPatents,AdditionalIncomeTaxesForPriorPeriods,ForeignExchangeLosses amortization of goodwill 43 AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationOfPatents,AmortizationExpense,SalesCost,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee,MerchandiseInventory,Software amortization of patent rights 44 AmortizationOfPatents,AmortizationOfGoodwill,AmortizationOfSoftware,AmortizationExpense,SalesCost,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee,MerchandiseInventory,Patent amortization of software 42 AmortizationOfSoftware,Software,SoftwareInProgress,AmortizationOfGoodwill,AmortizationOfPatents,AmortizationExpense,SalesCost,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee@@ -922,20 +928,19 @@ amortizationofpatents 1 AmortizationOfPatents amortizationofsoftware 1 AmortizationOfSoftware amount 1 InvestmentInAssociate-and 17 Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand,ToolsAndInstruments-as 91 Cash,Deposits,CurrentDeposits,Securities,InvestmentSecurities,InvestmentInAssociate,LongTermNationalBonds,ShortTermNationalBonds,Products,Machinery+and 18 Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand,ToolsAndInstruments+as 90 Cash,Deposits,CurrentDeposits,Securities,InvestmentSecurities,InvestmentInAssociate,LongTermNationalBonds,ShortTermNationalBonds,Products,Machinery asset 82 Cash,Deposits,CurrentDeposits,Securities,InvestmentSecurities,InvestmentInAssociate,LongTermNationalBonds,ShortTermNationalBonds,Products,Machinery assets 10 AccumulatedDepreciation,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,ContractAssets,DeferredTaxAssets,LeasedAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,IncomeSummary assets. 1 AccumulatedDepreciation associate 2 InvestmentInAssociate,AffiliateStocks associates 1 AffiliateStocks-at 55 InvestmentInAssociate,LongTermNationalBonds,ShortTermNationalBonds,Building,ReserveForDepreciation,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,Depreciation,AmortizationExpense,BusinessTrip+at 55 InvestmentInAssociate,LongTermNationalBonds,ShortTermNationalBonds,ReserveForDepreciation,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,Depreciation,AmortizationExpense,BusinessTrip,CentralBankPaymentExpense attributable 2 NetIncomeAttributableToNCI,NetLossAttributableToNCI automatically 1 IncomeSummary available-for-sale 2 ValuationDifferenceOnOtherSecurities,AvailableForSaleSecurities available-for-sale securities 12 ValuationDifferenceOnOtherSecurities,AvailableForSaleSecurities,Securities,InvestmentSecurities,GainOnSalesOfSecurities,GainOnValuationOfSecurities,InterestOnSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnValuationOfSecurities availableforsalesecurities 1 AvailableForSaleSecurities-backward 1 CommunicationExpenses bad 2 BadDebtLoss,RecoveryOfBadDebts bad debt loss 19 BadDebtLoss,RecoveryOfBadDebts,NetLoss,CashOverShort,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,MiscellaneousLoss,InventoryShrinkageLoss,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables baddebtloss 1 BadDebtLoss@@ -959,8 +964,10 @@ branch 2 BranchCurrentAccount,HeadOfficeCurrentAccount branch current account 23 BranchCurrentAccount,HeadOfficeCurrentAccount,CurrentDeposits,AccountsReceivable,ReserveDepositPayable,MerchandiseInventory,PrepaidExpenses,AccruedRevenue,CashOverShort,AccountsPayable branchcurrentaccount 1 BranchCurrentAccount+brought 1 RetainedEarnings building 1 Building-business commencement expenses 26 BusinessCommencementExpenses,BusinessTrip,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses+buildings 1 Building+business commencement expenses 25 BusinessCommencementExpenses,BusinessTrip,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses businesscommencementexpenses 1 BusinessCommencementExpenses businesstrip 1 BusinessTrip by 1 ReversalOfAllowanceForDoubtfulAccounts@@ -972,10 +979,10 @@ capitalsurplus 3 LegalCapitalSurplus,OtherCapitalSurplus,CapitalSurplus card 1 CreditCardReceivable cash 3 Cash,PettyCash,CashOverShort-cash over and short 26 CashOverShort,Cash,ShortTermNationalBonds,Products,Machinery,ShortTermLoansReceivable,GovernmentService,ShortTermLoansPayable,ShortTermNationalBondsPayable,BusinessTrip+cash over and short 27 CashOverShort,Cash,ShortTermNationalBonds,Products,Machinery,ShortTermLoansReceivable,GovernmentService,ShortTermLoansPayable,ShortTermNationalBondsPayable,BusinessTrip cashovershort 1 CashOverShort central bank notes 12 CentralBankNotePayable,CentralBankPaymentExpense,CentralBankPaymentIncome,NotesReceivable,NotesLoansReceivable,NotesPayable,NotesLoansPayable,BankOverdraft,LossOnSalesOfNotesReceivable,DishonoredNotesReceivable-central bank payment to treasury 28 CentralBankPaymentExpense,CentralBankPaymentIncome,CentralBankNotePayable,Products,StockInvestment,CapitalStock,ReceiptFee,MerchandiseInventory,PaymentsOnBehalf,SuspensePayments+central bank payment received 18 CentralBankPaymentIncome,CentralBankPaymentExpense,CentralBankNotePayable,DepositPayable,ReceiptFee,PaymentsOnBehalf,SuspensePayments,BankOverdraft,AdvancesReceived,DepositsReceived centralbanknotepayable 1 CentralBankNotePayable centralbankpaymentexpense 1 CentralBankPaymentExpense centralbankpaymentincome 1 CentralBankPaymentIncome@@ -985,27 +992,24 @@ closed. 1 IncomeSummary closing 1 CashOverShort commencement 1 BusinessCommencementExpenses-communication 2 Commutation,CommunicationExpenses-communication expenses 25 Commutation,CommunicationExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses-communicationexpenses 2 Commutation,CommunicationExpenses-commutation 2 Commutation,CommunicationExpenses-compatibility. 1 CommunicationExpenses+communication expenses 24 CommunicationExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses,ResearchAndDevelopmentExpenses+communicationexpenses 1 CommunicationExpenses consolidation 2 NetIncomeAttributableToNCI,NetLossAttributableToNCI construction 3 ConstructionInProgress,ConstructionFundReserve,GainOnConstructionGrants-construction in progress 82 ConstructionInProgress,SoftwareInProgress,GainOnConstructionGrants,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment+construction in progress 81 ConstructionInProgress,SoftwareInProgress,GainOnConstructionGrants,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment constructionfundreserve 1 ConstructionFundReserve constructioninprogress 1 ConstructionInProgress consumption 5 ConsumptionExpenditure,ConsumptionTaxPaid,ConsumptionTaxReceived,AccruedConsumptionTax,ConsumptionTaxRefundReceivable consumption expenditure 7 ConsumptionExpenditure,WageExpenditure,SubsidyExpense,ConsumptionTaxPaid,ConsumptionTaxReceived,AccruedConsumptionTax,ConsumptionTaxRefundReceivable consumption tax paid 26 ConsumptionTaxPaid,AccruedConsumptionTax,PrepaidCorporateIncomeTaxes,ConsumptionTaxReceived,AccruedCorporateIncomeTaxes,ConsumptionTaxRefundReceivable,TaxesExpense,ConsumptionExpenditure,TaxesRevenue,AdvancesPaid-consumption tax received 27 ConsumptionTaxReceived,ConsumptionTaxPaid,AccruedConsumptionTax,ConsumptionTaxRefundReceivable,DepositPayable,TaxesExpense,ConsumptionExpenditure,TaxesRevenue,PrepaidCorporateIncomeTaxes,AdvancesReceived+consumption tax received 28 ConsumptionTaxReceived,ConsumptionTaxPaid,AccruedConsumptionTax,ConsumptionTaxRefundReceivable,DepositPayable,TaxesExpense,ConsumptionExpenditure,TaxesRevenue,CentralBankPaymentIncome,PrepaidCorporateIncomeTaxes consumption tax refund receivable 36 ConsumptionTaxRefundReceivable,IncomeTaxesRefundReceivable,ConsumptionTaxPaid,ConsumptionTaxReceived,AccruedConsumptionTax,RefundOfIncomeTaxes,LongTermLoansReceivable,AccountsReceivable,ShortTermLoansReceivable,ReserveDepositReceivable consumptionexpenditure 1 ConsumptionExpenditure consumptiontaxpaid 1 ConsumptionTaxPaid consumptiontaxreceived 1 ConsumptionTaxReceived consumptiontaxrefundreceivable 1 ConsumptionTaxRefundReceivable contra 4 AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ContractAssets,ContraAccountForGuaranteeObligations-contra account for guarantee obligations 49 ContraAccountForGuaranteeObligations,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,MerchandiseInventory,ProvisionForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,GuaranteeObligations,AccountsReceivable,ReserveForDepreciation,ReserveDepositPayable+contra account for guarantee obligations 50 ContraAccountForGuaranteeObligations,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,MerchandiseInventory,ProvisionForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,GuaranteeObligations,AccountsReceivable,RetainedEarnings,ReserveForDepreciation contraaccountforguaranteeobligations 1 ContraAccountForGuaranteeObligations contract assets 10 ContractAssets,AccumulatedDepreciation,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,DeferredTaxAssets,LeasedAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,IncomeSummary contractassets 1 ContractAssets@@ -1018,7 +1022,7 @@ cost of services 44 CostOfServices,SalesCost,MerchandiseInventory,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee,Software,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,PaymentFees costofservices 1 CostOfServices costs 3 PrepaidPensionCost,StockIssuanceCosts,StorageExpenses-counterpart 3 PaymentFees,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts+counterpart 2 PaymentFees,ReversalOfAllowanceForDoubtfulAccounts credit card receivable 22 CreditCardReceivable,AllowanceForDoubtfulAccounts,LongTermLoansReceivable,AccountsReceivable,ShortTermLoansReceivable,ReserveDepositReceivable,NotesReceivable,ElectronicallyRecordedReceivable,NotesLoansReceivable,OtherReceivables credit-balance 3 AllowanceForDoubtfulAccounts,AccumulatedDepreciation,HeadOfficeCurrentAccount creditcardreceivable 1 CreditCardReceivable@@ -1046,10 +1050,10 @@ depositpayable 2 DepositPayable,ReserveDepositPayable deposits 12 Deposits,CurrentDeposits,ReserveDepositReceivable,DepositPayable,ReserveDepositPayable,DepositsReceived,TimeDeposits,SecurityDepositsPaid,DepositsInSpecialAccounts,GuaranteeDepositsReceived deposits accepted 12 DepositPayable,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,DepositsReceived,TimeDeposits,SecurityDepositsPaid,DepositsInSpecialAccounts,GuaranteeDepositsReceived-deposits for subscriptions of shares 73 StockSubscriptionDeposits,MerchandiseInventory,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,SubsidiaryStocks,AffiliateStocks,DepositsReceivedFromOfficers,ReversalOfAllowanceForBonuses-deposits in special accounts 95 DepositsInSpecialAccounts,Deposits,ReserveDepositPayable,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,CurrentDeposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery-deposits received 18 DepositPayable,DepositsReceived,GuaranteeDepositsReceived,DepositsReceivedFromOfficers,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,AdvancesReceived,ConsumptionTaxReceived-deposits received from officers 20 DepositsReceivedFromOfficers,DepositPayable,DepositsReceived,GuaranteeDepositsReceived,LandRentReceived,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,AdvancesReceived+deposits for subscriptions of shares 74 StockSubscriptionDeposits,MerchandiseInventory,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,SubsidiaryStocks,AffiliateStocks,DepositsReceivedFromOfficers,ReversalOfAllowanceForBonuses,DirectorsCompensations+deposits in special accounts 94 DepositsInSpecialAccounts,Deposits,ReserveDepositPayable,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,CurrentDeposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery+deposits received 19 DepositPayable,DepositsReceived,GuaranteeDepositsReceived,DepositsReceivedFromOfficers,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,CentralBankPaymentIncome,AdvancesReceived+deposits received from officers 22 DepositsReceivedFromOfficers,DepositPayable,DepositsReceived,GuaranteeDepositsReceived,LandRentReceived,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,CentralBankPaymentIncome deposits, 2 ReserveDepositReceivable,ReserveDepositPayable depositsinspecialaccounts 1 DepositsInSpecialAccounts depositsreceived 4 DepositPayable,DepositsReceived,GuaranteeDepositsReceived,DepositsReceivedFromOfficers@@ -1058,10 +1062,12 @@ depreciation 4 ReserveForDepreciation,Depreciation,AmortizationExpense,AccumulatedDepreciation depreciation; 1 AccumulatedDepreciation development 2 ResearchAndDevelopmentExpenses,DevelopmentExpenses-development expenses 25 ResearchAndDevelopmentExpenses,DevelopmentExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses+development expenses 24 ResearchAndDevelopmentExpenses,DevelopmentExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses developmentexpenses 2 ResearchAndDevelopmentExpenses,DevelopmentExpenses device: 1 IncomeSummary difference 1 ValuationDifferenceOnOtherSecurities+directors 1 DirectorsCompensations+directorscompensations 1 DirectorsCompensations dishonored notes receivable 23 DishonoredNotesReceivable,NotesReceivable,NotesLoansReceivable,LossOnSalesOfNotesReceivable,NonOperatingNotesReceivable,LongTermLoansReceivable,AccountsReceivable,ShortTermLoansReceivable,ReserveDepositReceivable,CentralBankNotePayable dishonorednotesreceivable 1 DishonoredNotesReceivable dividend 3 UnpaidDividends,DividendEqualizationReserve,DividendsReceived@@ -1082,7 +1088,7 @@ electronically recorded obligations - non-operating 35 NonOperatingElectronicallyRecordedObligations,NonOperatingElectronicallyRecordedReceivable,ElectronicallyRecordedObligations,ElectronicallyRecordedReceivable,NonOperatingNotesReceivable,NonOperatingNotesPayable,LossOnSalesOfElectronicallyRecordedReceivables,LongTermNationalBonds,ShortTermNationalBonds,LongTermLoansReceivable electronicallyrecordedobligations 2 ElectronicallyRecordedObligations,NonOperatingElectronicallyRecordedObligations electronicallyrecordedreceivable 3 ElectronicallyRecordedReceivable,NonOperatingElectronicallyRecordedReceivable,LossOnSalesOfElectronicallyRecordedReceivables-entertainment expenses 25 EntertainmentExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses+entertainment expenses 24 EntertainmentExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses entertainmentexpenses 1 EntertainmentExpenses entry 1 LossOnReductionOfFixedAssets equalization 1 DividendEqualizationReserve@@ -1090,39 +1096,39 @@ equipment investment 8 EquipmentInvestment,InvestmentSecurities,InvestmentInAssociate,Machinery,StockInvestment,Fixtures,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities equipmentinvestment 1 EquipmentInvestment equity 17 InvestmentInAssociate,CapitalStock,RetainedEarnings,EquityInEarningsOfInvestee,LegalRetainedEarnings,CumulativeTranslationAdjustment,StockSubscriptionDeposits,LegalCapitalSurplus,OtherCapitalSurplus,DividendEqualizationReserve-equity in earnings of investee 116 EquityInEarningsOfInvestee,RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,InvestmentInAssociate,OrdinaryProfit,MerchandiseInventory,CommunicationExpenses,GainOnSalesOfFixedAssets,ReversalOfAllowanceForDoubtfulAccounts+equity in earnings of investee 116 EquityInEarningsOfInvestee,RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,InvestmentInAssociate,OrdinaryProfit,MerchandiseInventory,GainOnSalesOfFixedAssets,ReversalOfAllowanceForDoubtfulAccounts,SoftwareInProgress equityinearningsofinvestee 1 EquityInEarningsOfInvestee-estate 1 Building estimated 1 ReversalOfAllowanceForDoubtfulAccounts examples 1 ReserveDepositPayable excess 1 ReversalOfAllowanceForDoubtfulAccounts exchange 3 AllowanceForDoubtfulAccounts,ForeignExchangeGains,ForeignExchangeLosses existing 2 AccumulatedDepreciation,ReversalOfAllowanceForDoubtfulAccounts expenditure 3 WageExpenditure,ConsumptionExpenditure,SubsidyExpense-expense 74 Depreciation,AmortizationExpense,SalesCost,BusinessTrip,Commutation,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses,SuppliesExpenses-expenses 25 Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses+expense 74 Depreciation,AmortizationExpense,SalesCost,BusinessTrip,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses+expenses 24 DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses,ResearchAndDevelopmentExpenses fee 3 ReceiptFee,PaymentFees,MembershipFees fees 3 ReceiptFee,PaymentFees,MembershipFees fire 1 LossOnFire fixed 5 LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets fixtures 1 Fixtures-fixtures and equipment 18 Fixtures,Machinery,Products,EquipmentInvestment,BusinessTrip,MerchandiseInventory,Land,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand-for 29 ReserveForDepreciation,AmortizationExpense,MerchandiseInventory,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ProvisionForDoubtfulAccounts,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties+fixtures and equipment 19 Fixtures,Machinery,Products,EquipmentInvestment,BusinessTrip,MerchandiseInventory,Land,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand+for 30 RetainedEarnings,ReserveForDepreciation,AmortizationExpense,MerchandiseInventory,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ProvisionForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties foreign exchange gains 3 ForeignExchangeGains,ForeignExchangeLosses,AllowanceForDoubtfulAccounts foreign exchange losses 3 ForeignExchangeLosses,ForeignExchangeGains,AllowanceForDoubtfulAccounts foreignexchangegains 1 ForeignExchangeGains foreignexchangelosses 1 ForeignExchangeLosses+forward 1 RetainedEarnings from 4 AllowanceForDoubtfulAccounts,AccumulatedDepreciation,LandRentReceived,DepositsReceivedFromOfficers gain 11 MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,InsuranceGain,GainOnBargainPurchase,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,GainOnConstructionGrants-gain on bargain purchase 93 GainOnBargainPurchase,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,InsuranceGain,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,GainOnConstructionGrants-gain on contribution received for construction 102 GainOnConstructionGrants,MerchandiseInventory,ConstructionFundReserve,ReserveForDepreciation,AmortizationExpense,ConsumptionTaxReceived,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ProvisionForDoubtfulAccounts,CommunicationExpenses-gain on insurance claims 91 InsuranceGain,ElectronicallyRecordedReceivable,MerchandiseInventory,GainOnSalesOfFixedAssets,NonOperatingElectronicallyRecordedReceivable,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,GainOnBargainPurchase,GainOnDonationOfFixedAssets-gain on receipt of donated non-current assets 110 GainOnDonationOfFixedAssets,GainOnSalesOfFixedAssets,GainOnNationalSubsidies,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,MerchandiseInventory,LossOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities-gain on receipt of national subsidies 107 GainOnNationalSubsidies,GainOnDonationOfFixedAssets,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable-gain on sale of investment securities 115 GainOnSalesOfInvestmentSecurities,GainOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnValuationOfSecurities,LossOnSalesOfSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities-gain on sale of securities 112 GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnValuationOfSecurities,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities-gain on sales of fixed assets 112 GainOnSalesOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,MerchandiseInventory,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnValuationOfSecurities-gain on valuation of securities 109 GainOnValuationOfSecurities,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnValuationOfSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,ValuationDifferenceOnOtherSecurities,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,LossOnValuationOfMerchandise+gain on bargain purchase 90 GainOnBargainPurchase,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,InsuranceGain,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,GainOnConstructionGrants+gain on contribution received for construction 105 GainOnConstructionGrants,MerchandiseInventory,ConstructionFundReserve,ReserveForDepreciation,AmortizationExpense,ConsumptionTaxReceived,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ProvisionForDoubtfulAccounts,GainOnSalesOfFixedAssets+gain on insurance claims 88 InsuranceGain,ElectronicallyRecordedReceivable,MerchandiseInventory,GainOnSalesOfFixedAssets,NonOperatingElectronicallyRecordedReceivable,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,GainOnBargainPurchase,GainOnDonationOfFixedAssets+gain on receipt of donated non-current assets 109 GainOnDonationOfFixedAssets,GainOnSalesOfFixedAssets,GainOnNationalSubsidies,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,MerchandiseInventory,LossOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities+gain on receipt of national subsidies 106 GainOnNationalSubsidies,GainOnDonationOfFixedAssets,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable+gain on sale of investment securities 114 GainOnSalesOfInvestmentSecurities,GainOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnValuationOfSecurities,LossOnSalesOfSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities+gain on sale of securities 111 GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnValuationOfSecurities,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities+gain on sales of fixed assets 111 GainOnSalesOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,MerchandiseInventory,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnValuationOfSecurities+gain on valuation of securities 108 GainOnValuationOfSecurities,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnValuationOfSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,ValuationDifferenceOnOtherSecurities,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,LossOnValuationOfMerchandise gainonbargainpurchase 1 GainOnBargainPurchase gainonconstructiongrants 1 GainOnConstructionGrants gainondonationoffixedassets 1 GainOnDonationOfFixedAssets@@ -1134,11 +1140,11 @@ gains 1 ForeignExchangeGains general reserve 9 GeneralReserve,ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,AccumulatedDepreciation,LegalRetainedEarnings,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve generalreserve 1 GeneralReserve-gift certificates received 10 GiftCertificatesReceived,DepositPayable,AdvancesReceived,DepositsReceived,ConsumptionTaxReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants,LandRentReceived,DepositsReceivedFromOfficers+gift certificates received 11 GiftCertificatesReceived,DepositPayable,CentralBankPaymentIncome,AdvancesReceived,DepositsReceived,ConsumptionTaxReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants,LandRentReceived giftcertificatesreceived 1 GiftCertificatesReceived gold 1 Gold goods 3 MerchandiseInventory,LossOnValuationOfMerchandise,GoodsInTransit-goods in transit 82 GoodsInTransit,MerchandiseInventory,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment+goods in transit 81 GoodsInTransit,MerchandiseInventory,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment goodsintransit 1 GoodsInTransit goodwill 2 Goodwill,AmortizationOfGoodwill government service 3 GovernmentService,ServiceRevenue,CostOfServices@@ -1147,15 +1153,16 @@ grossprofit 1 GrossProfit guarantee 4 SecurityDepositsPaid,GuaranteeDepositsReceived,ContraAccountForGuaranteeObligations,GuaranteeObligations guarantee deposits 14 SecurityDepositsPaid,GuaranteeDepositsReceived,Deposits,CurrentDeposits,ReserveDepositReceivable,DepositPayable,ReserveDepositPayable,DepositsReceived,TimeDeposits,DepositsInSpecialAccounts-guarantee deposits received 20 GuaranteeDepositsReceived,DepositPayable,DepositsReceived,SecurityDepositsPaid,DepositsReceivedFromOfficers,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,AdvancesReceived+guarantee deposits received 21 GuaranteeDepositsReceived,DepositPayable,DepositsReceived,SecurityDepositsPaid,DepositsReceivedFromOfficers,Deposits,CurrentDeposits,ReserveDepositReceivable,ReserveDepositPayable,CentralBankPaymentIncome guarantee obligations 7 ContraAccountForGuaranteeObligations,GuaranteeObligations,ElectronicallyRecordedObligations,SecurityDepositsPaid,NonOperatingElectronicallyRecordedObligations,LeaseObligations,GuaranteeDepositsReceived guaranteedepositsreceived 1 GuaranteeDepositsReceived guaranteeobligations 2 ContraAccountForGuaranteeObligations,GuaranteeObligations-head office current account 24 HeadOfficeCurrentAccount,BranchCurrentAccount,CurrentDeposits,AccountsReceivable,ReserveDepositPayable,MerchandiseInventory,PrepaidExpenses,AccruedRevenue,CashOverShort,AccountsPayable+hand 5 Products,MerchandiseInventory,SuppliesOnHand,LossOnValuationOfMerchandise,ResearchAndDevelopmentExpenses+head office current account 25 HeadOfficeCurrentAccount,BranchCurrentAccount,CurrentDeposits,AccountsReceivable,ReserveDepositPayable,MerchandiseInventory,PrepaidExpenses,AccruedRevenue,CashOverShort,AccountsPayable headofficecurrentaccount 1 HeadOfficeCurrentAccount held-to-maturity bonds 5 HeldToMaturityBonds,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable heldtomaturitybonds 1 HeldToMaturityBonds-in 81 Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment,RetainedEarnings,AmortizationExpense+in 80 Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment,RetainedEarnings,AmortizationExpense income 18 NetIncome,SubsidyIncome,RentalIncome,WageEarned,CentralBankPaymentIncome,PrepaidCorporateIncomeTaxes,CashOverShort,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,MiscellaneousIncome income summary 18 IncomeSummary,NetIncome,SubsidyIncome,RentalIncome,WageEarned,CentralBankPaymentIncome,PrepaidCorporateIncomeTaxes,CashOverShort,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes income taxes - deferred 48 IncomeTaxesAdjustment,PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,IncomeTaxesRefundReceivable,AdditionalIncomeTaxesForPriorPeriods,RefundOfIncomeTaxes,IncomeSummary,NetIncomeAttributableToNCI,LongTermNationalBonds@@ -1168,15 +1175,15 @@ instead. 1 MerchandiseInventory instruments 1 ToolsAndInstruments insurance 2 InsuranceGain,InsuranceExpense-insurance expenses 26 InsuranceExpense,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,InsuranceGain+insurance expenses 25 InsuranceExpense,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,InsuranceGain,OperatingExpenses insuranceexpense 1 InsuranceExpense insurancegain 1 InsuranceGain intact. 1 AllowanceForDoubtfulAccounts intangibles 1 AmortizationExpense interest 9 InterestExpense,NationalBondInterestEarned,DepositInterestEarned,InterestEarned,LeaseholdRights,NonControllingInterests,InterestOnSecurities,NetIncomeAttributableToNCI,NetLossAttributableToNCI interest earned 12 NationalBondInterestEarned,DepositInterestEarned,InterestEarned,InterestExpense,WageEarned,UnearnedRevenue,LeaseholdRights,NonControllingInterests,EarnedSurplus,InterestOnSecurities-interest expense 81 InterestExpense,NetIncomeAttributableToNCI,Depreciation,AmortizationExpense,SalesCost,BusinessTrip,Commutation,UtilitiesExpense,RentExpense,AdvertisingExpense-interest on securities 97 InterestOnSecurities,NationalBondInterestEarned,ValuationDifferenceOnOtherSecurities,NonControllingInterests,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities+interest expense 81 InterestExpense,NetIncomeAttributableToNCI,Depreciation,AmortizationExpense,SalesCost,BusinessTrip,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses+interest on securities 94 InterestOnSecurities,NationalBondInterestEarned,ValuationDifferenceOnOtherSecurities,NonControllingInterests,GainOnSalesOfSecurities,GainOnValuationOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities interestearned 3 NationalBondInterestEarned,DepositInterestEarned,InterestEarned interestexpense 1 InterestExpense interestonsecurities 1 InterestOnSecurities@@ -1187,46 +1194,46 @@ inventoryshrinkageloss 1 InventoryShrinkageLoss investee 1 EquityInEarningsOfInvestee investment 6 InvestmentSecurities,InvestmentInAssociate,StockInvestment,EquipmentInvestment,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities-investment in associate 82 InvestmentInAssociate,InvestmentSecurities,StockInvestment,EquipmentInvestment,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities,Deposits,Products,Machinery,Building+investment in associate 81 InvestmentInAssociate,InvestmentSecurities,StockInvestment,EquipmentInvestment,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities,Deposits,Products,Machinery,Building investment securities 15 InvestmentSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities,Securities,InvestmentInAssociate,StockInvestment,EquipmentInvestment,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnValuationOfSecurities investmentinassociate 1 InvestmentInAssociate investmentsecurities 3 InvestmentSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfInvestmentSecurities-is 26 Products,AdvertisingExpense,MiscellaneousExpenses,MerchandiseInventory,CashOverShort,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ProvisionForDoubtfulAccounts,MiscellaneousLoss,CommunicationExpenses+is 19 Products,AdvertisingExpense,MiscellaneousExpenses,MerchandiseInventory,CashOverShort,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ProvisionForDoubtfulAccounts,MiscellaneousLoss,MiscellaneousIncome issuance 1 StockIssuanceCosts-it 97 Deposits,CurrentDeposits,Securities,InvestmentSecurities,InvestmentInAssociate,ReserveDepositReceivable,CapitalStock,RetainedEarnings,LongTermLoansPayable,ShortTermLoansPayable+it 96 Deposits,CurrentDeposits,Securities,InvestmentSecurities,InvestmentInAssociate,ReserveDepositReceivable,CapitalStock,RetainedEarnings,LongTermLoansPayable,ShortTermLoansPayable job. 1 AllowanceForDoubtfulAccounts land 4 Land,LeaseholdRights,LandRentReceived,LandRentPaid landrentpaid 1 LandRentPaid landrentreceived 1 LandRentReceived-lease expenses 29 LeaseExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts,LeasedAssets+lease expenses 28 LeaseExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts,LeasedAssets,LongTermPrepaidExpenses lease liabilities 7 LeaseObligations,ReversalOfAllowanceForDoubtfulAccounts,LeasedAssets,LeaseholdRights,RefundLiabilities,DeferredTaxLiabilities,LeaseExpenses leased assets 11 LeasedAssets,AccumulatedDepreciation,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,ReversalOfAllowanceForDoubtfulAccounts,ContractAssets,DeferredTaxAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets leasedassets 1 LeasedAssets leaseexpenses 1 LeaseExpenses-leasehold interests in land 83 LeaseholdRights,NonControllingInterests,LandRentReceived,NetIncomeAttributableToNCI,NetLossAttributableToNCI,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery+leasehold interests in land 82 LeaseholdRights,NonControllingInterests,LandRentReceived,NetIncomeAttributableToNCI,NetLossAttributableToNCI,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery leaseholdrights 1 LeaseholdRights leaseobligations 1 LeaseObligations-legacy 2 AccumulatedDepreciation,CommunicationExpenses-legal (appropriated) retained earnings reserve 15 LegalRetainedEarnings,RetainedEarnings,AccumulatedDepreciation,EarnedSurplus,ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,EquityInEarningsOfInvestee,CommunicationExpenses,LegalCapitalSurplus+legacy 1 AccumulatedDepreciation+legal (appropriated) retained earnings reserve 14 LegalRetainedEarnings,RetainedEarnings,AccumulatedDepreciation,EarnedSurplus,ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,EquityInEarningsOfInvestee,LegalCapitalSurplus,DividendEqualizationReserve legal capital surplus 7 LegalCapitalSurplus,OtherCapitalSurplus,CapitalSurplus,CapitalStock,LegalRetainedEarnings,EarnedSurplus,StatutoryWelfareExpenses-legal welfare expenses 27 StatutoryWelfareExpenses,WelfareExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,LegalRetainedEarnings,CommunicationExpenses+legal welfare expenses 26 StatutoryWelfareExpenses,WelfareExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,LegalRetainedEarnings,CommunicationExpenses,LongTermPrepaidExpenses legalcapitalsurplus 1 LegalCapitalSurplus legalretainedearnings 1 LegalRetainedEarnings liabilities 3 RefundLiabilities,DeferredTaxLiabilities,LeaseObligations liability 41 LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,ReserveForDepreciation,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,CentralBankNotePayable,AccountsPayable loans 8 LongTermLoansReceivable,ShortTermLoansReceivable,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,NotesLoansReceivable,NotesLoansPayable,LoansReceivable loans payable 20 LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,NotesLoansPayable,LongTermLoansReceivable,ShortTermLoansReceivable,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,ReserveDepositPayable-loans payable on notes 101 NotesLoansPayable,LongTermLoansPayable,NotesLoansReceivable,NonOperatingNotesPayable,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,CentralBankNotePayable+loans payable on notes 98 NotesLoansPayable,LongTermLoansPayable,NotesLoansReceivable,NonOperatingNotesPayable,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,CentralBankNotePayable loans receivable 23 LongTermLoansReceivable,ShortTermLoansReceivable,NotesLoansReceivable,LoansReceivable,AccountsReceivable,ReserveDepositReceivable,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,NotesReceivable-loans receivable on notes 101 NotesLoansReceivable,LongTermLoansReceivable,NotesLoansPayable,LossOnSalesOfNotesReceivable,DishonoredNotesReceivable,NonOperatingNotesReceivable,ShortTermLoansReceivable,LongTermLoansPayable,NotesReceivable,ElectronicallyRecordedReceivable+loans receivable on notes 98 NotesLoansReceivable,LongTermLoansReceivable,NotesLoansPayable,LossOnSalesOfNotesReceivable,DishonoredNotesReceivable,NonOperatingNotesReceivable,ShortTermLoansReceivable,LongTermLoansPayable,NotesReceivable,ElectronicallyRecordedReceivable loanspayable 4 LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,NotesLoansPayable loansreceivable 4 LongTermLoansReceivable,ShortTermLoansReceivable,NotesLoansReceivable,LoansReceivable-long-term accounts payable - other 45 LongTermOtherPayables,LongTermLoansPayable,LongTermNationalBondsPayable,LongTermNationalBonds,LongTermLoansReceivable,ShortTermLoansPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,AccountsPayable,OtherPayables+long-term accounts payable - other 46 LongTermOtherPayables,LongTermLoansPayable,LongTermNationalBondsPayable,LongTermNationalBonds,LongTermLoansReceivable,ShortTermLoansPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,AccountsPayable,OtherPayables long-term loans payable 22 LongTermLoansPayable,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,LongTermNationalBondsPayable,NotesLoansPayable,LongTermOtherPayables,LongTermNationalBonds,ShortTermLoansReceivable,DepositPayable long-term loans receivable 27 LongTermLoansReceivable,ShortTermLoansReceivable,LongTermLoansPayable,NotesLoansReceivable,LoansReceivable,LongTermNationalBonds,AccountsReceivable,ReserveDepositReceivable,ShortTermLoansPayable,LoansPayable-long-term national bonds 11 LongTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBonds,ShortTermNationalBondsPayable,LongTermLoansReceivable,LongTermLoansPayable,NationalBondInterestEarned,LongTermPrepaidExpenses,LongTermOtherPayables,GainOnNationalSubsidies-long-term national bonds payable 23 LongTermNationalBondsPayable,LongTermNationalBonds,ShortTermNationalBondsPayable,ShortTermNationalBonds,LongTermLoansPayable,LongTermOtherPayables,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,DepositPayable-long-term prepaid expenses 32 LongTermPrepaidExpenses,PrepaidExpenses,LongTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,LongTermNationalBondsPayable,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses+long-term national bonds 12 LongTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBonds,ShortTermNationalBondsPayable,LongTermLoansReceivable,LongTermLoansPayable,CentralBankPaymentExpense,NationalBondInterestEarned,LongTermPrepaidExpenses,LongTermOtherPayables+long-term national bonds payable 24 LongTermNationalBondsPayable,LongTermNationalBonds,ShortTermNationalBondsPayable,ShortTermNationalBonds,LongTermLoansPayable,LongTermOtherPayables,LongTermLoansReceivable,ShortTermLoansPayable,LoansPayable,DepositPayable+long-term prepaid expenses 31 LongTermPrepaidExpenses,PrepaidExpenses,LongTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,LongTermNationalBondsPayable,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidCorporateIncomeTaxes longtermloanspayable 1 LongTermLoansPayable longtermloansreceivable 1 LongTermLoansReceivable longtermnationalbonds 2 LongTermNationalBonds,LongTermNationalBondsPayable@@ -1235,16 +1242,16 @@ longtermprepaidexpenses 1 LongTermPrepaidExpenses loss 18 NetLoss,CashOverShort,BadDebtLoss,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,MiscellaneousLoss,InventoryShrinkageLoss,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables loss attributable to non-controlling interests 38 NetLossAttributableToNCI,NetIncomeAttributableToNCI,CashOverShort,NonControllingInterests,InventoryShrinkageLoss,LossOnRetirementOfFixedAssets,Products,StockInvestment,CapitalStock,CentralBankPaymentExpense-loss on fire 95 LossOnFire,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnRetirementOfFixedAssets-loss on retirement of non-current assets 116 LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfFixedAssets,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities-loss on sale of electronically recorded monetary claims 114 LossOnSalesOfElectronicallyRecordedReceivables,ElectronicallyRecordedReceivable,NonOperatingElectronicallyRecordedReceivable,ElectronicallyRecordedObligations,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory-loss on sale of investment securities 120 LossOnSalesOfInvestmentSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnValuationOfSecurities,MerchandiseInventory-loss on sale of receivables 115 LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities-loss on sale of securities 117 LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnValuationOfSecurities,MerchandiseInventory-loss on sales of fixed assets 117 LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnDonationOfFixedAssets,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities-loss on sales of notes receivable 124 LossOnSalesOfNotesReceivable,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfFixedAssets,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,NotesLoansReceivable,MerchandiseInventory,GainOnSalesOfFixedAssets,DishonoredNotesReceivable-loss on tax purpose reduction entry of non-current assets 122 LossOnReductionOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfFixedAssets,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities-loss on valuation of securities 114 LossOnValuationOfSecurities,GainOnValuationOfSecurities,LossOnValuationOfMerchandise,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities+loss on fire 92 LossOnFire,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnRetirementOfFixedAssets+loss on retirement of non-current assets 115 LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfFixedAssets,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities+loss on sale of electronically recorded monetary claims 113 LossOnSalesOfElectronicallyRecordedReceivables,ElectronicallyRecordedReceivable,NonOperatingElectronicallyRecordedReceivable,ElectronicallyRecordedObligations,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory+loss on sale of investment securities 119 LossOnSalesOfInvestmentSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnValuationOfSecurities,MerchandiseInventory+loss on sale of receivables 114 LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,MerchandiseInventory,GainOnSalesOfFixedAssets,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities+loss on sale of securities 116 LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnValuationOfSecurities,MerchandiseInventory+loss on sales of fixed assets 116 LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnDonationOfFixedAssets,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities+loss on sales of notes receivable 123 LossOnSalesOfNotesReceivable,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfFixedAssets,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,NotesLoansReceivable,MerchandiseInventory,GainOnSalesOfFixedAssets,DishonoredNotesReceivable+loss on tax purpose reduction entry of non-current assets 121 LossOnReductionOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnSalesOfNotesReceivable,GainOnSalesOfFixedAssets,LossOnValuationOfMerchandise,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,LossOnSalesOfSecurities+loss on valuation of securities 113 LossOnValuationOfSecurities,GainOnValuationOfSecurities,LossOnValuationOfMerchandise,LossOnSalesOfSecurities,LossOnSalesOfInvestmentSecurities,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnSalesOfInvestmentSecurities losses 1 ForeignExchangeLosses lossonfire 1 LossOnFire lossonreductionoffixedassets 1 LossOnReductionOfFixedAssets@@ -1258,12 +1265,12 @@ lossonvaluationofmerchandise 1 LossOnValuationOfMerchandise lossonvaluationofsecurities 1 LossOnValuationOfSecurities machinery 1 Machinery-machinery and equipment 18 Machinery,Fixtures,Products,EquipmentInvestment,BusinessTrip,MerchandiseInventory,Land,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand+machinery and equipment 19 Machinery,Fixtures,Products,EquipmentInvestment,BusinessTrip,MerchandiseInventory,Land,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand made 1 PaymentsOnBehalf-maintenance expenses 25 MaintenanceExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses+maintenance expenses 24 MaintenanceExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses maintenanceexpenses 1 MaintenanceExpenses materials 1 RawMaterials-meeting expenses 25 MeetingExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses+meeting expenses 24 MeetingExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses meetingexpenses 1 MeetingExpenses membership fees 3 MembershipFees,ReceiptFee,PaymentFees membershipfees 1 MembershipFees@@ -1280,9 +1287,8 @@ module's 1 AllowanceForDoubtfulAccounts monetary 4 ElectronicallyRecordedReceivable,ElectronicallyRecordedObligations,NonOperatingElectronicallyRecordedReceivable,LossOnSalesOfElectronicallyRecordedReceivables name. 1 AccumulatedDepreciation-named 1 CommunicationExpenses-national 6 LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,NationalBondInterestEarned,GainOnNationalSubsidies-national bond interest earned 18 NationalBondInterestEarned,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,DepositInterestEarned,InterestEarned,InterestExpense,WageEarned,UnearnedRevenue+national 7 LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,CentralBankPaymentExpense,NationalBondInterestEarned,GainOnNationalSubsidies+national bond interest earned 19 NationalBondInterestEarned,LongTermNationalBonds,ShortTermNationalBonds,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,DepositInterestEarned,InterestEarned,InterestExpense,CentralBankPaymentExpense,WageEarned nationalbondinterestearned 1 NationalBondInterestEarned net income 27 NetIncome,NetIncomeAttributableToNCI,SubsidyIncome,RentalIncome,WageEarned,CentralBankPaymentIncome,NetLoss,ElectronicallyRecordedReceivable,PrepaidCorporateIncomeTaxes,CashOverShort net loss 26 NetLoss,LossOnSalesOfElectronicallyRecordedReceivables,NetLossAttributableToNCI,NetIncome,ElectronicallyRecordedReceivable,CashOverShort,ElectronicallyRecordedObligations,AllowanceForDoubtfulAccounts,BadDebtLoss,LossOnSalesOfFixedAssets@@ -1294,7 +1300,7 @@ netlossattributabletonci 1 NetLossAttributableToNCI new 2 ConstructionFundReserve,NewspaperBooksExpenses newspaperbooksexpenses 1 NewspaperBooksExpenses-newspapers and books 18 NewspaperBooksExpenses,Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand+newspapers and books 19 NewspaperBooksExpenses,Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand non-controlling 3 NonControllingInterests,NetIncomeAttributableToNCI,NetLossAttributableToNCI non-controlling interests 4 NonControllingInterests,NetIncomeAttributableToNCI,NetLossAttributableToNCI,LeaseholdRights non-current 3 GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets@@ -1316,22 +1322,22 @@ notespayable 2 NotesPayable,NonOperatingNotesPayable notesreceivable 4 NotesReceivable,LossOnSalesOfNotesReceivable,DishonoredNotesReceivable,NonOperatingNotesReceivable obligations 5 ElectronicallyRecordedObligations,NonOperatingElectronicallyRecordedObligations,LeaseObligations,ContraAccountForGuaranteeObligations,GuaranteeObligations-of 41 SalesCost,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee,MerchandiseInventory,Software,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,PaymentFees,CommunicationExpenses-off 8 LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,RecoveryOfBadDebts,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,HeadOfficeCurrentAccount,DepositsReceivedFromOfficers-office 2 HeadOfficeCurrentAccount,DepositsReceivedFromOfficers-officers 1 DepositsReceivedFromOfficers-on 89 LongTermNationalBonds,ShortTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,ReserveForDepreciation,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,Depreciation,AmortizationExpense,BusinessTrip-operating expenses 30 OperatingExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,NonOperatingNotesReceivable+of 41 SalesCost,GrossProfit,OrdinaryProfit,EquityInEarningsOfInvestee,MerchandiseInventory,Software,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,PaymentFees,GainOnSalesOfFixedAssets+off 9 LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,RecoveryOfBadDebts,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,HeadOfficeCurrentAccount,DepositsReceivedFromOfficers,DirectorsCompensations+office 3 HeadOfficeCurrentAccount,DepositsReceivedFromOfficers,DirectorsCompensations+officers 2 DepositsReceivedFromOfficers,DirectorsCompensations+on 86 LongTermNationalBonds,ShortTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,ReserveForDepreciation,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,Depreciation,AmortizationExpense,BusinessTrip+operating expenses 29 OperatingExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,NonOperatingNotesReceivable,NonOperatingElectronicallyRecordedReceivable operating revenue 46 OperatingRevenue,ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome operatingexpenses 1 OperatingExpenses operatingrevenue 1 OperatingRevenue ordinary profit 3 OrdinaryProfit,GrossProfit,NetIncomeAttributableToNCI ordinaryprofit 1 OrdinaryProfit-organization expenses 25 IncorporationExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses-other 5 OtherReceivables,OtherPayables,LongTermOtherPayables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities-other capital surplus 9 OtherCapitalSurplus,LegalCapitalSurplus,CapitalSurplus,CapitalStock,OtherReceivables,OtherPayables,LongTermOtherPayables,ValuationDifferenceOnOtherSecurities,EarnedSurplus-other payables 5 OtherPayables,LongTermOtherPayables,OtherReceivables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities-other receivables 8 OtherReceivables,OtherPayables,AllowanceForDoubtfulAccounts,LongTermOtherPayables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables+organization expenses 24 IncorporationExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses,RetirementBenefitExpenses+other 6 OtherReceivables,OtherPayables,LongTermOtherPayables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities,DirectorsCompensations+other capital surplus 10 OtherCapitalSurplus,LegalCapitalSurplus,CapitalSurplus,CapitalStock,OtherReceivables,OtherPayables,LongTermOtherPayables,ValuationDifferenceOnOtherSecurities,EarnedSurplus,DirectorsCompensations+other payables 6 OtherPayables,LongTermOtherPayables,OtherReceivables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities,DirectorsCompensations+other receivables 9 OtherReceivables,OtherPayables,AllowanceForDoubtfulAccounts,LongTermOtherPayables,OtherCapitalSurplus,ValuationDifferenceOnOtherSecurities,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables,DirectorsCompensations othercapitalsurplus 1 OtherCapitalSurplus otherpayables 2 OtherPayables,LongTermOtherPayables otherreceivables 1 OtherReceivables@@ -1343,9 +1349,10 @@ payables 2 OtherPayables,LongTermOtherPayables payment 6 CentralBankPaymentExpense,ReceiptFee,CentralBankPaymentIncome,PaymentsOnBehalf,SuspensePayments,PaymentFees payment fees / fees paid 38 PaymentFees,ReceiptFee,CentralBankPaymentExpense,CentralBankPaymentIncome,MembershipFees,Products,ReserveDepositReceivable,GovernmentService,ReserveForDepreciation,DepositPayable+payment to national treasury 33 CentralBankPaymentExpense,LongTermNationalBonds,ShortTermNationalBonds,Products,StockInvestment,CapitalStock,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,NationalBondInterestEarned,ReceiptFee paymentfees 2 ReceiptFee,PaymentFees payments 2 PaymentsOnBehalf,SuspensePayments-payments made on behalf 90 PaymentsOnBehalf,LongTermNationalBonds,ShortTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,ReserveForDepreciation,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,Depreciation,AmortizationExpense+payments made on behalf 87 PaymentsOnBehalf,LongTermNationalBonds,ShortTermNationalBonds,LongTermLoansReceivable,LongTermLoansPayable,ReserveForDepreciation,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,Depreciation,AmortizationExpense paymentsonbehalf 1 PaymentsOnBehalf pension 1 PrepaidPensionCost periodic/3-account 1 MerchandiseInventory@@ -1355,7 +1362,7 @@ placeholder; 1 IncomeSummary prepaid 4 PrepaidExpenses,PrepaidCorporateIncomeTaxes,LongTermPrepaidExpenses,PrepaidPensionCost prepaid corporate income taxes 23 PrepaidCorporateIncomeTaxes,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes,IncomeTaxesRefundReceivable,AdditionalIncomeTaxesForPriorPeriods,RefundOfIncomeTaxes,IncomeTaxesAdjustment,TaxesExpense,NetIncome,SubsidyIncome-prepaid expenses 27 PrepaidExpenses,LongTermPrepaidExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidCorporateIncomeTaxes,AccruedExpenses,CommunicationExpenses,PrepaidPensionCost+prepaid expenses 26 PrepaidExpenses,LongTermPrepaidExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidCorporateIncomeTaxes,AccruedExpenses,CommunicationExpenses,PrepaidPensionCost,OperatingExpenses prepaid pension costs 6 PrepaidPensionCost,PrepaidExpenses,PrepaidCorporateIncomeTaxes,LongTermPrepaidExpenses,StockIssuanceCosts,StorageExpenses prepaidcorporateincometaxes 1 PrepaidCorporateIncomeTaxes prepaidexpenses 2 PrepaidExpenses,LongTermPrepaidExpenses@@ -1366,16 +1373,15 @@ process 1 WorkInProcess products 2 Products,MerchandiseInventory profit 3 GrossProfit,OrdinaryProfit,NetIncomeAttributableToNCI-profit attributable to non-controlling interests 26 NetIncomeAttributableToNCI,NetLossAttributableToNCI,NonControllingInterests,Products,StockInvestment,CapitalStock,CentralBankPaymentExpense,GrossProfit,OrdinaryProfit,CentralBankPaymentIncome+profit attributable to non-controlling interests 26 NetIncomeAttributableToNCI,NetLossAttributableToNCI,NonControllingInterests,Products,StockInvestment,CapitalStock,CentralBankPaymentExpense,GrossProfit,OrdinaryProfit,MerchandiseInventory progress 2 ConstructionInProgress,SoftwareInProgress property tax payable 32 PropertyTaxPayable,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable,ReserveDepositPayable,CentralBankNotePayable,TaxesExpense propertytaxpayable 1 PropertyTaxPayable-provision 11 ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties-provision for bonuses 31 AllowanceForBonuses,ProvisionForBonuses,ReversalOfAllowanceForBonuses,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs-provision for doubtful accounts 34 ProvisionForDoubtfulAccounts,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs-provision for repairs 30 AllowanceForRepairs,ReversalOfAllowanceForRepairs,ProvisionForRepairs,ProvisionForDoubtfulAccounts,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits,RepairFundReserve,ReversalOfAllowanceForProductWarranties,ProvisionForBonuses-provision for retirement benefits 33 AllowanceForRetirementBenefits,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties-provision for warranties 29 AllowanceForProductWarranties,ReversalOfAllowanceForProductWarranties,ProvisionForProductWarranties,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForBonuses,AllowanceForRetirementBenefits,ReversalOfAllowanceForRepairs,ProvisionForRepairs,ProvisionForBonuses+provision for bonuses 32 ProvisionForBonuses,ProvisionForDoubtfulAccounts,AllowanceForBonuses,AllowanceForRetirementBenefits,ProvisionForRepairs,ProvisionForProductWarranties,ReversalOfAllowanceForBonuses,RetainedEarnings,ReserveForDepreciation,AmortizationExpense+provision for doubtful accounts 35 ProvisionForDoubtfulAccounts,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRetirementBenefits,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,AccountsReceivable,RetainedEarnings,ReserveForDepreciation+provision for repairs 31 ProvisionForRepairs,ProvisionForDoubtfulAccounts,AllowanceForRepairs,AllowanceForRetirementBenefits,RepairFundReserve,ReversalOfAllowanceForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,RetainedEarnings,ReserveForDepreciation+provision for retirement benefits 34 AllowanceForRetirementBenefits,ProvisionForDoubtfulAccounts,ProvisionForRepairs,ProvisionForBonuses,ProvisionForProductWarranties,RetainedEarnings,ReserveForDepreciation,AmortizationExpense,MerchandiseInventory,AllowanceForDoubtfulAccounts+provision for warranties 30 ProvisionForProductWarranties,ProvisionForDoubtfulAccounts,AllowanceForProductWarranties,AllowanceForRetirementBenefits,ReversalOfAllowanceForProductWarranties,ProvisionForRepairs,ProvisionForBonuses,RetainedEarnings,ReserveForDepreciation,AmortizationExpense provisionforbonuses 1 ProvisionForBonuses provisionfordoubtfulaccounts 1 ProvisionForDoubtfulAccounts provisionforproductwarranties 1 ProvisionForProductWarranties@@ -1389,7 +1395,6 @@ purpose 1 LossOnReductionOfFixedAssets raw materials 1 RawMaterials rawmaterials 1 RawMaterials-real estate 1 Building rebates 2 SalesRebates,PurchaseRebates receipt 5 ReceiptFee,SuspenseReceipts,PaymentFees,GainOnDonationOfFixedAssets,GainOnNationalSubsidies receipt fee 6 ReceiptFee,PaymentFees,SuspenseReceipts,GainOnDonationOfFixedAssets,GainOnNationalSubsidies,MembershipFees@@ -1398,11 +1403,11 @@ receivable 19 LongTermLoansReceivable,AccountsReceivable,ShortTermLoansReceivable,ReserveDepositReceivable,NotesReceivable,ElectronicallyRecordedReceivable,CreditCardReceivable,NotesLoansReceivable,OtherReceivables,AllowanceForDoubtfulAccounts receivables 4 OtherReceivables,AllowanceForDoubtfulAccounts,LossOnSalesOfElectronicallyRecordedReceivables,LossOnSalesOfReceivables receivables. 1 AllowanceForDoubtfulAccounts-received 10 DepositPayable,AdvancesReceived,DepositsReceived,ConsumptionTaxReceived,GiftCertificatesReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants,LandRentReceived,DepositsReceivedFromOfficers+received 11 DepositPayable,CentralBankPaymentIncome,AdvancesReceived,DepositsReceived,ConsumptionTaxReceived,GiftCertificatesReceived,GuaranteeDepositsReceived,DividendsReceived,GainOnConstructionGrants,LandRentReceived reciprocal 1 HeadOfficeCurrentAccount recorded 5 ElectronicallyRecordedReceivable,ElectronicallyRecordedObligations,NonOperatingElectronicallyRecordedReceivable,NonOperatingElectronicallyRecordedObligations,LossOnSalesOfElectronicallyRecordedReceivables records 1 MerchandiseInventory-recovery of bad debts written off 42 RecoveryOfBadDebts,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,HeadOfficeCurrentAccount,DepositsReceivedFromOfficers,SalesCost,GrossProfit+recovery of bad debts written off 42 RecoveryOfBadDebts,LossOnSalesOfFixedAssets,GainOnSalesOfFixedAssets,GainOnDonationOfFixedAssets,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,HeadOfficeCurrentAccount,DepositsReceivedFromOfficers,DirectorsCompensations,SalesCost recoveryofbaddebts 1 RecoveryOfBadDebts reduction 1 LossOnReductionOfFixedAssets refund 4 IncomeTaxesRefundReceivable,RefundLiabilities,RefundOfIncomeTaxes,ConsumptionTaxRefundReceivable@@ -1412,41 +1417,43 @@ refundofincometaxes 1 RefundOfIncomeTaxes related 1 AccumulatedDepreciation released). 1 ReversalOfAllowanceForDoubtfulAccounts+remuneration for directors (and other officers) 34 DirectorsCompensations,ValuationDifferenceOnOtherSecurities,RetainedEarnings,ReserveForDepreciation,AmortizationExpense,MerchandiseInventory,OtherReceivables,OtherPayables,AllowanceForDoubtfulAccounts,AccumulatedDepreciation rent 10 CurrentDeposits,RentExpense,RentalIncome,GainOnDonationOfFixedAssets,LandRentReceived,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,LandRentPaid,BranchCurrentAccount,HeadOfficeCurrentAccount-rent expenses on land 117 LandRentPaid,Commutation,CommunicationExpenses,LongTermPrepaidExpenses,GainOnDonationOfFixedAssets,LandRentReceived,IncorporationExpenses,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,CurrentDeposits+rent expenses on land 114 LandRentPaid,CommunicationExpenses,LongTermPrepaidExpenses,GainOnDonationOfFixedAssets,LandRentReceived,IncorporationExpenses,LossOnRetirementOfFixedAssets,LossOnReductionOfFixedAssets,CurrentDeposits,LongTermNationalBonds rental income 18 RentalIncome,LandRentReceived,NetIncome,SubsidyIncome,WageEarned,CentralBankPaymentIncome,PrepaidCorporateIncomeTaxes,CashOverShort,AccruedCorporateIncomeTaxes,CorporateIncomeTaxes rental income from land 24 LandRentReceived,RentalIncome,NetIncome,SubsidyIncome,WageEarned,CentralBankPaymentIncome,PrepaidCorporateIncomeTaxes,Land,CashOverShort,AccruedCorporateIncomeTaxes rentalincome 1 RentalIncome rentexpense 1 RentExpense-repair expenses 29 RepairsExpense,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,AllowanceForRepairs+repair expenses 28 RepairsExpense,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,AllowanceForRepairs,RepairFundReserve repairfundreserve 1 RepairFundReserve repairs 5 AllowanceForRepairs,RepairFundReserve,ReversalOfAllowanceForRepairs,ProvisionForRepairs,RepairsExpense repairsexpense 1 RepairsExpense-research and development expenses 39 ResearchAndDevelopmentExpenses,DevelopmentExpenses,LandRentPaid,NewspaperBooksExpenses,Products,Machinery,BusinessTrip,Commutation,DeliveryExpenses,SuppliesExpenses+research and development expenses 39 ResearchAndDevelopmentExpenses,DevelopmentExpenses,LandRentPaid,NewspaperBooksExpenses,Products,Machinery,BusinessTrip,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses researchanddevelopmentexpenses 1 ResearchAndDevelopmentExpenses reserve 9 ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,AccumulatedDepreciation,LegalRetainedEarnings,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve,GeneralReserve reserve deposits, asset side 89 ReserveDepositReceivable,ReserveDepositPayable,AccumulatedDepreciation,AllowanceForDoubtfulAccounts,IncomeSummary,Cash,Deposits,CurrentDeposits,Securities,InvestmentSecurities reserve deposits, liability side 50 ReserveDepositPayable,ReserveDepositReceivable,ReserveForDepreciation,AccumulatedDepreciation,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,DepositPayable,LongTermNationalBondsPayable,ShortTermNationalBondsPayable-reserve for depreciation 34 ReserveForDepreciation,AccumulatedDepreciation,AmortizationExpense,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve,ReserveDepositReceivable,ReserveDepositPayable,Depreciation,MerchandiseInventory-reserve for dividend equalization 35 DividendEqualizationReserve,ReserveForDepreciation,AccumulatedDepreciation,RepairFundReserve,ConstructionFundReserve,ReserveDepositReceivable,ReserveDepositPayable,AmortizationExpense,MerchandiseInventory,UnpaidDividends-reserve for new construction 35 ConstructionFundReserve,ReserveForDepreciation,AccumulatedDepreciation,DividendEqualizationReserve,RepairFundReserve,GainOnConstructionGrants,ReserveDepositReceivable,ReserveDepositPayable,AmortizationExpense,MerchandiseInventory-reserve for repairs 34 RepairFundReserve,ReserveForDepreciation,AccumulatedDepreciation,AllowanceForRepairs,DividendEqualizationReserve,ConstructionFundReserve,ReversalOfAllowanceForRepairs,ProvisionForRepairs,ReserveDepositReceivable,ReserveDepositPayable+reserve for depreciation 35 ReserveForDepreciation,AccumulatedDepreciation,AmortizationExpense,DividendEqualizationReserve,RepairFundReserve,ConstructionFundReserve,ReserveDepositReceivable,RetainedEarnings,ReserveDepositPayable,Depreciation+reserve for dividend equalization 36 DividendEqualizationReserve,ReserveForDepreciation,AccumulatedDepreciation,RepairFundReserve,ConstructionFundReserve,ReserveDepositReceivable,RetainedEarnings,ReserveDepositPayable,AmortizationExpense,MerchandiseInventory+reserve for new construction 36 ConstructionFundReserve,ReserveForDepreciation,AccumulatedDepreciation,DividendEqualizationReserve,RepairFundReserve,GainOnConstructionGrants,ReserveDepositReceivable,RetainedEarnings,ReserveDepositPayable,AmortizationExpense+reserve for repairs 35 RepairFundReserve,ReserveForDepreciation,AccumulatedDepreciation,AllowanceForRepairs,DividendEqualizationReserve,ConstructionFundReserve,ReversalOfAllowanceForRepairs,ProvisionForRepairs,ReserveDepositReceivable,RetainedEarnings reservedepositpayable 1 ReserveDepositPayable reservedepositreceivable 1 ReserveDepositReceivable reservefordepreciation 2 ReserveForDepreciation,AccumulatedDepreciation-retained 5 RetainedEarnings,AccumulatedDepreciation,LegalRetainedEarnings,CommunicationExpenses,EarnedSurplus-retained earnings 6 RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,EquityInEarningsOfInvestee,AccumulatedDepreciation,CommunicationExpenses+retained 4 RetainedEarnings,AccumulatedDepreciation,LegalRetainedEarnings,EarnedSurplus+retained earnings 5 RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,EquityInEarningsOfInvestee,AccumulatedDepreciation+retained earnings brought forward 5 RetainedEarnings,LegalRetainedEarnings,EarnedSurplus,EquityInEarningsOfInvestee,AccumulatedDepreciation retainedearnings 2 RetainedEarnings,LegalRetainedEarnings retirement 5 NetDefinedBenefitAsset,AllowanceForRetirementBenefits,NetDefinedBenefitLiability,RetirementBenefitExpenses,LossOnRetirementOfFixedAssets retirement benefit asset 85 NetDefinedBenefitAsset,AllowanceForRetirementBenefits,NetDefinedBenefitLiability,RetirementBenefitExpenses,LossOnRetirementOfFixedAssets,Cash,Deposits,CurrentDeposits,Securities,InvestmentSecurities-retirement benefit expenses 29 RetirementBenefitExpenses,NetDefinedBenefitAsset,AllowanceForRetirementBenefits,NetDefinedBenefitLiability,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses+retirement benefit expenses 28 RetirementBenefitExpenses,NetDefinedBenefitAsset,AllowanceForRetirementBenefits,NetDefinedBenefitLiability,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses retirement benefit liability 44 AllowanceForRetirementBenefits,NetDefinedBenefitLiability,NetDefinedBenefitAsset,RetirementBenefitExpenses,LongTermLoansPayable,ShortTermLoansPayable,LoansPayable,ReserveForDepreciation,DepositPayable,LongTermNationalBondsPayable retirementbenefitexpenses 1 RetirementBenefitExpenses revenue 41 ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome,WageEarned-reversal of allowance for doubtful accounts 70 ReversalOfAllowanceForDoubtfulAccounts,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses,ProvisionForDoubtfulAccounts,MerchandiseInventory,CommunicationExpenses,AllowanceForRepairs,AllowanceForProductWarranties-reversal of provision for bonuses 65 ReversalOfAllowanceForBonuses,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForBonuses,ProvisionForBonuses,MerchandiseInventory,ProvisionForDoubtfulAccounts,CommunicationExpenses,AllowanceForRepairs-reversal of provision for repairs 64 ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForRepairs,ProvisionForRepairs,MerchandiseInventory,ProvisionForDoubtfulAccounts,CommunicationExpenses,AllowanceForProductWarranties-reversal of provision for warranties 63 ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForBonuses,ReversalOfAllowanceForDoubtfulAccounts,AllowanceForProductWarranties,ProvisionForProductWarranties,MerchandiseInventory,ProvisionForDoubtfulAccounts,CommunicationExpenses,AllowanceForRepairs+reversal of allowance for bonuses 68 ReversalOfAllowanceForBonuses,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,AllowanceForBonuses,MerchandiseInventory,AllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForRetirementBenefits+reversal of allowance for doubtful accounts 71 ReversalOfAllowanceForDoubtfulAccounts,AllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses,ProvisionForDoubtfulAccounts,MerchandiseInventory,AllowanceForRepairs,AllowanceForProductWarranties,AllowanceForBonuses+reversal of allowance for repairs 67 ReversalOfAllowanceForRepairs,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForBonuses,AllowanceForRepairs,MerchandiseInventory,AllowanceForDoubtfulAccounts,AllowanceForProductWarranties,AllowanceForBonuses,AllowanceForRetirementBenefits+reversal of allowance for warranties 66 ReversalOfAllowanceForProductWarranties,ReversalOfAllowanceForDoubtfulAccounts,ReversalOfAllowanceForRepairs,ReversalOfAllowanceForBonuses,AllowanceForProductWarranties,MerchandiseInventory,AllowanceForDoubtfulAccounts,AllowanceForRepairs,AllowanceForBonuses,AllowanceForRetirementBenefits reversalofallowanceforbonuses 1 ReversalOfAllowanceForBonuses reversalofallowancefordoubtfulaccounts 1 ReversalOfAllowanceForDoubtfulAccounts reversalofallowanceforproductwarranties 1 ReversalOfAllowanceForProductWarranties@@ -1475,8 +1482,8 @@ short 5 ShortTermNationalBonds,ShortTermLoansReceivable,ShortTermLoansPayable,ShortTermNationalBondsPayable,CashOverShort short-term loans payable 21 ShortTermLoansPayable,ShortTermLoansReceivable,LongTermLoansPayable,LoansPayable,ShortTermNationalBondsPayable,NotesLoansPayable,ShortTermNationalBonds,LongTermLoansReceivable,DepositPayable,LongTermNationalBondsPayable short-term loans receivable 25 ShortTermLoansReceivable,LongTermLoansReceivable,ShortTermLoansPayable,NotesLoansReceivable,LoansReceivable,ShortTermNationalBonds,AccountsReceivable,ReserveDepositReceivable,LongTermLoansPayable,LoansPayable-short-term national bonds 9 ShortTermNationalBonds,ShortTermNationalBondsPayable,LongTermNationalBonds,LongTermNationalBondsPayable,ShortTermLoansReceivable,ShortTermLoansPayable,NationalBondInterestEarned,GainOnNationalSubsidies,HeldToMaturityBonds-short-term national bonds payable 22 ShortTermNationalBondsPayable,ShortTermNationalBonds,LongTermNationalBondsPayable,LongTermNationalBonds,ShortTermLoansPayable,ShortTermLoansReceivable,LongTermLoansPayable,LoansPayable,DepositPayable,ReserveDepositPayable+short-term national bonds 10 ShortTermNationalBonds,ShortTermNationalBondsPayable,LongTermNationalBonds,LongTermNationalBondsPayable,ShortTermLoansReceivable,ShortTermLoansPayable,CentralBankPaymentExpense,NationalBondInterestEarned,GainOnNationalSubsidies,HeldToMaturityBonds+short-term national bonds payable 23 ShortTermNationalBondsPayable,ShortTermNationalBonds,LongTermNationalBondsPayable,LongTermNationalBonds,ShortTermLoansPayable,ShortTermLoansReceivable,LongTermLoansPayable,LoansPayable,DepositPayable,ReserveDepositPayable shorttermloanspayable 1 ShortTermLoansPayable shorttermloansreceivable 1 ShortTermLoansReceivable shorttermnationalbonds 2 ShortTermNationalBonds,ShortTermNationalBondsPayable@@ -1485,7 +1492,7 @@ side 5 ReserveDepositReceivable,ReserveDepositPayable,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,IncomeSummary smaller 1 ReversalOfAllowanceForDoubtfulAccounts software 3 Software,SoftwareInProgress,AmortizationOfSoftware-software in progress 83 SoftwareInProgress,ConstructionInProgress,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment+software in progress 82 SoftwareInProgress,ConstructionInProgress,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment softwareinprogress 1 SoftwareInProgress special 1 DepositsInSpecialAccounts statutorywelfareexpenses 1 StatutoryWelfareExpenses@@ -1508,7 +1515,8 @@ subsidyexpense 1 SubsidyExpense subsidyincome 1 SubsidyIncome summary 1 IncomeSummary-supplies 2 SuppliesExpenses,SuppliesOnHand+supplies expense 75 SuppliesExpenses,Depreciation,AmortizationExpense,SalesCost,BusinessTrip,UtilitiesExpense,RentExpense,AdvertisingExpense,DeliveryExpenses,MiscellaneousExpenses+supplies on hand 89 SuppliesOnHand,MerchandiseInventory,LossOnValuationOfMerchandise,LongTermNationalBonds,ShortTermNationalBonds,Products,LongTermLoansReceivable,LongTermLoansPayable,ReserveForDepreciation,LongTermNationalBondsPayable suppliesexpenses 1 SuppliesExpenses suppliesonhand 1 SuppliesOnHand surplus 4 LegalCapitalSurplus,OtherCapitalSurplus,CapitalSurplus,EarnedSurplus@@ -1526,11 +1534,11 @@ technical 1 IncomeSummary temporary/suspense 1 CashOverShort than 1 ReversalOfAllowanceForDoubtfulAccounts-the 14 InvestmentInAssociate,EquityInEarningsOfInvestee,MerchandiseInventory,OtherReceivables,OtherPayables,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,PaymentFees,CommunicationExpenses,ReversalOfAllowanceForDoubtfulAccounts+the 14 InvestmentInAssociate,EquityInEarningsOfInvestee,MerchandiseInventory,OtherReceivables,OtherPayables,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,PaymentFees,ReversalOfAllowanceForDoubtfulAccounts,LongTermOtherPayables time deposits 12 TimeDeposits,Deposits,CurrentDeposits,ReserveDepositReceivable,DepositPayable,ReserveDepositPayable,DepositsReceived,SecurityDepositsPaid,DepositsInSpecialAccounts,GuaranteeDepositsReceived timedeposits 1 TimeDeposits-to 22 Products,StockInvestment,CapitalStock,CentralBankPaymentExpense,CentralBankPaymentIncome,MerchandiseInventory,CashOverShort,ToolsAndInstruments,StockSubscriptionDeposits,InterestOnSecurities-tools and instruments 17 ToolsAndInstruments,Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand+to 22 Products,StockInvestment,CapitalStock,CentralBankPaymentExpense,MerchandiseInventory,CashOverShort,ToolsAndInstruments,StockSubscriptionDeposits,InterestOnSecurities,CostOfServices+tools and instruments 18 ToolsAndInstruments,Products,Machinery,BusinessTrip,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand toolsandinstruments 1 ToolsAndInstruments trademark 1 Trademark trading securities 12 TradingSecurities,Securities,InvestmentSecurities,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnValuationOfSecurities,InterestOnSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnValuationOfSecurities@@ -1539,8 +1547,8 @@ transit 1 GoodsInTransit translation 1 CumulativeTranslationAdjustment transportation 1 BusinessTrip-travel and transportation 17 BusinessTrip,Products,Machinery,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand,ToolsAndInstruments-treasury 2 CentralBankPaymentExpense,CentralBankPaymentIncome+travel and transportation 18 BusinessTrip,Products,Machinery,MerchandiseInventory,Land,Fixtures,CashOverShort,AllowanceForDoubtfulAccounts,SuppliesOnHand,ToolsAndInstruments+treasury 1 CentralBankPaymentExpense under 4 InvestmentInAssociate,EquityInEarningsOfInvestee,MerchandiseInventory,AccumulatedDepreciation unearned revenue 41 UnearnedRevenue,ValueAdded,SubsidyIncome,NationalBondInterestEarned,DepositInterestEarned,GrossProfit,OrdinaryProfit,InterestEarned,ReceiptFee,RentalIncome unearnedrevenue 1 UnearnedRevenue@@ -1551,8 +1559,8 @@ utilities 1 UtilitiesExpense utilitiesexpense 1 UtilitiesExpense valuation 6 AllowanceForDoubtfulAccounts,AccumulatedDepreciation,ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities,LossOnValuationOfMerchandise,LossOnValuationOfSecurities-valuation difference on available-for-sale securities 93 ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities,LossOnValuationOfSecurities,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,GainOnSalesOfSecurities,InterestOnSecurities,GainOnSalesOfInvestmentSecurities,LossOnValuationOfMerchandise,LossOnSalesOfSecurities-valuation loss on goods 96 LossOnValuationOfMerchandise,LossOnValuationOfSecurities,MerchandiseInventory,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities,LossOnSalesOfElectronicallyRecordedReceivables+valuation difference on available-for-sale securities 90 ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities,LossOnValuationOfSecurities,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,GainOnSalesOfSecurities,InterestOnSecurities,GainOnSalesOfInvestmentSecurities,LossOnValuationOfMerchandise,LossOnSalesOfSecurities+valuation loss on goods 93 LossOnValuationOfMerchandise,LossOnValuationOfSecurities,MerchandiseInventory,AllowanceForDoubtfulAccounts,AccumulatedDepreciation,LossOnSalesOfFixedAssets,LossOnSalesOfNotesReceivable,ValuationDifferenceOnOtherSecurities,GainOnValuationOfSecurities,LossOnSalesOfElectronicallyRecordedReceivables valuationdifferenceonothersecurities 1 ValuationDifferenceOnOtherSecurities value added 2 ValueAdded,AllowanceForDoubtfulAccounts valueadded 1 ValueAdded@@ -1565,24 +1573,24 @@ wages 1 WageExpenditure warranties 3 AllowanceForProductWarranties,ReversalOfAllowanceForProductWarranties,ProvisionForProductWarranties welfare 2 WelfareExpenses,StatutoryWelfareExpenses-welfare expenses 25 WelfareExpenses,StatutoryWelfareExpenses,Commutation,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses+welfare expenses 24 WelfareExpenses,StatutoryWelfareExpenses,DeliveryExpenses,SuppliesExpenses,MiscellaneousExpenses,PrepaidExpenses,AccruedExpenses,CommunicationExpenses,LongTermPrepaidExpenses,OperatingExpenses welfareexpenses 2 WelfareExpenses,StatutoryWelfareExpenses when 1 ReversalOfAllowanceForDoubtfulAccounts which 1 MerchandiseInventory-work in process 81 WorkInProcess,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment,RetainedEarnings+work in process 80 WorkInProcess,Deposits,InvestmentSecurities,InvestmentInAssociate,Products,Machinery,Building,StockInvestment,EquipmentInvestment,RetainedEarnings workinprocess 1 WorkInProcess written 1 RecoveryOfBadDebts-— 10 ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,AmortizationExpense,Commutation,NetIncome,GrossProfit,OrdinaryProfit,NetLoss+— 9 ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,AmortizationExpense,NetIncome,GrossProfit,OrdinaryProfit,NetLoss が本科目を買掛金の代用にしていた経緯あり) 1 ReserveDepositPayable その他有価証券 2 ValuationDifferenceOnOtherSecurities,AvailableForSaleSecurities その他有価証券評価差額金 1 ValuationDifferenceOnOtherSecurities その他資本剰余金 1 OtherCapitalSurplus-では 2 Products,Commutation+では 1 Products と区別される) 1 AmortizationExpense のれん 3 Goodwill,GainOnBargainPurchase,AmortizationOfGoodwill のれん償却 1 AmortizationOfGoodwill-を使う 4 Products,ReserveForDepreciation,ReserveDepositPayable,Commutation-を使う) 2 ReserveForDepreciation,Commutation+を使う 3 Products,ReserveForDepreciation,ReserveDepositPayable+を使う) 1 ReserveForDepreciation を使うこと 1 ReserveDepositPayable クレジット売掛金 1 CreditCardReceivable ソフトウェア 4 AmortizationExpense,Software,SoftwareInProgress,AmortizationOfSoftware@@ -1636,8 +1644,8 @@ 創立費 1 IncorporationExpenses 区分) 2 NetIncome,NetLoss 原材料 1 RawMaterials-受入預金 — 銀行側の負債としての預金。SNA/マクロ系。従業員等からの預り金は 'DepositsReceived' 10 DepositPayable,ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,AmortizationExpense,Commutation,NetIncome,GrossProfit,OrdinaryProfit,NetLoss-受入預金 — 銀行側の負債としての預金。sna/マクロ系。従業員等からの預り金は 'depositsreceived' 10 DepositPayable,ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,AmortizationExpense,Commutation,NetIncome,GrossProfit,OrdinaryProfit,NetLoss+受入預金 — 銀行側の負債としての預金。SNA/マクロ系。従業員等からの預り金は 'DepositsReceived' 9 DepositPayable,ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,AmortizationExpense,NetIncome,GrossProfit,OrdinaryProfit,NetLoss+受入預金 — 銀行側の負債としての預金。sna/マクロ系。従業員等からの預り金は 'depositsreceived' 9 DepositPayable,ReserveDepositReceivable,ReserveForDepreciation,ReserveDepositPayable,AmortizationExpense,NetIncome,GrossProfit,OrdinaryProfit,NetLoss 受取利息 1 InterestEarned 受取商品券 1 GiftCertificatesReceived 受取地代 1 LandRentReceived@@ -1675,7 +1683,7 @@ 売上値引 1 SalesAllowances 売上割戻 1 SalesRebates 売上原価 1 SalesCost-売上総利益 — 決算振替用 10 GrossProfit,NetIncome,OrdinaryProfit,NetLoss,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,AmortizationExpense,Commutation+売上総利益 — 決算振替用 9 GrossProfit,NetIncome,OrdinaryProfit,NetLoss,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,AmortizationExpense 売掛金 2 AccountsReceivable,CreditCardReceivable 売買目的有価証券 1 TradingSecurities 契約資産 1 ContractAssets@@ -1692,12 +1700,13 @@ 建設仮勘定 1 ConstructionInProgress 当座借越 1 BankOverdraft 当座預金 1 CurrentDeposits-当期純利益 — 決算振替用。借方側に立つため Expense 区分 81 NetIncome,AmortizationExpense,Commutation,NetLoss,NetIncomeAttributableToNCI,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,Depreciation-当期純利益 — 決算振替用。借方側に立つため expense 区分 81 NetIncome,AmortizationExpense,Commutation,NetLoss,NetIncomeAttributableToNCI,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,Depreciation-当期純損失 — 決算振替用。貸方側に立つため Revenue 区分 48 NetLoss,NetIncome,GrossProfit,OrdinaryProfit,NetLossAttributableToNCI,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,AmortizationExpense-当期純損失 — 決算振替用。貸方側に立つため revenue 区分 48 NetLoss,NetIncome,GrossProfit,OrdinaryProfit,NetLossAttributableToNCI,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,AmortizationExpense+当期純利益 — 決算振替用。借方側に立つため Expense 区分 81 NetIncome,AmortizationExpense,NetLoss,NetIncomeAttributableToNCI,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,Depreciation,SalesCost+当期純利益 — 決算振替用。借方側に立つため expense 区分 81 NetIncome,AmortizationExpense,NetLoss,NetIncomeAttributableToNCI,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,Depreciation,SalesCost+当期純損失 — 決算振替用。貸方側に立つため Revenue 区分 47 NetLoss,NetIncome,GrossProfit,OrdinaryProfit,NetLossAttributableToNCI,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,AmortizationExpense+当期純損失 — 決算振替用。貸方側に立つため revenue 区分 47 NetLoss,NetIncome,GrossProfit,OrdinaryProfit,NetLossAttributableToNCI,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,AmortizationExpense 役務原価 1 CostOfServices 役務収益 1 ServiceRevenue+役員報酬 1 DirectorsCompensations 役員預り金 1 DepositsReceivedFromOfficers 手形借入金 1 NotesLoansPayable 手形売却損 1 LossOnSalesOfNotesReceivable@@ -1719,7 +1728,6 @@ 新築積立金 1 ConstructionFundReserve 新聞図書費 1 NewspaperBooksExpenses 旅費交通費 1 BusinessTrip-旧称。新規コードでは 1 Commutation 普通預金 1 Deposits 有価証券 12 Securities,InvestmentSecurities,ValuationDifferenceOnOtherSecurities,GainOnSalesOfSecurities,GainOnValuationOfSecurities,InterestOnSecurities,GainOnSalesOfInvestmentSecurities,LossOnSalesOfSecurities,LossOnValuationOfSecurities,LossOnSalesOfInvestmentSecurities 有価証券利息 1 InterestOnSecurities@@ -1757,22 +1765,22 @@ 消耗品費 1 SuppliesExpenses 消費支出。SNA/マクロ系 1 ConsumptionExpenditure 消費支出。sna/マクロ系 1 ConsumptionExpenditure-減価償却引当金 — SNA/マクロ系の旧称。簿記の間接法には 'AccumulatedDepreciation' (減価償却累計額) を使う 12 ReserveForDepreciation,ReserveDepositPayable,Commutation,Products,ReserveDepositReceivable,DepositPayable,AmortizationExpense,NetIncome,GrossProfit,OrdinaryProfit-減価償却引当金 — sna/マクロ系の旧称。簿記の間接法には 'accumulateddepreciation' (減価償却累計額) を使う 12 ReserveForDepreciation,ReserveDepositPayable,Commutation,Products,ReserveDepositReceivable,DepositPayable,AmortizationExpense,NetIncome,GrossProfit,OrdinaryProfit+減価償却引当金 — SNA/マクロ系の旧称。簿記の間接法には 'AccumulatedDepreciation' (減価償却累計額) を使う 11 ReserveForDepreciation,ReserveDepositPayable,Products,ReserveDepositReceivable,DepositPayable,AmortizationExpense,NetIncome,GrossProfit,OrdinaryProfit,NetLoss+減価償却引当金 — sna/マクロ系の旧称。簿記の間接法には 'accumulateddepreciation' (減価償却累計額) を使う 11 ReserveForDepreciation,ReserveDepositPayable,Products,ReserveDepositReceivable,DepositPayable,AmortizationExpense,NetIncome,GrossProfit,OrdinaryProfit,NetLoss 減価償却累計額 2 ReserveForDepreciation,AccumulatedDepreciation 減価償却費 2 Depreciation,AmortizationExpense 満期保有目的債券 1 HeldToMaturityBonds-準備預金, 負債側 — 中央銀行が受け入れる準備預金。SNA/マクロ系 10 ReserveDepositPayable,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,AmortizationExpense,Commutation,NetIncome,GrossProfit,OrdinaryProfit,NetLoss-準備預金, 負債側 — 中央銀行が受け入れる準備預金。sna/マクロ系 10 ReserveDepositPayable,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,AmortizationExpense,Commutation,NetIncome,GrossProfit,OrdinaryProfit,NetLoss-準備預金, 資産側 — 市中銀行が中央銀行に置く準備預金。SNA/マクロ系 10 ReserveDepositReceivable,ReserveDepositPayable,ReserveForDepreciation,DepositPayable,AmortizationExpense,Commutation,NetIncome,GrossProfit,OrdinaryProfit,NetLoss-準備預金, 資産側 — 市中銀行が中央銀行に置く準備預金。sna/マクロ系 10 ReserveDepositReceivable,ReserveDepositPayable,ReserveForDepreciation,DepositPayable,AmortizationExpense,Commutation,NetIncome,GrossProfit,OrdinaryProfit,NetLoss+準備預金, 負債側 — 中央銀行が受け入れる準備預金。SNA/マクロ系 9 ReserveDepositPayable,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,AmortizationExpense,NetIncome,GrossProfit,OrdinaryProfit,NetLoss+準備預金, 負債側 — 中央銀行が受け入れる準備預金。sna/マクロ系 9 ReserveDepositPayable,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,AmortizationExpense,NetIncome,GrossProfit,OrdinaryProfit,NetLoss+準備預金, 資産側 — 市中銀行が中央銀行に置く準備預金。SNA/マクロ系 9 ReserveDepositReceivable,ReserveDepositPayable,ReserveForDepreciation,DepositPayable,AmortizationExpense,NetIncome,GrossProfit,OrdinaryProfit,NetLoss+準備預金, 資産側 — 市中銀行が中央銀行に置く準備預金。sna/マクロ系 9 ReserveDepositReceivable,ReserveDepositPayable,ReserveForDepreciation,DepositPayable,AmortizationExpense,NetIncome,GrossProfit,OrdinaryProfit,NetLoss 火災損失 1 LossOnFire 為替差損 1 ForeignExchangeLosses 為替差益 1 ForeignExchangeGains 為替換算調整勘定; 在外子会社等の外貨建財務諸表の換算差額を計上する OCI/資本の部の項目 1 CumulativeTranslationAdjustment 為替換算調整勘定; 在外子会社等の外貨建財務諸表の換算差額を計上する oci/資本の部の項目 1 CumulativeTranslationAdjustment-無形固定資産償却費 — 特許権・商標権・ソフトウェア等の無形資産の償却費。有形の 'Depreciation' (減価償却費) と区別される 11 AmortizationExpense,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,Depreciation,Commutation,NetIncome,GrossProfit,OrdinaryProfit-無形固定資産償却費 — 特許権・商標権・ソフトウェア等の無形資産の償却費。有形の 'depreciation' (減価償却費) と区別される 11 AmortizationExpense,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,Depreciation,Commutation,NetIncome,GrossProfit,OrdinaryProfit+無形固定資産償却費 — 特許権・商標権・ソフトウェア等の無形資産の償却費。有形の 'Depreciation' (減価償却費) と区別される 10 AmortizationExpense,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,Depreciation,NetIncome,GrossProfit,OrdinaryProfit,NetLoss+無形固定資産償却費 — 特許権・商標権・ソフトウェア等の無形資産の償却費。有形の 'depreciation' (減価償却費) と区別される 10 AmortizationExpense,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,Depreciation,NetIncome,GrossProfit,OrdinaryProfit,NetLoss 特許権 3 AmortizationExpense,Patent,AmortizationOfPatents 特許権・商標権・ソフトウェア等の無形資産の償却費。有形の 1 AmortizationExpense 特許権償却 1 AmortizationOfPatents@@ -1792,7 +1800,7 @@ 租税収入。SNA/マクロ系 1 TaxesRevenue 租税収入。sna/マクロ系 1 TaxesRevenue 立替金 1 PaymentsOnBehalf-経常利益 — 決算振替用 10 OrdinaryProfit,NetIncome,GrossProfit,NetLoss,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,AmortizationExpense,Commutation+経常利益 — 決算振替用 9 OrdinaryProfit,NetIncome,GrossProfit,NetLoss,ReserveDepositReceivable,ReserveForDepreciation,DepositPayable,ReserveDepositPayable,AmortizationExpense 給料 1 WageExpenditure 繰延税金負債 1 DeferredTaxLiabilities 繰延税金資産 1 DeferredTaxAssets@@ -1830,9 +1838,7 @@ 退職給付に係る資産 1 NetDefinedBenefitAsset 退職給付引当金 1 AllowanceForRetirementBenefits 退職給付費用 1 RetirementBenefitExpenses-通信費 2 Commutation,CommunicationExpenses-通信費 — 旧称。新規コードでは 'CommunicationExpenses' を使う 12 Commutation,ReserveForDepreciation,ReserveDepositPayable,Products,ReserveDepositReceivable,DepositPayable,AmortizationExpense,NetIncome,GrossProfit,OrdinaryProfit-通信費 — 旧称。新規コードでは 'communicationexpenses' を使う 12 Commutation,ReserveForDepreciation,ReserveDepositPayable,Products,ReserveDepositReceivable,DepositPayable,AmortizationExpense,NetIncome,GrossProfit,OrdinaryProfit+通信費 1 CommunicationExpenses 還付法人税等 2 IncomeTaxesRefundReceivable,RefundOfIncomeTaxes 配当平均積立金 1 DividendEqualizationReserve 金 75 Cash,Deposits,CurrentDeposits,LongTermLoansReceivable,AccountsReceivable,ShortTermLoansReceivable,ReserveDepositReceivable,Gold,CapitalStock,RetainedEarnings
− test/fixtures/pre-vland2/ordinals.tsv
@@ -1,118 +0,0 @@-# pre-vland2 Enum ordinals (constructor, fromEnum) — insertion discipline pin; commit 85d6a7f-Cash 0-Deposits 1-CurrentDeposits 2-Securities 3-InvestmentSecurities 4-InvestmentInAssociate 5-LongTermNationalBonds 6-ShortTermNationalBonds 7-Products 8-Machinery 9-Building 10-Vehicle 11-StockInvestment 12-EquipmentInvestment 13-LongTermLoansReceivable 14-AccountsReceivable 15-ShortTermLoansReceivable 16-ReserveDepositReceivable 17-Gold 18-GovernmentService 19-CapitalStock 20-RetainedEarnings 21-LongTermLoansPayable 22-ShortTermLoansPayable 23-LoansPayable 24-ReserveForDepreciation 25-DepositPayable 26-LongTermNationalBondsPayable 27-ShortTermNationalBondsPayable 28-ReserveDepositPayable 29-CentralBankNotePayable 30-Depreciation 31-AmortizationExpense 32-SalesCost 33-BusinessTrip 34-Commutation 35-UtilitiesExpense 36-RentExpense 37-AdvertisingExpense 38-DeliveryExpenses 39-SuppliesExpenses 40-MiscellaneousExpenses 41-WageExpenditure 42-InterestExpense 43-TaxesExpense 44-ConsumptionExpenditure 45-SubsidyExpense 46-CentralBankPaymentExpense 47-Purchases 48-NetIncome 49-ValueAdded 50-SubsidyIncome 51-NationalBondInterestEarned 52-DepositInterestEarned 53-GrossProfit 54-OrdinaryProfit 55-InterestEarned 56-ReceiptFee 57-RentalIncome 58-WageEarned 59-TaxesRevenue 60-CentralBankPaymentIncome 61-Sales 62-EquityInEarningsOfInvestee 63-NetLoss 64-PettyCash 65-NotesReceivable 66-ElectronicallyRecordedReceivable 67-CreditCardReceivable 68-NotesLoansReceivable 69-MerchandiseInventory 70-AdvancesPaid 71-PrepaidExpenses 72-AccruedRevenue 73-OtherReceivables 74-PaymentsOnBehalf 75-SuspensePayments 76-ConsumptionTaxPaid 77-PrepaidCorporateIncomeTaxes 78-Land 79-Fixtures 80-Patent 81-Trademark 82-Software 83-CashOverShort 84-AccountsPayable 85-NotesPayable 86-ElectronicallyRecordedObligations 87-NotesLoansPayable 88-BankOverdraft 89-AdvancesReceived 90-UnearnedRevenue 91-AccruedExpenses 92-OtherPayables 93-DepositsReceived 94-SuspenseReceipts 95-ConsumptionTaxReceived 96-AccruedConsumptionTax 97-AccruedCorporateIncomeTaxes 98-UnpaidDividends 99-AllowanceForDoubtfulAccounts 100-AccumulatedDepreciation 101-LegalRetainedEarnings 102-CumulativeTranslationAdjustment 103-ProvisionForDoubtfulAccounts 104-BadDebtLoss 105-LossOnSalesOfFixedAssets 106-LossOnSalesOfNotesReceivable 107-PaymentFees 108-MiscellaneousLoss 109-CorporateIncomeTaxes 110-CommunicationExpenses 111-GainOnSalesOfFixedAssets 112-RecoveryOfBadDebts 113-MiscellaneousIncome 114-ReversalOfAllowanceForDoubtfulAccounts 115-AccountTitle 116
test/fixtures/readout-baseline-p1/README.md view
@@ -20,8 +20,8 @@ The `alg-*` files cover `bar`, `norm`, `balance`, `diffRL`, `compress`, `balanceMapBy`, `netPairMapBy`, `postFromNetBy`, `projNetNorm`, `balanceBy`,-`Pair.compare`, `closingEntries`, `accountBalances`, `checkedEntry`,-`trialBalanceFindings`, and `periodResultOfAlg`. The+`Pair.compare`, `closingEntries`, `accountBalances`, `checkedEntry`, and+`periodResultOfAlg`. The `journal-*` files cover `bar`, `norm`, `projWithBaseNetNorm`, `projWithNoteBaseNetNorm`, `compress`, and `closingEntries`. The Double journal files also cover `carryEntries` and `carryBefore`; those APIs accept Double
test/fixtures/readout-baseline-p1/alg-decimal-f-dec2.tsv view
@@ -49,9 +49,6 @@ accountBalances all map RetainedEarnings DebitBalance 0.1 accountBalances all map Purchases CreditBalance 0.09 accountBalances all map Sales DebitBalance 20.18-trialBalanceFindings BeforeClosing result [UnbalancedTrialBalance 1255.37 1255.16,UnexplainedAbnormalBalance Cash Debit (CreditBalance 1234.55),UnexplainedAbnormalBalance RetainedEarnings Credit (DebitBalance 0.1),UnexplainedAbnormalBalance Purchases Debit (CreditBalance 0.09),UnexplainedAbnormalBalance Sales Credit (DebitBalance 20.18)]-trialBalanceFindings.debitTotal BeforeClosing scalar 1255.37-trialBalanceFindings.creditTotal BeforeClosing scalar 1255.16 Convert.Checked.checkedEntry 0.1+0.2 vs 0.3 result Right 0.3:@Hat:<Cash .+ 0.1:@Not:<Cash .+ 0.2:@Not:<Cash Convert.Checked.debitInput 0.1+0.2 scalar 0.3 Convert.Checked.creditInput 0.3 scalar 0.3
test/fixtures/readout-baseline-p1/alg-decimal-f-int.tsv view
@@ -49,7 +49,4 @@ accountBalances all map RetainedEarnings DebitBalance 12245 accountBalances all map Purchases CreditBalance 1 accountBalances all map Sales CreditBalance 3-trialBalanceFindings BeforeClosing result [UnbalancedTrialBalance 24794 214,UnexplainedAbnormalBalance Cash Debit (CreditBalance 3),UnexplainedAbnormalBalance RetainedEarnings Credit (DebitBalance 12245),UnexplainedAbnormalBalance Purchases Debit (CreditBalance 1)]-trialBalanceFindings.debitTotal BeforeClosing scalar 24794-trialBalanceFindings.creditTotal BeforeClosing scalar 214 periodResultOfAlg all PeriodProfit 4
test/fixtures/readout-baseline-p1/alg-double-f-cancel.tsv view
@@ -46,7 +46,4 @@ accountBalances all map RetainedEarnings NoBalance accountBalances all map Purchases CreditBalance 0x433fffffffffffff 9.007199254740991e15 accountBalances all map Sales DebitBalance 0x3ff0000000000000 1.0-trialBalanceFindings BeforeClosing result [UnbalancedTrialBalance 3.8014398509481984e16 4.7021597764222976e16,UnexplainedAbnormalBalance AccountsReceivable Debit (CreditBalance 1.0),UnexplainedAbnormalBalance Purchases Debit (CreditBalance 9.007199254740991e15),UnexplainedAbnormalBalance Sales Credit (DebitBalance 1.0)]-trialBalanceFindings.debitTotal BeforeClosing scalar 0x4360e1bc9bf04000 3.8014398509481984e16-trialBalanceFindings.creditTotal BeforeClosing scalar 0x4364e1bc9bf04000 4.7021597764222976e16 periodResultOfAlg all PeriodProfit 0x433ffffffffffffe 9.00719925474099e15
test/fixtures/readout-baseline-p1/alg-double-f-dec2.tsv view
@@ -53,9 +53,6 @@ accountBalances all map RetainedEarnings DebitBalance 0x3fb9999999999998 9.999999999999998e-2 accountBalances all map Purchases CreditBalance 0x3fb70a3d70a3d70b 9.000000000000001e-2 accountBalances all map Sales DebitBalance 0x40342e147ae147ae 20.18-trialBalanceFindings BeforeClosing result [UnbalancedTrialBalance 1255.37 1255.1599999999999,UnexplainedAbnormalBalance Cash Debit (CreditBalance 1234.55),UnexplainedAbnormalBalance RetainedEarnings Credit (DebitBalance 9.999999999999998e-2),UnexplainedAbnormalBalance Purchases Debit (CreditBalance 9.000000000000001e-2),UnexplainedAbnormalBalance Sales Credit (DebitBalance 20.18)]-trialBalanceFindings.debitTotal BeforeClosing scalar 0x40939d7ae147ae14 1255.37-trialBalanceFindings.creditTotal BeforeClosing scalar 0x40939ca3d70a3d70 1255.1599999999999 Convert.Checked.checkedEntry 0.1+0.2 vs 0.3 result Left (Imbalanced {_debitTotal = 0.30000000000000004, _creditTotal = 0.3} :| []) Convert.Checked.debitInput 0.1+0.2 scalar 0x3fd3333333333334 0.30000000000000004 Convert.Checked.creditInput 0.3 scalar 0x3fd3333333333333 0.3
test/fixtures/readout-baseline-p1/alg-double-f-exp.tsv view
@@ -39,7 +39,4 @@ accountBalances all map RetainedEarnings DebitBalance 0x3ff0000000000000 1.0 accountBalances all map Purchases CreditBalance 0x7e37e43c8800759c 1.0e300 accountBalances all map Sales CreditBalance 0x7ff0000000000000 Infinity-trialBalanceFindings BeforeClosing result [UnbalancedTrialBalance 1.0e300 Infinity,UnexplainedAbnormalBalance RetainedEarnings Credit (DebitBalance 1.0),UnexplainedAbnormalBalance Purchases Debit (CreditBalance 1.0e300)]-trialBalanceFindings.debitTotal BeforeClosing scalar 0x7e37e43c8800759c 1.0e300-trialBalanceFindings.creditTotal BeforeClosing scalar 0x7ff0000000000000 Infinity periodResultOfAlg all PeriodProfit 0x7ff0000000000000 Infinity
test/fixtures/readout-baseline-p1/alg-double-f-int.tsv view
@@ -49,7 +49,4 @@ accountBalances all map RetainedEarnings DebitBalance 0x40c7ea8000000000 12245.0 accountBalances all map Purchases CreditBalance 0x3ff0000000000000 1.0 accountBalances all map Sales CreditBalance 0x4008000000000000 3.0-trialBalanceFindings BeforeClosing result [UnbalancedTrialBalance 24794.0 214.0,UnexplainedAbnormalBalance Cash Debit (CreditBalance 3.0),UnexplainedAbnormalBalance RetainedEarnings Credit (DebitBalance 12245.0),UnexplainedAbnormalBalance Purchases Debit (CreditBalance 1.0)]-trialBalanceFindings.debitTotal BeforeClosing scalar 0x40d8368000000000 24794.0-trialBalanceFindings.creditTotal BeforeClosing scalar 0x406ac00000000000 214.0 periodResultOfAlg all PeriodProfit 0x4010000000000000 4.0
test/fixtures/readout-baseline-p1/alg-double-f-sub.tsv view
@@ -87,7 +87,4 @@ accountBalances all map RetainedEarnings DebitBalance 0x000fffffffffffff 2.225073858507201e-308 accountBalances all map Purchases CreditBalance 0x3ff0000000000000 1.0 accountBalances all map Sales CreditBalance 0x000fffffffffffff 2.225073858507201e-308-trialBalanceFindings BeforeClosing result [UnbalancedTrialBalance 1.0 1.0,UnexplainedAbnormalBalance Cash Debit (CreditBalance 2.2250738585072004e-308),UnexplainedAbnormalBalance RetainedEarnings Credit (DebitBalance 2.225073858507201e-308),UnexplainedAbnormalBalance Purchases Debit (CreditBalance 1.0)]-trialBalanceFindings.debitTotal BeforeClosing scalar 0x3ff0000000000000 1.0-trialBalanceFindings.creditTotal BeforeClosing scalar 0x3ff0000000000000 1.0 periodResultOfAlg all PeriodProfit 0x3ff0000000000000 1.0
test/fixtures/registry-aliases/alias-resolution.tsv view
@@ -23,7 +23,6 @@ CentralBankPaymentExpense Right CentralBankPaymentExpense CentralBankPaymentIncome Right CentralBankPaymentIncome CommunicationExpenses Right CommunicationExpenses- Commutation Right Commutation ConsumptionExpenditure Right ConsumptionExpenditure ConsumptionTaxPaid Right ConsumptionTaxPaid ConsumptionTaxReceived Right ConsumptionTaxReceived@@ -218,7 +217,7 @@ 賃金収入 Right WageEarned 資本金 Right CapitalStock 車両運搬具 Right Vehicle- 通信費 Left (AmbiguousAccount " \36890\20449\36027 " [CommunicationExpenses,Commutation])+ 通信費 Right CommunicationExpenses 金 Right Gold 長期借入金 Right LongTermLoansPayable 長期国債 Left (AmbiguousAccount " \38263\26399\22269\20661 " [LongTermNationalBonds,LongTermNationalBondsPayable])@@ -275,7 +274,6 @@ CENTRALBANKPAYMENTINCOME Right CentralBankPaymentIncome COGS Right SalesCost COMMUNICATIONEXPENSES Right CommunicationExpenses-COMMUTATION Right Commutation CONSUMPTIONEXPENDITURE Right ConsumptionExpenditure CONSUMPTIONTAXPAID Right ConsumptionTaxPaid CONSUMPTIONTAXRECEIVED Right ConsumptionTaxReceived@@ -291,7 +289,6 @@ CentralBankPaymentExpense Right CentralBankPaymentExpense CentralBankPaymentIncome Right CentralBankPaymentIncome CommunicationExpenses Right CommunicationExpenses-Commutation Right Commutation ConsumptionExpenditure Right ConsumptionExpenditure ConsumptionTaxPaid Right ConsumptionTaxPaid ConsumptionTaxReceived Right ConsumptionTaxReceived@@ -498,7 +495,6 @@ centralbankpaymentincome Right CentralBankPaymentIncome cogs Right SalesCost communicationexpenses Right CommunicationExpenses-commutation Right Commutation consumptionexpenditure Right ConsumptionExpenditure consumptiontaxpaid Right ConsumptionTaxPaid consumptiontaxreceived Right ConsumptionTaxReceived@@ -690,7 +686,7 @@ 賃金収入 Right WageEarned 資本金 Right CapitalStock 車両運搬具 Right Vehicle-通信費 Left (AmbiguousAccount "\36890\20449\36027" [CommunicationExpenses,Commutation])+通信費 Right CommunicationExpenses 金 Right Gold 長期借入金 Right LongTermLoansPayable 長期国債 Left (AmbiguousAccount "\38263\26399\22269\20661" [LongTermNationalBonds,LongTermNationalBondsPayable])
test/fixtures/statement-presentation/presentation.txt view
@@ -10,7 +10,7 @@ 60.00:@Not:<LoansPayable -- projFixedLiability 0--- projCapitalStock+-- projNonContraCreditEquity 40.00:@Not:<CapitalStock ## b2-pl -- projCurrentAssets@@ -23,7 +23,7 @@ 0 -- projFixedLiability 0--- projCapitalStock+-- projNonContraCreditEquity 0 ## b3-contra -- projCurrentAssets@@ -36,7 +36,7 @@ 400.00:@Not:<LoansPayable -- projFixedLiability 0--- projCapitalStock+-- projNonContraCreditEquity 2000.00:@Not:<CapitalStock ## b4-abnormal -- projCurrentAssets@@ -49,7 +49,7 @@ 200.00:@Not:<LoansPayable -- projFixedLiability 0--- projCapitalStock+-- projNonContraCreditEquity 0 ## b5-closing -- projCurrentAssets@@ -62,5 +62,5 @@ 400.00:@Not:<LoansPayable -- projFixedLiability 0--- projCapitalStock+-- projNonContraCreditEquity 2000.00:@Not:<CapitalStock
test/fixtures/wire-format-p2/decode-boundaries.tsv view
@@ -2,9 +2,9 @@ reject Posted negative 01ff000000000000000700000000000010ffffffffffffffcc reject Posted infinity 010100000000000000070000000000001000000000000003cc reject Posted above bound 01010000000000000007000000000000100000000000000351-reject TransferRules zero coefficient 000000000000000100800000803e0100000000000000000000000000+reject TransferScale removed operation 01 reject TransferRules overlap 000000000000000200800000803e0000800000803e00-reject AccountTitles unused code 80f3+reject AccountTitles unused code 80f4 reject AccountTitles old code 0000 reject Alg invalid tag 0000000000000003 reject Alg negative value 000000000000000101ff000000000000000700000000000010ffffffffffffffcc008000
test/fixtures/wire-format-p2/wire-format.tsv view
@@ -41,7 +41,6 @@ AccountTitles AmortizationExpense 8020 AccountTitles SalesCost 8021 AccountTitles BusinessTrip 8022-AccountTitles Commutation 8023 AccountTitles UtilitiesExpense 8024 AccountTitles RentExpense 8025 AccountTitles AdvertisingExpense 8026@@ -249,6 +248,7 @@ AccountTitles SalesAllowances 80f0 AccountTitles PurchaseAllowances 80f1 AccountTitles ReversalOfAllowanceForBonuses 80f2+AccountTitles DirectorsCompensations 80f3 AccountTitles AccountTitle ffff CountUnit Yen 00 CountUnit Dollar 01@@ -262,12 +262,9 @@ Pair both sides and repeated values 00000000000000030101000000000000000700000000000010ffffffffffffffcc0101000000000000000700000000000010ffffffffffffffcc0101000000000000000700000000000018ffffffffffffffcd00000000000000020101000000000000000700000000000010ffffffffffffffcd0101000000000000000700000000000010ffffffffffffffce Alg Zero 0000000000000000 Alg singleton 00000000000000010101000000000000000700000000000010ffffffffffffffcc008000-Alg repeated base on both sides 00000000000000020000000000000002800000000000000000020101000000000000000700000000000010ffffffffffffffcc0101000000000000000700000000000010ffffffffffffffcd00000000000000010101000000000000000700000000000018ffffffffffffffcd803e000000000000000000000000000000010101000000000000000700000000000010ffffffffffffffce+Alg repeated base on both sides 00000000000000020000000000000002803e000000000000000000000000000000010101000000000000000700000000000010ffffffffffffffce800000000000000000020101000000000000000700000000000010ffffffffffffffcc0101000000000000000700000000000010ffffffffffffffcd00000000000000010101000000000000000700000000000018ffffffffffffffcd TransferScale Relabel 00-TransferScale MulBy 010101000000000000000700000000000010ffffffffffffffcd-TransferScale DivBy 020101000000000000000700000000000010ffffffffffffffcb-TransferRule relabel 00800001803e00-TransferRule multiply 01803e008000010101000000000000000700000000000010ffffffffffffffcd+TransferRule Relabel 00800001803e00 TransferRules empty 0000000000000000 TransferRules one 000000000000000100800000803e00 TransferRules two sorted rules 000000000000000200800000803e0001800001803e00
test/fixtures/write-rows-0510/ebex8-journal.tsv view
@@ -1,5 +1,5 @@ # write-rows-0510 journalRows ex8CorrectionLedger ex8GetDay; schema 1; commit 250cbf15d9663f163f98f0ce3650f057de80170d Day Debit Amount Credit Amount-2024-03-10 Sales 45000 Sales 45000- Cash 45000 Cash 45000+2024-03-10 Cash 45000 Cash 45000+ Sales 45000 Sales 45000 2024-03-15 Cash 45000 AccountsReceivable 45000
tools/check-orphans.py view
@@ -13,21 +13,34 @@ ROOT = pathlib.Path(__file__).resolve().parent.parent BASELINE = ROOT / "test/fixtures/export-surface-p2/orphans.txt"+WORK_DIR = ".stack-work-orphans" +def without_location(entry):+ """Drop the path prefix and the line and column of a "Defined at" comment.++ Editing lines above an existing instance moves it without adding an+ orphan, so the comparison ignores where the instance currently sits.+ """+ declaration = entry.split(": ", 1)[1]+ return re.sub(r"(-- Defined at \S+?):\d+:\d+", r"\1", declaration)++ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--update", action="store_true", help="Write the current warning set") args = parser.parse_args()+ # GHC reports an orphan only when it compiles the module, so every module+ # is compiled again. The warning comes from the type checker, so the build+ # runs without optimisation (--fast). It uses its own work directory, which+ # keeps the optimised products of the normal build in .stack-work untouched.+ # Do not pass -j to GHC here: with parallel make the progress lines of other+ # modules land inside a warning, and the declaration can no longer be read. command = ["stack", *shlex.split(os.environ.get("STACK_ARGS", "")),- "--stack-yaml", str(ROOT / "stack.yaml"), "build"]- if os.environ.get("EA_VISUALIZE", "1") == "0":- command.extend(["exchangealgebra", "--test", "--no-run-tests"])- command.extend(["--flag", "exchangealgebra:-visualize"])- else:- command.extend(["--test", "--bench", "--no-run-tests",- "--no-run-benchmarks"])- command.extend(["--force-dirty", "--ghc-options=-fforce-recomp -Worphans"])+ "--stack-yaml", str(ROOT / "stack.yaml"),+ "--work-dir", WORK_DIR, "build", "--fast",+ "--test", "--bench", "--no-run-tests", "--no-run-benchmarks",+ "--force-dirty", "--ghc-options=-fforce-recomp -Worphans"] result = subprocess.run(command, cwd=ROOT, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if result.returncode:@@ -66,8 +79,8 @@ raise RuntimeError(f"Missing orphan baseline: {BASELINE}") else: baseline = set(BASELINE.read_text().splitlines())- known_instances = Counter(line.split(": ", 1)[1] for line in baseline)- current_instances = Counter(warning.split(": ", 1)[1] for warning in warnings)+ known_instances = Counter(without_location(line) for line in baseline)+ current_instances = Counter(without_location(warning) for warning in warnings) added = {instance: count - known_instances[instance] for instance, count in current_instances.items() if count > known_instances[instance]}