@things-factory/integration-barobill 0.0.0-stage → 10.1.281

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +5 -2
  2. package/dist-server/engine/connector/barobill-client.d.ts +106 -0
  3. package/dist-server/engine/connector/barobill-client.js +180 -0
  4. package/dist-server/engine/connector/barobill-connector.d.ts +36 -0
  5. package/dist-server/engine/connector/barobill-connector.js +51 -0
  6. package/dist-server/engine/connector/soap-xml.d.ts +23 -0
  7. package/dist-server/engine/connector/soap-xml.js +94 -0
  8. package/dist-server/engine/index.d.ts +2 -0
  9. package/dist-server/engine/index.js +5 -0
  10. package/dist-server/engine/rules/bank-lines.d.ts +49 -0
  11. package/dist-server/engine/rules/bank-lines.js +77 -0
  12. package/dist-server/engine/rules/card-charges.d.ts +47 -0
  13. package/dist-server/engine/rules/card-charges.js +63 -0
  14. package/dist-server/engine/rules/period.d.ts +12 -0
  15. package/dist-server/engine/rules/period.js +31 -0
  16. package/dist-server/engine/rules/tax-invoices.d.ts +40 -0
  17. package/dist-server/engine/rules/tax-invoices.js +45 -0
  18. package/dist-server/engine/task/bank-lines.d.ts +22 -0
  19. package/dist-server/engine/task/bank-lines.js +28 -0
  20. package/dist-server/engine/task/card-charges.d.ts +19 -0
  21. package/dist-server/engine/task/card-charges.js +23 -0
  22. package/dist-server/engine/task/index.d.ts +3 -0
  23. package/dist-server/engine/task/index.js +6 -0
  24. package/dist-server/engine/task/task-input.d.ts +19 -0
  25. package/dist-server/engine/task/task-input.js +27 -0
  26. package/dist-server/engine/task/tax-invoices.d.ts +25 -0
  27. package/dist-server/engine/task/tax-invoices.js +28 -0
  28. package/dist-server/index.d.ts +7 -0
  29. package/dist-server/index.js +14 -0
  30. package/dist-server/service/barobill-setting-rules.d.ts +40 -0
  31. package/dist-server/service/barobill-setting-rules.js +71 -0
  32. package/dist-server/service/barobill-setting.d.ts +21 -0
  33. package/dist-server/service/barobill-setting.js +121 -0
  34. package/dist-server/service/index.d.ts +5 -0
  35. package/dist-server/service/index.js +10 -0
  36. package/helps/integration/connector/barobill-connector.md +21 -0
  37. package/helps/integration/task/barobill-bank-lines.md +5 -0
  38. package/helps/integration/task/barobill-card-charges.md +5 -0
  39. package/helps/integration/task/barobill-tax-invoices.md +5 -0
  40. package/package.json +41 -4
  41. package/things-factory.config.js +1 -0
  42. package/translations/en.json +16 -0
  43. package/translations/es.json +16 -0
  44. package/translations/ja.json +16 -0
  45. package/translations/ko.json +16 -0
  46. package/translations/ms.json +16 -0
  47. package/translations/zh.json +16 -0
package/README.md CHANGED
@@ -1,3 +1,6 @@
1
- # Temporary Holding Version
1
+ # @things-factory/integration-barobill
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 바로빌 조회 연동 — 은행 계좌 입출금, 법인카드 승인, 세금계산서를 읽어 업체에 매이지 않은 줄 모양으로 내놓는다(ADR-0204). 읽기 연산만 보낸다.
4
+
5
+ - 시험: `npm test` — 녹음·작성한 SOAP 응답으로 돈다(키 필요 없음).
6
+ - 실 서버 점검: `BAROBILL_CERTKEY=… BAROBILL_CORPNUM=… BAROBILL_USERID=… npm run probe -- bank|card|invoice|all [--days 7] [--record <저장소 밖 폴더>]`
@@ -0,0 +1,106 @@
1
+ import { XmlNode, XmlValue } from './soap-xml';
2
+ /**
3
+ * Barobill's web services (SOAP 1.1 over HTTPS), read only.
4
+ *
5
+ * - Every call takes the partner key (CERTKEY) and the member's business number (CorpNum, digits only).
6
+ * - A failure is a negative number where the answer would be: the int result itself, `CurrentPage` of a paged list, or
7
+ * the number field of a list's only item (`BankAccountNum`, `CardNum` - seen on the test server 2026-11-14).
8
+ * `GetErrString` words it.
9
+ * - Only the operations in `READ_OPERATIONS` can be called. Registering accounts or cards, issuing invoices and the
10
+ * rest are Barobill's own screens - this client cannot send them, whatever a task or a script asks.
11
+ */
12
+ export declare const BAROBILL_ORIGINS: {
13
+ readonly test: "https://testws.baroservice.com";
14
+ readonly production: "https://ws.baroservice.com";
15
+ };
16
+ export type BarobillService = 'BANKACCOUNT' | 'CARD' | 'TI';
17
+ export declare const READ_OPERATIONS: Record<BarobillService, readonly string[]>;
18
+ /**
19
+ * The query codes Barobill's period lists take. Read from the manual's wording; the probe (`npm run probe`) prints what
20
+ * each answers on the test server, and these are corrected there if it says otherwise.
21
+ */
22
+ export declare const QUERY_CODES: {
23
+ /** GetPeriodBankAccountLogEx2 TransDirection */
24
+ readonly bankDirection: {
25
+ readonly all: 1;
26
+ readonly deposit: 2;
27
+ readonly withdrawal: 3;
28
+ };
29
+ /** OrderDirection of the period lists */
30
+ readonly order: {
31
+ readonly oldestFirst: 1;
32
+ readonly newestFirst: 2;
33
+ };
34
+ /** GetPeriodTaxInvoice*ListEx DateType */
35
+ readonly invoiceDate: {
36
+ readonly written: 1;
37
+ readonly issued: 2;
38
+ readonly sent: 3;
39
+ };
40
+ /**
41
+ * GetPeriodTaxInvoice*ListEx TaxType. The test server takes 1 and 3 and refuses 0, 2 and 4 (-11010, 2026-11-14) -
42
+ * there is no 'every kind', so a period is asked once for each.
43
+ */
44
+ readonly invoiceTax: readonly [1, 3];
45
+ };
46
+ export declare class BarobillError extends Error {
47
+ code: number;
48
+ operation: string;
49
+ constructor(operation: string, code: number, text: string);
50
+ }
51
+ export interface BarobillClientOptions {
52
+ certKey: string;
53
+ corpNum: string;
54
+ /** 'test' (default) or 'production', or an origin of its own (a mock server). */
55
+ server?: string;
56
+ }
57
+ export interface BarobillPage<T> {
58
+ items: T[];
59
+ total: number;
60
+ }
61
+ export declare const digitsOnly: (value: string) => string;
62
+ export declare class BarobillClient {
63
+ readonly origin: string;
64
+ readonly corpNum: string;
65
+ private readonly certKey;
66
+ constructor(options: BarobillClientOptions);
67
+ /** The body's `<operation>Result`. Only a read operation is sent. */
68
+ call(service: BarobillService, operation: string, args?: Record<string, string | number>): Promise<XmlValue | XmlValue[] | undefined>;
69
+ /** Barobill's words for a failure code; '' when it has none. */
70
+ errorText(service: BarobillService, code: number): Promise<string>;
71
+ private refuse;
72
+ /** 1 when the key and the business number are good together; a negative code says why not. */
73
+ checkKey(service?: BarobillService): Promise<number>;
74
+ /** Every page of a period list, oldest first. */
75
+ allPages(service: BarobillService, operation: string, args: Record<string, string | number>, listName: string, itemName: string): Promise<BarobillPage<XmlNode>>;
76
+ /** A list of what is registered; its only item carrying a negative number in `numberField` is the failure. */
77
+ private registered;
78
+ /** The accounts registered with Barobill for collection. */
79
+ bankAccounts(): Promise<XmlNode[]>;
80
+ /** An account's lines between two days (YYYYMMDD), both included. */
81
+ bankLines(query: {
82
+ userId: string;
83
+ accountNumber: string;
84
+ from: string;
85
+ to: string;
86
+ direction?: number;
87
+ }): Promise<BarobillPage<XmlNode>>;
88
+ /** The cards registered with Barobill for collection. */
89
+ cards(): Promise<XmlNode[]>;
90
+ /** A card's approvals and cancels between two days (YYYYMMDD), both included. */
91
+ cardApprovals(query: {
92
+ userId: string;
93
+ cardNumber: string;
94
+ from: string;
95
+ to: string;
96
+ }): Promise<BarobillPage<XmlNode>>;
97
+ /** The company's sales or purchase tax invoices between two days (YYYYMMDD), every tax type unless one is given. */
98
+ taxInvoices(query: {
99
+ side: 'sales' | 'purchase';
100
+ userId: string;
101
+ from: string;
102
+ to: string;
103
+ dateType?: number;
104
+ taxType?: number;
105
+ }): Promise<BarobillPage<XmlNode>>;
106
+ }
@@ -0,0 +1,180 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BarobillClient = exports.digitsOnly = exports.BarobillError = exports.QUERY_CODES = exports.READ_OPERATIONS = exports.BAROBILL_ORIGINS = void 0;
4
+ const soap_xml_1 = require("./soap-xml");
5
+ /**
6
+ * Barobill's web services (SOAP 1.1 over HTTPS), read only.
7
+ *
8
+ * - Every call takes the partner key (CERTKEY) and the member's business number (CorpNum, digits only).
9
+ * - A failure is a negative number where the answer would be: the int result itself, `CurrentPage` of a paged list, or
10
+ * the number field of a list's only item (`BankAccountNum`, `CardNum` - seen on the test server 2026-11-14).
11
+ * `GetErrString` words it.
12
+ * - Only the operations in `READ_OPERATIONS` can be called. Registering accounts or cards, issuing invoices and the
13
+ * rest are Barobill's own screens - this client cannot send them, whatever a task or a script asks.
14
+ */
15
+ exports.BAROBILL_ORIGINS = {
16
+ test: 'https://testws.baroservice.com',
17
+ production: 'https://ws.baroservice.com'
18
+ };
19
+ exports.READ_OPERATIONS = {
20
+ BANKACCOUNT: ['CheckCERTIsValid', 'GetErrString', 'GetBankAccountEx2', 'GetPeriodBankAccountLogEx2'],
21
+ CARD: ['CheckCERTIsValid', 'GetErrString', 'GetCardEx2', 'GetPeriodCardApprovalLog'],
22
+ TI: ['CheckCERTIsValid', 'GetErrString', 'GetPeriodTaxInvoiceSalesListEx', 'GetPeriodTaxInvoicePurchaseListEx']
23
+ };
24
+ /**
25
+ * The query codes Barobill's period lists take. Read from the manual's wording; the probe (`npm run probe`) prints what
26
+ * each answers on the test server, and these are corrected there if it says otherwise.
27
+ */
28
+ exports.QUERY_CODES = {
29
+ /** GetPeriodBankAccountLogEx2 TransDirection */
30
+ bankDirection: { all: 1, deposit: 2, withdrawal: 3 },
31
+ /** OrderDirection of the period lists */
32
+ order: { oldestFirst: 1, newestFirst: 2 },
33
+ /** GetPeriodTaxInvoice*ListEx DateType */
34
+ invoiceDate: { written: 1, issued: 2, sent: 3 },
35
+ /**
36
+ * GetPeriodTaxInvoice*ListEx TaxType. The test server takes 1 and 3 and refuses 0, 2 and 4 (-11010, 2026-11-14) -
37
+ * there is no 'every kind', so a period is asked once for each.
38
+ */
39
+ invoiceTax: [1, 3]
40
+ };
41
+ const PAGE = 100;
42
+ /** Barobill answers a period list in pages; past this many something is wrong with the period, not the company. */
43
+ const PAGE_LIMIT = 200;
44
+ class BarobillError extends Error {
45
+ constructor(operation, code, text) {
46
+ super(`Barobill ${operation} failed (${code}${text ? ` ${text}` : ''})`);
47
+ this.code = code;
48
+ this.operation = operation;
49
+ }
50
+ }
51
+ exports.BarobillError = BarobillError;
52
+ const digitsOnly = (value) => String(value ?? '').replace(/\D/g, '');
53
+ exports.digitsOnly = digitsOnly;
54
+ class BarobillClient {
55
+ constructor(options) {
56
+ const certKey = String(options.certKey ?? '').trim();
57
+ if (!certKey)
58
+ throw new Error('the Barobill connection has no partner key (CERTKEY)');
59
+ const corpNum = (0, exports.digitsOnly)(options.corpNum);
60
+ if (corpNum.length !== 10)
61
+ throw new Error(`the Barobill business number must be 10 digits (it has ${corpNum.length})`);
62
+ const server = String(options.server ?? '').trim() || 'test';
63
+ this.origin = server in exports.BAROBILL_ORIGINS ? exports.BAROBILL_ORIGINS[server] : server.replace(/\/+$/, '');
64
+ if (!/^https?:\/\/[^\s/]+$/.test(this.origin))
65
+ throw new Error(`'${server}' is neither test, production nor an origin`);
66
+ this.certKey = certKey;
67
+ this.corpNum = corpNum;
68
+ }
69
+ /** The body's `<operation>Result`. Only a read operation is sent. */
70
+ async call(service, operation, args = {}) {
71
+ if (!exports.READ_OPERATIONS[service].includes(operation))
72
+ throw new Error(`Barobill ${service}.${operation} is not a read this client sends`);
73
+ const response = await fetch(`${this.origin}/${service}.asmx`, {
74
+ method: 'POST',
75
+ headers: { 'Content-Type': 'text/xml; charset=utf-8', SOAPAction: `"${soap_xml_1.BAROBILL_NAMESPACE}${operation}"` },
76
+ body: (0, soap_xml_1.soapEnvelope)(operation, { CERTKEY: this.certKey, ...(operation === 'GetErrString' ? {} : { CorpNum: this.corpNum }), ...args })
77
+ });
78
+ const text = await response.text();
79
+ let document;
80
+ try {
81
+ document = (0, soap_xml_1.readXml)(text);
82
+ }
83
+ catch {
84
+ throw new Error(`Barobill ${operation} answered HTTP ${response.status} with no SOAP document`);
85
+ }
86
+ const body = (0, soap_xml_1.at)(document, 'Envelope', 'Body');
87
+ const fault = (0, soap_xml_1.at)(body, 'Fault');
88
+ if (fault)
89
+ throw new Error(`Barobill ${operation} fault: ${(0, soap_xml_1.textOf)((0, soap_xml_1.at)(fault, 'faultstring')) || (0, soap_xml_1.textOf)((0, soap_xml_1.at)(fault, 'faultcode'))}`);
90
+ if (!response.ok)
91
+ throw new Error(`Barobill ${operation} answered HTTP ${response.status}`);
92
+ return (0, soap_xml_1.at)(body, `${operation}Response`, `${operation}Result`);
93
+ }
94
+ /** Barobill's words for a failure code; '' when it has none. */
95
+ async errorText(service, code) {
96
+ try {
97
+ const text = (0, soap_xml_1.textOf)(await this.call(service, 'GetErrString', { ErrCode: code }));
98
+ /* With a key Barobill does not know, it answers the code itself. */
99
+ return text === String(code) ? '' : text;
100
+ }
101
+ catch {
102
+ return '';
103
+ }
104
+ }
105
+ async refuse(service, operation, code) {
106
+ throw new BarobillError(operation, code, await this.errorText(service, code));
107
+ }
108
+ /** 1 when the key and the business number are good together; a negative code says why not. */
109
+ async checkKey(service = 'BANKACCOUNT') {
110
+ return Number((0, soap_xml_1.textOf)(await this.call(service, 'CheckCERTIsValid')));
111
+ }
112
+ /** Every page of a period list, oldest first. */
113
+ async allPages(service, operation, args, listName, itemName) {
114
+ const items = [];
115
+ let total = 0;
116
+ for (let page = 1; page <= PAGE_LIMIT; page++) {
117
+ const result = await this.call(service, operation, { ...args, CountPerPage: PAGE, CurrentPage: page });
118
+ const current = Number((0, soap_xml_1.textOf)((0, soap_xml_1.at)(result, 'CurrentPage')));
119
+ if (!Number.isFinite(current))
120
+ throw new Error(`Barobill ${operation} answered no page`);
121
+ if (current < 0)
122
+ await this.refuse(service, operation, current);
123
+ total = Number((0, soap_xml_1.textOf)((0, soap_xml_1.at)(result, 'MaxIndex'))) || 0;
124
+ items.push(...(0, soap_xml_1.listOf)((0, soap_xml_1.at)(result, listName, itemName)));
125
+ const last = Number((0, soap_xml_1.textOf)((0, soap_xml_1.at)(result, 'MaxPageNum'))) || 0;
126
+ if (page >= last)
127
+ return { items, total };
128
+ }
129
+ throw new Error(`Barobill ${operation} has more than ${PAGE_LIMIT} pages - ask for a shorter period`);
130
+ }
131
+ /** A list of what is registered; its only item carrying a negative number in `numberField` is the failure. */
132
+ async registered(service, operation, itemName, numberField) {
133
+ const items = (0, soap_xml_1.listOf)((0, soap_xml_1.at)(await this.call(service, operation, { AvailOnly: 1 }), itemName));
134
+ const code = items.length === 1 ? (0, soap_xml_1.textOf)(items[0][numberField]) : '';
135
+ if (/^-\d+$/.test(code))
136
+ await this.refuse(service, operation, Number(code));
137
+ return items;
138
+ }
139
+ /** The accounts registered with Barobill for collection. */
140
+ async bankAccounts() {
141
+ return this.registered('BANKACCOUNT', 'GetBankAccountEx2', 'BankAccountEx', 'BankAccountNum');
142
+ }
143
+ /** An account's lines between two days (YYYYMMDD), both included. */
144
+ async bankLines(query) {
145
+ return this.allPages('BANKACCOUNT', 'GetPeriodBankAccountLogEx2', {
146
+ ID: query.userId,
147
+ BankAccountNum: (0, exports.digitsOnly)(query.accountNumber),
148
+ StartDate: query.from,
149
+ EndDate: query.to,
150
+ TransDirection: query.direction ?? exports.QUERY_CODES.bankDirection.all,
151
+ OrderDirection: exports.QUERY_CODES.order.oldestFirst
152
+ }, 'BankAccountLogList', 'BankAccountLogEx2');
153
+ }
154
+ /** The cards registered with Barobill for collection. */
155
+ async cards() {
156
+ return this.registered('CARD', 'GetCardEx2', 'CardEx', 'CardNum');
157
+ }
158
+ /** A card's approvals and cancels between two days (YYYYMMDD), both included. */
159
+ async cardApprovals(query) {
160
+ return this.allPages('CARD', 'GetPeriodCardApprovalLog', { ID: query.userId, CardNum: (0, exports.digitsOnly)(query.cardNumber), StartDate: query.from, EndDate: query.to, OrderDirection: exports.QUERY_CODES.order.oldestFirst }, 'CardLogList', 'CardApprovalLog');
161
+ }
162
+ /** The company's sales or purchase tax invoices between two days (YYYYMMDD), every tax type unless one is given. */
163
+ async taxInvoices(query) {
164
+ if (query.taxType === undefined) {
165
+ const pages = [];
166
+ for (const taxType of exports.QUERY_CODES.invoiceTax)
167
+ pages.push(await this.taxInvoices({ ...query, taxType }));
168
+ return { items: pages.flatMap(page => page.items), total: pages.reduce((sum, page) => sum + page.total, 0) };
169
+ }
170
+ return this.allPages('TI', query.side === 'sales' ? 'GetPeriodTaxInvoiceSalesListEx' : 'GetPeriodTaxInvoicePurchaseListEx', {
171
+ UserID: query.userId,
172
+ TaxType: query.taxType,
173
+ DateType: query.dateType ?? exports.QUERY_CODES.invoiceDate.written,
174
+ StartDate: query.from,
175
+ EndDate: query.to
176
+ }, 'SimpleTaxInvoiceEx2List', 'SimpleTaxInvoiceEx2');
177
+ }
178
+ }
179
+ exports.BarobillClient = BarobillClient;
180
+ //# sourceMappingURL=barobill-client.js.map
@@ -0,0 +1,36 @@
1
+ import { Connector } from '@things-factory/integration-base';
2
+ import { BarobillClient } from './barobill-client';
3
+ /**
4
+ * Barobill (바로빌) - one connection per company: the partner key (CERTKEY), the company's business number and its
5
+ * Barobill user id. The bank, card company and hometax logins are registered on Barobill's own screens, never here
6
+ * (ADR-0204 decision 1). `server` is test or production; an `endpoint` given on the connection replaces either (a mock).
7
+ * Every parameter is a domain attribute: the Settings screen's Barobill card writes them for the connection named
8
+ * `barobill` (`BAROBILL_CONNECTION`), so the key is kept in one place.
9
+ */
10
+ export interface BarobillConnectionInstance {
11
+ client: BarobillClient;
12
+ userId: string;
13
+ }
14
+ export declare class BarobillConnector implements Connector {
15
+ ready(connectionConfigs: any): Promise<void>;
16
+ connect(connection: any): Promise<void>;
17
+ disconnect(connection: any): Promise<void>;
18
+ get parameterSpec(): ({
19
+ type: string;
20
+ name: string;
21
+ label: string;
22
+ useDomainAttribute: boolean;
23
+ property?: undefined;
24
+ } | {
25
+ type: string;
26
+ name: string;
27
+ label: string;
28
+ property: {
29
+ options: string[];
30
+ };
31
+ useDomainAttribute: boolean;
32
+ })[];
33
+ get taskPrefixes(): string[];
34
+ get help(): string;
35
+ get description(): string;
36
+ }
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BarobillConnector = void 0;
4
+ const integration_base_1 = require("@things-factory/integration-base");
5
+ const barobill_client_1 = require("./barobill-client");
6
+ class BarobillConnector {
7
+ async ready(connectionConfigs) {
8
+ await Promise.all(connectionConfigs.map(this.connect.bind(this)));
9
+ integration_base_1.ConnectionManager.logger.info('barobill-connector connections are ready');
10
+ }
11
+ async connect(connection) {
12
+ const { endpoint, params = {} } = connection;
13
+ try {
14
+ const client = new barobill_client_1.BarobillClient({ certKey: params.certKey, corpNum: params.corpNum, server: endpoint || params.server || 'test' });
15
+ const userId = String(params.userId ?? '').trim();
16
+ if (!userId)
17
+ throw new Error('the Barobill connection has no Barobill user id');
18
+ const instance = { client, userId };
19
+ integration_base_1.ConnectionManager.addConnectionInstance(connection, instance);
20
+ integration_base_1.ConnectionManager.logger.info(`barobill-connector connection(${connection.name}) is connected (${client.origin})`);
21
+ }
22
+ catch (ex) {
23
+ integration_base_1.ConnectionManager.logger.error(`barobill-connector connection(${connection.name}) failed`, ex);
24
+ throw ex;
25
+ }
26
+ }
27
+ async disconnect(connection) {
28
+ integration_base_1.ConnectionManager.removeConnectionInstance(connection);
29
+ integration_base_1.ConnectionManager.logger.info(`barobill-connector connection(${connection.name}) is disconnected`);
30
+ }
31
+ get parameterSpec() {
32
+ return [
33
+ { type: 'secret', name: 'certKey', label: 'barobill-cert-key', useDomainAttribute: true },
34
+ { type: 'string', name: 'corpNum', label: 'barobill-corp-num', useDomainAttribute: true },
35
+ { type: 'string', name: 'userId', label: 'barobill-user-id', useDomainAttribute: true },
36
+ { type: 'select', name: 'server', label: 'barobill-server', property: { options: ['test', 'production'] }, useDomainAttribute: true }
37
+ ];
38
+ }
39
+ get taskPrefixes() {
40
+ return ['barobill'];
41
+ }
42
+ get help() {
43
+ return 'integration/connector/barobill-connector';
44
+ }
45
+ get description() {
46
+ return 'Barobill Connector - bank lines, card approvals and tax invoices, read only';
47
+ }
48
+ }
49
+ exports.BarobillConnector = BarobillConnector;
50
+ integration_base_1.ConnectionManager.registerConnector('barobill-connector', new BarobillConnector());
51
+ //# sourceMappingURL=barobill-connector.js.map
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The little of SOAP 1.1 Barobill needs: an envelope with flat string arguments out, and the body's answer read back as
3
+ * plain values. Barobill answers are elements of text or of elements - no attributes we read, no mixed content - so a
4
+ * small reader does, and the module carries no XML library.
5
+ */
6
+ export type XmlValue = string | XmlNode;
7
+ export interface XmlNode {
8
+ [name: string]: XmlValue | XmlValue[];
9
+ }
10
+ export declare const BAROBILL_NAMESPACE = "http://ws.baroservice.com/";
11
+ /** The envelope calling `operation` with `args` in their given order (the service reads them by name; order is kept for the eye). */
12
+ export declare function soapEnvelope(operation: string, args: Record<string, string | number | boolean | null | undefined>): string;
13
+ /**
14
+ * The document as nested values: an element with children is a node, one without is its text. A name that repeats
15
+ * under one parent becomes a list in document order.
16
+ */
17
+ export declare function readXml(xml: string): XmlNode;
18
+ /** The node at a path of local names, or undefined. */
19
+ export declare function at(node: XmlValue | XmlValue[] | undefined, ...path: string[]): XmlValue | XmlValue[] | undefined;
20
+ /** A value that may be one or many, as a list ('' - an empty element - is none). */
21
+ export declare const listOf: <T extends XmlValue>(value: T | T[] | undefined) => T[];
22
+ /** The text of a leaf, '' for an absent or empty one. */
23
+ export declare const textOf: (value: XmlValue | XmlValue[] | undefined) => string;
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ /**
3
+ * The little of SOAP 1.1 Barobill needs: an envelope with flat string arguments out, and the body's answer read back as
4
+ * plain values. Barobill answers are elements of text or of elements - no attributes we read, no mixed content - so a
5
+ * small reader does, and the module carries no XML library.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.textOf = exports.listOf = exports.BAROBILL_NAMESPACE = void 0;
9
+ exports.soapEnvelope = soapEnvelope;
10
+ exports.readXml = readXml;
11
+ exports.at = at;
12
+ exports.BAROBILL_NAMESPACE = 'http://ws.baroservice.com/';
13
+ const escape = (value) => value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
14
+ const unescape = (value) => value
15
+ .replace(/&lt;/g, '<')
16
+ .replace(/&gt;/g, '>')
17
+ .replace(/&quot;/g, '"')
18
+ .replace(/&apos;/g, "'")
19
+ .replace(/&#x([0-9a-fA-F]+);/g, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))
20
+ .replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec)))
21
+ .replace(/&amp;/g, '&');
22
+ /** The envelope calling `operation` with `args` in their given order (the service reads them by name; order is kept for the eye). */
23
+ function soapEnvelope(operation, args) {
24
+ const body = Object.entries(args)
25
+ .map(([name, value]) => `<${name}>${value === null || value === undefined ? '' : escape(String(value))}</${name}>`)
26
+ .join('');
27
+ return ('<?xml version="1.0" encoding="utf-8"?>' +
28
+ '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
29
+ `<soap:Body><${operation} xmlns="${exports.BAROBILL_NAMESPACE}">${body}</${operation}></soap:Body>` +
30
+ '</soap:Envelope>');
31
+ }
32
+ const localName = (tag) => tag.slice(tag.indexOf(':') + 1);
33
+ /**
34
+ * The document as nested values: an element with children is a node, one without is its text. A name that repeats
35
+ * under one parent becomes a list in document order.
36
+ */
37
+ function readXml(xml) {
38
+ const root = {};
39
+ const stack = [{ name: '', node: root, text: '', hasChildren: true }];
40
+ const pattern = /<!\[CDATA\[([\s\S]*?)\]\]>|<(\/?)([A-Za-z_][\w.:-]*)((?:\s+[^\s=>/]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>|<\?[\s\S]*?\?>|<!--[\s\S]*?-->|([^<]+)/g;
41
+ let match;
42
+ const add = (parent, name, value) => {
43
+ const before = parent[name];
44
+ if (before === undefined)
45
+ parent[name] = value;
46
+ else if (Array.isArray(before))
47
+ before.push(value);
48
+ else
49
+ parent[name] = [before, value];
50
+ };
51
+ while ((match = pattern.exec(xml))) {
52
+ const [, cdata, closing, tag, , selfClosing, text] = match;
53
+ const top = stack[stack.length - 1];
54
+ if (cdata !== undefined)
55
+ top.text += cdata;
56
+ else if (text !== undefined)
57
+ top.text += unescape(text);
58
+ else if (!tag)
59
+ continue;
60
+ else if (closing) {
61
+ const done = stack.pop();
62
+ if (!done || done.name !== localName(tag))
63
+ throw new Error(`malformed XML: </${tag}> closes <${done?.name ?? ''}>`);
64
+ add(stack[stack.length - 1].node, done.name, done.hasChildren ? done.node : done.text.trim());
65
+ }
66
+ else {
67
+ top.hasChildren = true;
68
+ if (selfClosing)
69
+ add(top.node, localName(tag), '');
70
+ else
71
+ stack.push({ name: localName(tag), node: {}, text: '', hasChildren: false });
72
+ }
73
+ }
74
+ if (stack.length !== 1)
75
+ throw new Error(`malformed XML: <${stack[stack.length - 1].name}> is not closed`);
76
+ return root;
77
+ }
78
+ /** The node at a path of local names, or undefined. */
79
+ function at(node, ...path) {
80
+ let here = node;
81
+ for (const name of path) {
82
+ if (here === undefined || typeof here === 'string' || Array.isArray(here))
83
+ return undefined;
84
+ here = here[name];
85
+ }
86
+ return here;
87
+ }
88
+ /** A value that may be one or many, as a list ('' - an empty element - is none). */
89
+ const listOf = (value) => value === undefined || value === '' ? [] : Array.isArray(value) ? value : [value];
90
+ exports.listOf = listOf;
91
+ /** The text of a leaf, '' for an absent or empty one. */
92
+ const textOf = (value) => (typeof value === 'string' ? value : '');
93
+ exports.textOf = textOf;
94
+ //# sourceMappingURL=soap-xml.js.map
@@ -0,0 +1,2 @@
1
+ import './connector/barobill-connector';
2
+ import './task';
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ require("./connector/barobill-connector");
4
+ require("./task");
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Barobill's bank account lines (`BankAccountLogEx2`) as the books take a bank line - the shape a statement file's line
3
+ * has once read (accounting `parseBankRows`), so both come in through one function (ADR-0204 decision 2). Nothing here
4
+ * knows the books: the account is said by its number and the line by what the bank printed.
5
+ */
6
+ export interface StatementLine {
7
+ /** The order the bank gave the lines in, oldest first - it settles two lines of one second. */
8
+ bankSequence: number;
9
+ currency: string;
10
+ /** The time as the bank printed it, 'YYYY-MM-DD HH:mm:ss' ('YYYY-MM-DD' when it printed none). */
11
+ bankLocalTime: string;
12
+ type: 'INCOME' | 'EXPENSE';
13
+ amount: number;
14
+ balance: number;
15
+ bankDescription: string | null;
16
+ bankKind: string | null;
17
+ bankCounterpartyName: string | null;
18
+ bankCounterpartyAccount: string | null;
19
+ bankCounterpartyBank: string | null;
20
+ bankMemo: string | null;
21
+ /** The branch that handled the line. */
22
+ bankOffice: string | null;
23
+ /** What the collector calls the line, kept for tracing a line back to it. */
24
+ collectorKey: string | null;
25
+ /** The remarks a person kept on the line at the collector. */
26
+ collectorRemark1: string | null;
27
+ collectorRemark2: string | null;
28
+ }
29
+ export interface StatementLines {
30
+ accountNumber: string;
31
+ /** The days asked for, YYYY-MM-DD - lines outside them are not the collector's to say. */
32
+ periodStart: string;
33
+ periodEnd: string;
34
+ lines: StatementLine[];
35
+ }
36
+ /** A Barobill money value ('' for none) as a number; anything but a number is refused, never read as zero by mistake. */
37
+ export declare function moneyOf(value: unknown, what: string): number;
38
+ /** 'YYYYMMDDHHmmss' (or 'YYYYMMDD') as the bank's local 'YYYY-MM-DD HH:mm:ss' ('YYYY-MM-DD'). */
39
+ export declare function localTimeOf(value: unknown, what: string): string;
40
+ /** 'YYYYMMDD' as 'YYYY-MM-DD'. */
41
+ export declare const dayOf: (yyyymmdd: string) => string;
42
+ /**
43
+ * The lines of one account. A line that moved nothing is left out; one that says both a deposit and a withdrawal, or
44
+ * belongs to another account, is refused - the answer is not what the account's lines are.
45
+ */
46
+ export declare function bankLinesOf(accountNumber: string, items: readonly Record<string, any>[], period: {
47
+ from: string;
48
+ to: string;
49
+ }, currency?: string): StatementLines;
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ /**
3
+ * Barobill's bank account lines (`BankAccountLogEx2`) as the books take a bank line - the shape a statement file's line
4
+ * has once read (accounting `parseBankRows`), so both come in through one function (ADR-0204 decision 2). Nothing here
5
+ * knows the books: the account is said by its number and the line by what the bank printed.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.dayOf = void 0;
9
+ exports.moneyOf = moneyOf;
10
+ exports.localTimeOf = localTimeOf;
11
+ exports.bankLinesOf = bankLinesOf;
12
+ const text = (value) => {
13
+ const one = typeof value === 'string' ? value.trim() : '';
14
+ return one ? one : null;
15
+ };
16
+ /** A Barobill money value ('' for none) as a number; anything but a number is refused, never read as zero by mistake. */
17
+ function moneyOf(value, what) {
18
+ const raw = typeof value === 'string' ? value.replace(/,/g, '').trim() : '';
19
+ if (raw === '')
20
+ return 0;
21
+ const amount = Number(raw);
22
+ if (!Number.isFinite(amount))
23
+ throw new Error(`Barobill ${what} '${raw}' is not an amount`);
24
+ return amount;
25
+ }
26
+ /** 'YYYYMMDDHHmmss' (or 'YYYYMMDD') as the bank's local 'YYYY-MM-DD HH:mm:ss' ('YYYY-MM-DD'). */
27
+ function localTimeOf(value, what) {
28
+ const raw = typeof value === 'string' ? value.trim() : '';
29
+ const match = /^(\d{4})(\d{2})(\d{2})(?:(\d{2})(\d{2})(\d{2}))?$/.exec(raw);
30
+ if (!match)
31
+ throw new Error(`Barobill ${what} '${raw}' is not a time`);
32
+ const [, y, m, d, h, min, s] = match;
33
+ return h === undefined ? `${y}-${m}-${d}` : `${y}-${m}-${d} ${h}:${min}:${s}`;
34
+ }
35
+ /** 'YYYYMMDD' as 'YYYY-MM-DD'. */
36
+ const dayOf = (yyyymmdd) => `${yyyymmdd.slice(0, 4)}-${yyyymmdd.slice(4, 6)}-${yyyymmdd.slice(6, 8)}`;
37
+ exports.dayOf = dayOf;
38
+ /**
39
+ * The lines of one account. A line that moved nothing is left out; one that says both a deposit and a withdrawal, or
40
+ * belongs to another account, is refused - the answer is not what the account's lines are.
41
+ */
42
+ function bankLinesOf(accountNumber, items, period, currency = 'KRW') {
43
+ const account = String(accountNumber).replace(/\D/g, '');
44
+ const lines = [];
45
+ items.forEach((item, index) => {
46
+ const own = String(item.BankAccountNum ?? '').replace(/\D/g, '');
47
+ if (own && own !== account)
48
+ throw new Error(`Barobill answered a line of account ${own} for account ${account}`);
49
+ const deposit = moneyOf(item.Deposit, 'deposit');
50
+ const withdrawal = moneyOf(item.Withdraw, 'withdrawal');
51
+ if (deposit < 0 || withdrawal < 0 || (deposit && withdrawal))
52
+ throw new Error(`Barobill line ${index + 1} of ${account} says deposit ${deposit} and withdrawal ${withdrawal}`);
53
+ if (!deposit && !withdrawal)
54
+ return;
55
+ const remark = text(item.TransRemark);
56
+ lines.push({
57
+ bankSequence: index + 1,
58
+ currency,
59
+ bankLocalTime: localTimeOf(item.TransDT, 'transaction time'),
60
+ type: deposit ? 'INCOME' : 'EXPENSE',
61
+ amount: deposit || withdrawal,
62
+ balance: moneyOf(item.Balance, 'balance'),
63
+ bankDescription: remark,
64
+ bankKind: text(item.TransType),
65
+ bankCounterpartyName: remark,
66
+ bankCounterpartyAccount: null,
67
+ bankCounterpartyBank: null,
68
+ bankMemo: text(item.Memo),
69
+ bankOffice: text(item.TransOffice),
70
+ collectorKey: text(item.TransRefKey),
71
+ collectorRemark1: text(item.MgtRemark1),
72
+ collectorRemark2: text(item.MgtRemark2)
73
+ });
74
+ });
75
+ return { accountNumber: account, periodStart: (0, exports.dayOf)(period.from), periodEnd: (0, exports.dayOf)(period.to), lines };
76
+ }
77
+ //# sourceMappingURL=bank-lines.js.map