@serge-pro-dev/payload-payment-yookassa 0.0.0-stage → 0.1.0-beta.0
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.
- package/LICENSE +21 -0
- package/README.md +146 -2
- package/README.ru.md +148 -0
- package/dist/amount.d.ts +11 -0
- package/dist/amount.js +29 -0
- package/dist/amount.js.map +1 -0
- package/dist/api.d.ts +51 -0
- package/dist/api.js +58 -0
- package/dist/api.js.map +1 -0
- package/dist/client.d.ts +49 -0
- package/dist/client.js +61 -0
- package/dist/client.js.map +1 -0
- package/dist/confirm.d.ts +4 -0
- package/dist/confirm.js +95 -0
- package/dist/confirm.js.map +1 -0
- package/dist/fields.d.ts +13 -0
- package/dist/fields.js +68 -0
- package/dist/fields.js.map +1 -0
- package/dist/finalize.d.ts +45 -0
- package/dist/finalize.js +207 -0
- package/dist/finalize.js.map +1 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.js +164 -0
- package/dist/index.js.map +1 -0
- package/dist/initiate.d.ts +3 -0
- package/dist/initiate.js +221 -0
- package/dist/initiate.js.map +1 -0
- package/dist/messages.d.ts +3 -0
- package/dist/messages.js +77 -0
- package/dist/messages.js.map +1 -0
- package/dist/receipt.d.ts +57 -0
- package/dist/receipt.js +43 -0
- package/dist/receipt.js.map +1 -0
- package/dist/reconcile.d.ts +35 -0
- package/dist/reconcile.js +125 -0
- package/dist/reconcile.js.map +1 -0
- package/dist/settings.d.ts +29 -0
- package/dist/settings.js +207 -0
- package/dist/settings.js.map +1 -0
- package/dist/settlement.d.ts +25 -0
- package/dist/settlement.js +62 -0
- package/dist/settlement.js.map +1 -0
- package/dist/status.d.ts +13 -0
- package/dist/status.js +92 -0
- package/dist/status.js.map +1 -0
- package/dist/types.d.ts +84 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/dist/utils.d.ts +8 -0
- package/dist/utils.js +25 -0
- package/dist/utils.js.map +1 -0
- package/dist/webhooks.d.ts +16 -0
- package/dist/webhooks.js +83 -0
- package/dist/webhooks.js.map +1 -0
- package/package.json +54 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/receipt.ts"],"sourcesContent":["import { formatAmount } from './amount.js'\n\nexport type TaxSystemCode = 1 | 2 | 3 | 4 | 5 | 6\n\nexport type ReceiptOptions = {\n /**\n * Tax system of the shop (1 general, 2 USN income, 3 USN income-expenses,\n * 4 ENVD, 5 ESN, 6 patent). Send it only when the shop has several tax systems.\n */\n taxSystemCode?: TaxSystemCode\n /** VAT code used when a product has none. 1 = without VAT. Default 1. */\n defaultVatCode?: number\n /** Default \"commodity\". */\n paymentSubject?: string\n /** Default \"full_payment\". */\n paymentMode?: string\n /** VAT code of the delivery line. Default: `defaultVatCode`. */\n deliveryVatCode?: number\n}\n\n/** One purchased line. `unitAmount` is in minor units. */\nexport type OrderLine = {\n description: string\n quantity: number\n unitAmount: number\n vatCode?: number\n /** Overrides the subject of payment for this line (the delivery is a \"service\"). */\n paymentSubject?: string\n}\n\nconst MAX_DESCRIPTION_LENGTH = 128\n\nexport const isVatCode = (value: unknown): value is number =>\n typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= 12\n\nexport const sumLines = (lines: OrderLine[]): number =>\n lines.reduce((total, line) => total + line.unitAmount * line.quantity, 0)\n\nexport const truncate = (value: string, max: number): string =>\n value.length <= max ? value : `${value.slice(0, max - 1)}…`\n\ntype BuildReceiptArgs = {\n lines: OrderLine[]\n currency: string\n decimals?: number\n customerEmail: string\n options: ReceiptOptions\n}\n\n/**\n * Builds the `receipt` object of a YooKassa payment. The sum of all lines is the\n * payment amount, so the caller must compute the payment amount from the same lines.\n */\nexport const buildReceipt = ({\n lines,\n currency,\n decimals = 2,\n customerEmail,\n options,\n}: BuildReceiptArgs) => {\n if (lines.length === 0) throw new Error('Receipt needs at least one item')\n\n if (lines.length > 100) throw new Error('A receipt cannot have more than 100 items')\n\n const defaultVatCode = options.defaultVatCode ?? 1\n\n if (!isVatCode(defaultVatCode)) throw new Error('defaultVatCode must be an integer from 1 to 12')\n\n return {\n customer: { email: customerEmail },\n items: lines.map((line) => {\n if (!Number.isInteger(line.quantity) || line.quantity < 1) {\n throw new Error('Receipt item quantity must be a positive integer')\n }\n\n if (!Number.isSafeInteger(line.unitAmount) || line.unitAmount < 1) {\n throw new Error('Receipt item price must be a positive amount')\n }\n\n return {\n description: truncate(line.description, MAX_DESCRIPTION_LENGTH),\n quantity: line.quantity,\n amount: { value: formatAmount(line.unitAmount, decimals), currency },\n vat_code: isVatCode(line.vatCode) ? line.vatCode : defaultVatCode,\n payment_mode: options.paymentMode ?? 'full_payment',\n payment_subject: line.paymentSubject ?? options.paymentSubject ?? 'commodity',\n }\n }),\n ...(options.taxSystemCode ? { tax_system_code: options.taxSystemCode } : {}),\n }\n}\n"],"names":["formatAmount","MAX_DESCRIPTION_LENGTH","isVatCode","value","Number","isInteger","sumLines","lines","reduce","total","line","unitAmount","quantity","truncate","max","length","slice","buildReceipt","currency","decimals","customerEmail","options","Error","defaultVatCode","customer","email","items","map","isSafeInteger","description","amount","vat_code","vatCode","payment_mode","paymentMode","payment_subject","paymentSubject","taxSystemCode","tax_system_code"],"mappings":"AAAA,SAASA,YAAY,QAAQ,cAAa;AA8B1C,MAAMC,yBAAyB;AAE/B,OAAO,MAAMC,YAAY,CAACC,QACxB,OAAOA,UAAU,YAAYC,OAAOC,SAAS,CAACF,UAAUA,SAAS,KAAKA,SAAS,GAAE;AAEnF,OAAO,MAAMG,WAAW,CAACC,QACvBA,MAAMC,MAAM,CAAC,CAACC,OAAOC,OAASD,QAAQC,KAAKC,UAAU,GAAGD,KAAKE,QAAQ,EAAE,GAAE;AAE3E,OAAO,MAAMC,WAAW,CAACV,OAAeW,MACtCX,MAAMY,MAAM,IAAID,MAAMX,QAAQ,GAAGA,MAAMa,KAAK,CAAC,GAAGF,MAAM,GAAG,CAAC,CAAC,CAAA;AAU7D;;;CAGC,GACD,OAAO,MAAMG,eAAe,CAAC,EAC3BV,KAAK,EACLW,QAAQ,EACRC,WAAW,CAAC,EACZC,aAAa,EACbC,OAAO,EACU;IACjB,IAAId,MAAMQ,MAAM,KAAK,GAAG,MAAM,IAAIO,MAAM;IAExC,IAAIf,MAAMQ,MAAM,GAAG,KAAK,MAAM,IAAIO,MAAM;IAExC,MAAMC,iBAAiBF,QAAQE,cAAc,IAAI;IAEjD,IAAI,CAACrB,UAAUqB,iBAAiB,MAAM,IAAID,MAAM;IAEhD,OAAO;QACLE,UAAU;YAAEC,OAAOL;QAAc;QACjCM,OAAOnB,MAAMoB,GAAG,CAAC,CAACjB;YAChB,IAAI,CAACN,OAAOC,SAAS,CAACK,KAAKE,QAAQ,KAAKF,KAAKE,QAAQ,GAAG,GAAG;gBACzD,MAAM,IAAIU,MAAM;YAClB;YAEA,IAAI,CAAClB,OAAOwB,aAAa,CAAClB,KAAKC,UAAU,KAAKD,KAAKC,UAAU,GAAG,GAAG;gBACjE,MAAM,IAAIW,MAAM;YAClB;YAEA,OAAO;gBACLO,aAAahB,SAASH,KAAKmB,WAAW,EAAE5B;gBACxCW,UAAUF,KAAKE,QAAQ;gBACvBkB,QAAQ;oBAAE3B,OAAOH,aAAaU,KAAKC,UAAU,EAAEQ;oBAAWD;gBAAS;gBACnEa,UAAU7B,UAAUQ,KAAKsB,OAAO,IAAItB,KAAKsB,OAAO,GAAGT;gBACnDU,cAAcZ,QAAQa,WAAW,IAAI;gBACrCC,iBAAiBzB,KAAK0B,cAAc,IAAIf,QAAQe,cAAc,IAAI;YACpE;QACF;QACA,GAAIf,QAAQgB,aAAa,GAAG;YAAEC,iBAAiBjB,QAAQgB,aAAa;QAAC,IAAI,CAAC,CAAC;IAC7E;AACF,EAAC"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { TaskConfig } from 'payload';
|
|
2
|
+
import type { ResolvedConfig } from './types.js';
|
|
3
|
+
export declare const RECONCILE_TASK = "yookassaReconcile";
|
|
4
|
+
export type ReconcileOptions = {
|
|
5
|
+
/** How often the check runs (cron, 5 or 6 fields). Default every 5 minutes. */
|
|
6
|
+
cron?: string;
|
|
7
|
+
/** Payload Jobs queue. Default "default". */
|
|
8
|
+
queue?: string;
|
|
9
|
+
/** Transactions younger than this are left to the webhook and the return page. Default 10. */
|
|
10
|
+
minAgeMinutes?: number;
|
|
11
|
+
/** Most transactions checked in one run. Default 50. */
|
|
12
|
+
limit?: number;
|
|
13
|
+
/** Default "transactions". */
|
|
14
|
+
transactionsSlug?: string;
|
|
15
|
+
};
|
|
16
|
+
type ReconcileTask = TaskConfig<{
|
|
17
|
+
input: Record<string, unknown>;
|
|
18
|
+
output: {
|
|
19
|
+
checked: number;
|
|
20
|
+
settled: number;
|
|
21
|
+
cancelled: number;
|
|
22
|
+
failed: number;
|
|
23
|
+
};
|
|
24
|
+
}>;
|
|
25
|
+
/**
|
|
26
|
+
* Safety net for missed notifications. Takes the transactions that are still `pending` after
|
|
27
|
+
* `minAgeMinutes`, asks YooKassa for each payment and brings the transaction in line: creates
|
|
28
|
+
* the order of a paid payment, cancels the transaction of a canceled one. Safe to run together
|
|
29
|
+
* with the webhook and the return page (the order is claimed atomically).
|
|
30
|
+
*
|
|
31
|
+
* A payment the buyer has not paid yet is left alone: YooKassa cancels it by itself after its
|
|
32
|
+
* payment timeout and the transaction is cancelled on the next run.
|
|
33
|
+
*/
|
|
34
|
+
export declare const reconcileTask: (config: ResolvedConfig, options?: ReconcileOptions) => ReconcileTask;
|
|
35
|
+
export {};
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { DEFAULT_QUEUE } from '@serge-pro-dev/payload-plugins-shared/delivery';
|
|
2
|
+
import { applyPayment } from './finalize.js';
|
|
3
|
+
import { isRecord } from './utils.js';
|
|
4
|
+
export const RECONCILE_TASK = 'yookassaReconcile';
|
|
5
|
+
/**
|
|
6
|
+
* Safety net for missed notifications. Takes the transactions that are still `pending` after
|
|
7
|
+
* `minAgeMinutes`, asks YooKassa for each payment and brings the transaction in line: creates
|
|
8
|
+
* the order of a paid payment, cancels the transaction of a canceled one. Safe to run together
|
|
9
|
+
* with the webhook and the return page (the order is claimed atomically).
|
|
10
|
+
*
|
|
11
|
+
* A payment the buyer has not paid yet is left alone: YooKassa cancels it by itself after its
|
|
12
|
+
* payment timeout and the transaction is cancelled on the next run.
|
|
13
|
+
*/ export const reconcileTask = (config, options = {})=>{
|
|
14
|
+
const transactionsSlug = options.transactionsSlug ?? 'transactions';
|
|
15
|
+
const minAgeMinutes = options.minAgeMinutes ?? 10;
|
|
16
|
+
const limit = options.limit ?? 50;
|
|
17
|
+
return {
|
|
18
|
+
slug: RECONCILE_TASK,
|
|
19
|
+
label: 'YooKassa: check unpaid transactions',
|
|
20
|
+
inputSchema: [],
|
|
21
|
+
outputSchema: [
|
|
22
|
+
{
|
|
23
|
+
name: 'checked',
|
|
24
|
+
type: 'number'
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
name: 'settled',
|
|
28
|
+
type: 'number'
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
name: 'cancelled',
|
|
32
|
+
type: 'number'
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
name: 'failed',
|
|
36
|
+
type: 'number'
|
|
37
|
+
}
|
|
38
|
+
],
|
|
39
|
+
// The next scheduled run is the retry.
|
|
40
|
+
retries: 0,
|
|
41
|
+
schedule: [
|
|
42
|
+
{
|
|
43
|
+
cron: options.cron ?? '*/5 * * * *',
|
|
44
|
+
queue: options.queue ?? DEFAULT_QUEUE
|
|
45
|
+
}
|
|
46
|
+
],
|
|
47
|
+
handler: async ({ req })=>{
|
|
48
|
+
const payload = req.payload;
|
|
49
|
+
const olderThan = new Date(Date.now() - minAgeMinutes * 60_000).toISOString();
|
|
50
|
+
const found = await payload.find({
|
|
51
|
+
collection: transactionsSlug,
|
|
52
|
+
depth: 0,
|
|
53
|
+
limit,
|
|
54
|
+
pagination: false,
|
|
55
|
+
overrideAccess: true,
|
|
56
|
+
sort: 'createdAt',
|
|
57
|
+
where: {
|
|
58
|
+
and: [
|
|
59
|
+
{
|
|
60
|
+
paymentMethod: {
|
|
61
|
+
equals: 'yookassa'
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
status: {
|
|
66
|
+
equals: 'pending'
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
createdAt: {
|
|
71
|
+
less_than: olderThan
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
'yookassa.paymentID': {
|
|
76
|
+
exists: true
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
]
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
let settled = 0;
|
|
83
|
+
let cancelled = 0;
|
|
84
|
+
let failed = 0;
|
|
85
|
+
for (const doc of found.docs){
|
|
86
|
+
const transaction = doc;
|
|
87
|
+
const provider = isRecord(transaction.yookassa) ? transaction.yookassa : {};
|
|
88
|
+
const paymentID = provider.paymentID;
|
|
89
|
+
if (typeof paymentID !== 'string' || !paymentID) continue;
|
|
90
|
+
try {
|
|
91
|
+
const payment = await config.client.getPayment(paymentID);
|
|
92
|
+
const result = await applyPayment({
|
|
93
|
+
config,
|
|
94
|
+
payment,
|
|
95
|
+
req,
|
|
96
|
+
transaction,
|
|
97
|
+
transactionsSlug
|
|
98
|
+
});
|
|
99
|
+
if (result === 'settled') settled += 1;
|
|
100
|
+
if (result === 'cancelled') cancelled += 1;
|
|
101
|
+
} catch (error) {
|
|
102
|
+
// One broken transaction must not stop the others.
|
|
103
|
+
failed += 1;
|
|
104
|
+
payload.logger.error({
|
|
105
|
+
err: error,
|
|
106
|
+
msg: `YooKassa reconcile: transaction ${String(transaction.id)} could not be checked`
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (settled > 0) {
|
|
111
|
+
payload.logger.warn(`YooKassa reconcile: ${settled} paid order(s) were created that the notification had missed.`);
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
output: {
|
|
115
|
+
checked: found.docs.length,
|
|
116
|
+
settled,
|
|
117
|
+
cancelled,
|
|
118
|
+
failed
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
//# sourceMappingURL=reconcile.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/reconcile.ts"],"sourcesContent":["import { DEFAULT_QUEUE } from '@serge-pro-dev/payload-plugins-shared/delivery'\nimport type { TaskConfig } from 'payload'\n\nimport { applyPayment } from './finalize.js'\nimport type { ResolvedConfig } from './types.js'\nimport { isRecord } from './utils.js'\n\nexport const RECONCILE_TASK = 'yookassaReconcile'\n\nexport type ReconcileOptions = {\n /** How often the check runs (cron, 5 or 6 fields). Default every 5 minutes. */\n cron?: string\n /** Payload Jobs queue. Default \"default\". */\n queue?: string\n /** Transactions younger than this are left to the webhook and the return page. Default 10. */\n minAgeMinutes?: number\n /** Most transactions checked in one run. Default 50. */\n limit?: number\n /** Default \"transactions\". */\n transactionsSlug?: string\n}\n\ntype ReconcileTask = TaskConfig<{\n input: Record<string, unknown>\n output: { checked: number; settled: number; cancelled: number; failed: number }\n}>\n\n/**\n * Safety net for missed notifications. Takes the transactions that are still `pending` after\n * `minAgeMinutes`, asks YooKassa for each payment and brings the transaction in line: creates\n * the order of a paid payment, cancels the transaction of a canceled one. Safe to run together\n * with the webhook and the return page (the order is claimed atomically).\n *\n * A payment the buyer has not paid yet is left alone: YooKassa cancels it by itself after its\n * payment timeout and the transaction is cancelled on the next run.\n */\nexport const reconcileTask = (config: ResolvedConfig, options: ReconcileOptions = {}): ReconcileTask => {\n const transactionsSlug = options.transactionsSlug ?? 'transactions'\n const minAgeMinutes = options.minAgeMinutes ?? 10\n const limit = options.limit ?? 50\n\n return {\n slug: RECONCILE_TASK,\n label: 'YooKassa: check unpaid transactions',\n inputSchema: [],\n outputSchema: [\n { name: 'checked', type: 'number' },\n { name: 'settled', type: 'number' },\n { name: 'cancelled', type: 'number' },\n { name: 'failed', type: 'number' },\n ],\n // The next scheduled run is the retry.\n retries: 0,\n schedule: [{ cron: options.cron ?? '*/5 * * * *', queue: options.queue ?? DEFAULT_QUEUE }],\n handler: async ({ req }) => {\n const payload = req.payload\n const olderThan = new Date(Date.now() - minAgeMinutes * 60_000).toISOString()\n\n const found = await payload.find({\n collection: transactionsSlug as never,\n depth: 0,\n limit,\n pagination: false,\n overrideAccess: true,\n sort: 'createdAt',\n where: {\n and: [\n { paymentMethod: { equals: 'yookassa' } },\n { status: { equals: 'pending' } },\n { createdAt: { less_than: olderThan } },\n { 'yookassa.paymentID': { exists: true } },\n ],\n } as never,\n })\n\n let settled = 0\n let cancelled = 0\n let failed = 0\n\n for (const doc of found.docs) {\n const transaction = doc as unknown as Record<string, unknown>\n const provider = isRecord(transaction.yookassa) ? transaction.yookassa : {}\n const paymentID = provider.paymentID\n\n if (typeof paymentID !== 'string' || !paymentID) continue\n\n try {\n const payment = await config.client.getPayment(paymentID)\n const result = await applyPayment({ config, payment, req, transaction, transactionsSlug })\n\n if (result === 'settled') settled += 1\n\n if (result === 'cancelled') cancelled += 1\n } catch (error) {\n // One broken transaction must not stop the others.\n failed += 1\n\n payload.logger.error({\n err: error,\n msg: `YooKassa reconcile: transaction ${String(transaction.id)} could not be checked`,\n })\n }\n }\n\n if (settled > 0) {\n payload.logger.warn(\n `YooKassa reconcile: ${settled} paid order(s) were created that the notification had missed.`,\n )\n }\n\n return { output: { checked: found.docs.length, settled, cancelled, failed } }\n },\n }\n}\n"],"names":["DEFAULT_QUEUE","applyPayment","isRecord","RECONCILE_TASK","reconcileTask","config","options","transactionsSlug","minAgeMinutes","limit","slug","label","inputSchema","outputSchema","name","type","retries","schedule","cron","queue","handler","req","payload","olderThan","Date","now","toISOString","found","find","collection","depth","pagination","overrideAccess","sort","where","and","paymentMethod","equals","status","createdAt","less_than","exists","settled","cancelled","failed","doc","docs","transaction","provider","yookassa","paymentID","payment","client","getPayment","result","error","logger","err","msg","String","id","warn","output","checked","length"],"mappings":"AAAA,SAASA,aAAa,QAAQ,iDAAgD;AAG9E,SAASC,YAAY,QAAQ,gBAAe;AAE5C,SAASC,QAAQ,QAAQ,aAAY;AAErC,OAAO,MAAMC,iBAAiB,oBAAmB;AAoBjD;;;;;;;;CAQC,GACD,OAAO,MAAMC,gBAAgB,CAACC,QAAwBC,UAA4B,CAAC,CAAC;IAClF,MAAMC,mBAAmBD,QAAQC,gBAAgB,IAAI;IACrD,MAAMC,gBAAgBF,QAAQE,aAAa,IAAI;IAC/C,MAAMC,QAAQH,QAAQG,KAAK,IAAI;IAE/B,OAAO;QACLC,MAAMP;QACNQ,OAAO;QACPC,aAAa,EAAE;QACfC,cAAc;YACZ;gBAAEC,MAAM;gBAAWC,MAAM;YAAS;YAClC;gBAAED,MAAM;gBAAWC,MAAM;YAAS;YAClC;gBAAED,MAAM;gBAAaC,MAAM;YAAS;YACpC;gBAAED,MAAM;gBAAUC,MAAM;YAAS;SAClC;QACD,uCAAuC;QACvCC,SAAS;QACTC,UAAU;YAAC;gBAAEC,MAAMZ,QAAQY,IAAI,IAAI;gBAAeC,OAAOb,QAAQa,KAAK,IAAInB;YAAc;SAAE;QAC1FoB,SAAS,OAAO,EAAEC,GAAG,EAAE;YACrB,MAAMC,UAAUD,IAAIC,OAAO;YAC3B,MAAMC,YAAY,IAAIC,KAAKA,KAAKC,GAAG,KAAKjB,gBAAgB,QAAQkB,WAAW;YAE3E,MAAMC,QAAQ,MAAML,QAAQM,IAAI,CAAC;gBAC/BC,YAAYtB;gBACZuB,OAAO;gBACPrB;gBACAsB,YAAY;gBACZC,gBAAgB;gBAChBC,MAAM;gBACNC,OAAO;oBACLC,KAAK;wBACH;4BAAEC,eAAe;gCAAEC,QAAQ;4BAAW;wBAAE;wBACxC;4BAAEC,QAAQ;gCAAED,QAAQ;4BAAU;wBAAE;wBAChC;4BAAEE,WAAW;gCAAEC,WAAWjB;4BAAU;wBAAE;wBACtC;4BAAE,sBAAsB;gCAAEkB,QAAQ;4BAAK;wBAAE;qBAC1C;gBACH;YACF;YAEA,IAAIC,UAAU;YACd,IAAIC,YAAY;YAChB,IAAIC,SAAS;YAEb,KAAK,MAAMC,OAAOlB,MAAMmB,IAAI,CAAE;gBAC5B,MAAMC,cAAcF;gBACpB,MAAMG,WAAW9C,SAAS6C,YAAYE,QAAQ,IAAIF,YAAYE,QAAQ,GAAG,CAAC;gBAC1E,MAAMC,YAAYF,SAASE,SAAS;gBAEpC,IAAI,OAAOA,cAAc,YAAY,CAACA,WAAW;gBAEjD,IAAI;oBACF,MAAMC,UAAU,MAAM9C,OAAO+C,MAAM,CAACC,UAAU,CAACH;oBAC/C,MAAMI,SAAS,MAAMrD,aAAa;wBAAEI;wBAAQ8C;wBAAS9B;wBAAK0B;wBAAaxC;oBAAiB;oBAExF,IAAI+C,WAAW,WAAWZ,WAAW;oBAErC,IAAIY,WAAW,aAAaX,aAAa;gBAC3C,EAAE,OAAOY,OAAO;oBACd,mDAAmD;oBACnDX,UAAU;oBAEVtB,QAAQkC,MAAM,CAACD,KAAK,CAAC;wBACnBE,KAAKF;wBACLG,KAAK,CAAC,gCAAgC,EAAEC,OAAOZ,YAAYa,EAAE,EAAE,qBAAqB,CAAC;oBACvF;gBACF;YACF;YAEA,IAAIlB,UAAU,GAAG;gBACfpB,QAAQkC,MAAM,CAACK,IAAI,CACjB,CAAC,oBAAoB,EAAEnB,QAAQ,6DAA6D,CAAC;YAEjG;YAEA,OAAO;gBAAEoB,QAAQ;oBAAEC,SAASpC,MAAMmB,IAAI,CAACkB,MAAM;oBAAEtB;oBAASC;oBAAWC;gBAAO;YAAE;QAC9E;IACF;AACF,EAAC"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { GlobalConfig } from 'payload';
|
|
2
|
+
import type { ReceiptOptions } from './receipt.js';
|
|
3
|
+
import type { ReceiptResolver } from './types.js';
|
|
4
|
+
type SettingsAccess = Pick<NonNullable<GlobalConfig['access']>, 'read' | 'update'>;
|
|
5
|
+
type SettingsGlobalArgs = {
|
|
6
|
+
/**
|
|
7
|
+
* Who can open and edit the settings. Required on purpose: customers are users too,
|
|
8
|
+
* so a "logged in" check is not enough. Pass your admin-only access function.
|
|
9
|
+
*/
|
|
10
|
+
access: SettingsAccess;
|
|
11
|
+
slug?: string;
|
|
12
|
+
group?: string;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Global with the 54-FZ receipt settings of the shop, editable in the admin panel.
|
|
16
|
+
* Add it to `globals` and pass `receipt: receiptFromSettings()` to `yookassaAdapter`.
|
|
17
|
+
*/
|
|
18
|
+
export declare const yookassaSettingsGlobal: ({ access, group, slug, }: SettingsGlobalArgs) => GlobalConfig;
|
|
19
|
+
/**
|
|
20
|
+
* Turns the saved settings into the adapter's receipt options, `false` when receipts are off.
|
|
21
|
+
* Unknown or empty values fall back to the adapter defaults instead of breaking a payment.
|
|
22
|
+
*/
|
|
23
|
+
export declare const settingsToReceipt: (settings: unknown) => false | ReceiptOptions;
|
|
24
|
+
/**
|
|
25
|
+
* Reads the settings global for every payment, so a change in the admin panel
|
|
26
|
+
* applies at once, without a restart.
|
|
27
|
+
*/
|
|
28
|
+
export declare const receiptFromSettings: (slug?: string) => ReceiptResolver;
|
|
29
|
+
export {};
|
package/dist/settings.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { l } from '@serge-pro-dev/payload-plugins-shared/i18n';
|
|
2
|
+
import { VAT_CODE_OPTIONS } from './fields.js';
|
|
3
|
+
import { isVatCode } from './receipt.js';
|
|
4
|
+
const DEFAULT_SLUG = 'yookassa-settings';
|
|
5
|
+
const TAX_SYSTEM_OPTIONS = [
|
|
6
|
+
{
|
|
7
|
+
value: '1',
|
|
8
|
+
label: l('General (OSN)', 'Общая система (ОСН)')
|
|
9
|
+
},
|
|
10
|
+
{
|
|
11
|
+
value: '2',
|
|
12
|
+
label: l('Simplified, income (USN)', 'Упрощённая, доходы (УСН)')
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
value: '3',
|
|
16
|
+
label: l('Simplified, income minus expenses (USN)', 'Упрощённая, доходы минус расходы (УСН)')
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
value: '4',
|
|
20
|
+
label: l('Single imputed income tax (ENVD)', 'Единый налог на вмену (ЕНВД)')
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
value: '5',
|
|
24
|
+
label: l('Single agricultural tax (ESN)', 'Единый сельхозналог (ЕСХН)')
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
value: '6',
|
|
28
|
+
label: l('Patent', 'Патентная система')
|
|
29
|
+
}
|
|
30
|
+
];
|
|
31
|
+
const PAYMENT_SUBJECT_OPTIONS = [
|
|
32
|
+
{
|
|
33
|
+
value: 'commodity',
|
|
34
|
+
label: l('Goods', 'Товар')
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
value: 'service',
|
|
38
|
+
label: l('Service', 'Услуга')
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
value: 'job',
|
|
42
|
+
label: l('Work', 'Работа')
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
value: 'intellectual_activity',
|
|
46
|
+
label: l('Intellectual property', 'Результаты интеллектуальной деятельности')
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
value: 'payment',
|
|
50
|
+
label: l('Payment', 'Платёж')
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
value: 'composite',
|
|
54
|
+
label: l('Composite item', 'Составной предмет расчёта')
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
value: 'another',
|
|
58
|
+
label: l('Other', 'Иной предмет расчёта')
|
|
59
|
+
}
|
|
60
|
+
];
|
|
61
|
+
const PAYMENT_MODE_OPTIONS = [
|
|
62
|
+
{
|
|
63
|
+
value: 'full_payment',
|
|
64
|
+
label: l('Full payment', 'Полная оплата')
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
value: 'full_prepayment',
|
|
68
|
+
label: l('Full prepayment', 'Полная предоплата')
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
value: 'partial_prepayment',
|
|
72
|
+
label: l('Partial prepayment', 'Частичная предоплата')
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
value: 'advance',
|
|
76
|
+
label: l('Advance', 'Аванс')
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
value: 'partial_payment',
|
|
80
|
+
label: l('Partial payment and credit', 'Частичная оплата и кредит')
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
value: 'credit',
|
|
84
|
+
label: l('Credit', 'Кредит')
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
value: 'credit_payment',
|
|
88
|
+
label: l('Credit payment', 'Выплата по кредиту')
|
|
89
|
+
}
|
|
90
|
+
];
|
|
91
|
+
/**
|
|
92
|
+
* Global with the 54-FZ receipt settings of the shop, editable in the admin panel.
|
|
93
|
+
* Add it to `globals` and pass `receipt: receiptFromSettings()` to `yookassaAdapter`.
|
|
94
|
+
*/ export const yookassaSettingsGlobal = ({ access, group = 'Ecommerce', slug = DEFAULT_SLUG })=>({
|
|
95
|
+
slug,
|
|
96
|
+
access,
|
|
97
|
+
admin: {
|
|
98
|
+
group
|
|
99
|
+
},
|
|
100
|
+
label: l('YooKassa settings', 'Настройки ЮKassa'),
|
|
101
|
+
fields: [
|
|
102
|
+
{
|
|
103
|
+
name: 'receiptsEnabled',
|
|
104
|
+
type: 'checkbox',
|
|
105
|
+
defaultValue: false,
|
|
106
|
+
label: l('Send receipts (54-FZ)', 'Отправлять чеки (54-ФЗ)'),
|
|
107
|
+
admin: {
|
|
108
|
+
description: l('Turn on only when "Receipts from YooKassa" is connected in the YooKassa shop, otherwise payments are rejected.', 'Включайте, только если в магазине ЮKassa подключены «Чеки от ЮKassa», иначе платежи будут отклоняться.')
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
type: 'collapsible',
|
|
113
|
+
label: l('Receipt parameters', 'Параметры чека'),
|
|
114
|
+
admin: {
|
|
115
|
+
condition: (data)=>data?.receiptsEnabled === true
|
|
116
|
+
},
|
|
117
|
+
fields: [
|
|
118
|
+
{
|
|
119
|
+
name: 'taxSystemCode',
|
|
120
|
+
type: 'select',
|
|
121
|
+
options: TAX_SYSTEM_OPTIONS,
|
|
122
|
+
label: l('Tax system', 'Система налогообложения'),
|
|
123
|
+
admin: {
|
|
124
|
+
description: l('Fill in only when the shop has several tax systems. Otherwise leave empty.', 'Заполняйте, только если в магазине несколько систем налогообложения. Иначе оставьте пустым.')
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
name: 'defaultVatCode',
|
|
129
|
+
type: 'select',
|
|
130
|
+
defaultValue: '1',
|
|
131
|
+
options: VAT_CODE_OPTIONS,
|
|
132
|
+
label: l('Default VAT rate', 'Ставка НДС по умолчанию'),
|
|
133
|
+
admin: {
|
|
134
|
+
description: l('Used for products without their own VAT rate.', 'Для товаров, у которых не задана своя ставка.')
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
name: 'deliveryVatCode',
|
|
139
|
+
type: 'select',
|
|
140
|
+
options: VAT_CODE_OPTIONS,
|
|
141
|
+
label: l('VAT rate of the delivery', 'Ставка НДС доставки'),
|
|
142
|
+
admin: {
|
|
143
|
+
description: l('Empty means the default VAT rate.', 'Пусто — ставка по умолчанию.')
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
{
|
|
147
|
+
name: 'paymentSubject',
|
|
148
|
+
type: 'select',
|
|
149
|
+
defaultValue: 'commodity',
|
|
150
|
+
options: PAYMENT_SUBJECT_OPTIONS,
|
|
151
|
+
label: l('Subject of payment', 'Признак предмета расчёта')
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
name: 'paymentMode',
|
|
155
|
+
type: 'select',
|
|
156
|
+
defaultValue: 'full_payment',
|
|
157
|
+
options: PAYMENT_MODE_OPTIONS,
|
|
158
|
+
label: l('Method of payment', 'Признак способа расчёта')
|
|
159
|
+
}
|
|
160
|
+
]
|
|
161
|
+
}
|
|
162
|
+
]
|
|
163
|
+
});
|
|
164
|
+
const isOneOf = (value, options)=>typeof value === 'string' && options.some((option)=>option.value === value);
|
|
165
|
+
/**
|
|
166
|
+
* Turns the saved settings into the adapter's receipt options, `false` when receipts are off.
|
|
167
|
+
* Unknown or empty values fall back to the adapter defaults instead of breaking a payment.
|
|
168
|
+
*/ export const settingsToReceipt = (settings)=>{
|
|
169
|
+
if (typeof settings !== 'object' || settings === null) return false;
|
|
170
|
+
const data = settings;
|
|
171
|
+
if (data.receiptsEnabled !== true) return false;
|
|
172
|
+
const taxSystem = Number(data.taxSystemCode);
|
|
173
|
+
const vatCode = Number(data.defaultVatCode);
|
|
174
|
+
// Number(null) is 0, which is not a VAT code, so an empty select falls back to the default.
|
|
175
|
+
const deliveryVatCode = Number(data.deliveryVatCode);
|
|
176
|
+
return {
|
|
177
|
+
...Number.isInteger(taxSystem) && taxSystem >= 1 && taxSystem <= 6 ? {
|
|
178
|
+
taxSystemCode: taxSystem
|
|
179
|
+
} : {},
|
|
180
|
+
...isVatCode(vatCode) ? {
|
|
181
|
+
defaultVatCode: vatCode
|
|
182
|
+
} : {},
|
|
183
|
+
...isVatCode(deliveryVatCode) ? {
|
|
184
|
+
deliveryVatCode
|
|
185
|
+
} : {},
|
|
186
|
+
...isOneOf(data.paymentSubject, PAYMENT_SUBJECT_OPTIONS) ? {
|
|
187
|
+
paymentSubject: data.paymentSubject
|
|
188
|
+
} : {},
|
|
189
|
+
...isOneOf(data.paymentMode, PAYMENT_MODE_OPTIONS) ? {
|
|
190
|
+
paymentMode: data.paymentMode
|
|
191
|
+
} : {}
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
/**
|
|
195
|
+
* Reads the settings global for every payment, so a change in the admin panel
|
|
196
|
+
* applies at once, without a restart.
|
|
197
|
+
*/ export const receiptFromSettings = (slug = DEFAULT_SLUG)=>async ({ req })=>{
|
|
198
|
+
const settings = await req.payload.findGlobal({
|
|
199
|
+
slug: slug,
|
|
200
|
+
depth: 0,
|
|
201
|
+
overrideAccess: true,
|
|
202
|
+
req
|
|
203
|
+
});
|
|
204
|
+
return settingsToReceipt(settings);
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
//# sourceMappingURL=settings.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/settings.ts"],"sourcesContent":["import { l } from '@serge-pro-dev/payload-plugins-shared/i18n'\nimport type { GlobalConfig } from 'payload'\n\nimport { VAT_CODE_OPTIONS } from './fields.js'\nimport type { ReceiptOptions, TaxSystemCode } from './receipt.js'\nimport { isVatCode } from './receipt.js'\nimport type { ReceiptResolver } from './types.js'\n\nconst DEFAULT_SLUG = 'yookassa-settings'\n\nconst TAX_SYSTEM_OPTIONS = [\n { value: '1', label: l('General (OSN)', 'Общая система (ОСН)') },\n { value: '2', label: l('Simplified, income (USN)', 'Упрощённая, доходы (УСН)') },\n {\n value: '3',\n label: l('Simplified, income minus expenses (USN)', 'Упрощённая, доходы минус расходы (УСН)'),\n },\n { value: '4', label: l('Single imputed income tax (ENVD)', 'Единый налог на вмену (ЕНВД)') },\n { value: '5', label: l('Single agricultural tax (ESN)', 'Единый сельхозналог (ЕСХН)') },\n { value: '6', label: l('Patent', 'Патентная система') },\n]\n\nconst PAYMENT_SUBJECT_OPTIONS = [\n { value: 'commodity', label: l('Goods', 'Товар') },\n { value: 'service', label: l('Service', 'Услуга') },\n { value: 'job', label: l('Work', 'Работа') },\n { value: 'intellectual_activity', label: l('Intellectual property', 'Результаты интеллектуальной деятельности') },\n { value: 'payment', label: l('Payment', 'Платёж') },\n { value: 'composite', label: l('Composite item', 'Составной предмет расчёта') },\n { value: 'another', label: l('Other', 'Иной предмет расчёта') },\n]\n\nconst PAYMENT_MODE_OPTIONS = [\n { value: 'full_payment', label: l('Full payment', 'Полная оплата') },\n { value: 'full_prepayment', label: l('Full prepayment', 'Полная предоплата') },\n { value: 'partial_prepayment', label: l('Partial prepayment', 'Частичная предоплата') },\n { value: 'advance', label: l('Advance', 'Аванс') },\n { value: 'partial_payment', label: l('Partial payment and credit', 'Частичная оплата и кредит') },\n { value: 'credit', label: l('Credit', 'Кредит') },\n { value: 'credit_payment', label: l('Credit payment', 'Выплата по кредиту') },\n]\n\ntype SettingsAccess = Pick<NonNullable<GlobalConfig['access']>, 'read' | 'update'>\n\ntype SettingsGlobalArgs = {\n /**\n * Who can open and edit the settings. Required on purpose: customers are users too,\n * so a \"logged in\" check is not enough. Pass your admin-only access function.\n */\n access: SettingsAccess\n slug?: string\n group?: string\n}\n\n/**\n * Global with the 54-FZ receipt settings of the shop, editable in the admin panel.\n * Add it to `globals` and pass `receipt: receiptFromSettings()` to `yookassaAdapter`.\n */\nexport const yookassaSettingsGlobal = ({\n access,\n group = 'Ecommerce',\n slug = DEFAULT_SLUG,\n}: SettingsGlobalArgs): GlobalConfig => ({\n slug,\n access,\n admin: { group },\n label: l('YooKassa settings', 'Настройки ЮKassa'),\n fields: [\n {\n name: 'receiptsEnabled',\n type: 'checkbox',\n defaultValue: false,\n label: l('Send receipts (54-FZ)', 'Отправлять чеки (54-ФЗ)'),\n admin: {\n description: l(\n 'Turn on only when \"Receipts from YooKassa\" is connected in the YooKassa shop, otherwise payments are rejected.',\n 'Включайте, только если в магазине ЮKassa подключены «Чеки от ЮKassa», иначе платежи будут отклоняться.',\n ),\n },\n },\n {\n type: 'collapsible',\n label: l('Receipt parameters', 'Параметры чека'),\n admin: { condition: (data) => data?.receiptsEnabled === true },\n fields: [\n {\n name: 'taxSystemCode',\n type: 'select',\n options: TAX_SYSTEM_OPTIONS,\n label: l('Tax system', 'Система налогообложения'),\n admin: {\n description: l(\n 'Fill in only when the shop has several tax systems. Otherwise leave empty.',\n 'Заполняйте, только если в магазине несколько систем налогообложения. Иначе оставьте пустым.',\n ),\n },\n },\n {\n name: 'defaultVatCode',\n type: 'select',\n defaultValue: '1',\n options: VAT_CODE_OPTIONS,\n label: l('Default VAT rate', 'Ставка НДС по умолчанию'),\n admin: {\n description: l(\n 'Used for products without their own VAT rate.',\n 'Для товаров, у которых не задана своя ставка.',\n ),\n },\n },\n {\n name: 'deliveryVatCode',\n type: 'select',\n options: VAT_CODE_OPTIONS,\n label: l('VAT rate of the delivery', 'Ставка НДС доставки'),\n admin: {\n description: l(\n 'Empty means the default VAT rate.',\n 'Пусто — ставка по умолчанию.',\n ),\n },\n },\n {\n name: 'paymentSubject',\n type: 'select',\n defaultValue: 'commodity',\n options: PAYMENT_SUBJECT_OPTIONS,\n label: l('Subject of payment', 'Признак предмета расчёта'),\n },\n {\n name: 'paymentMode',\n type: 'select',\n defaultValue: 'full_payment',\n options: PAYMENT_MODE_OPTIONS,\n label: l('Method of payment', 'Признак способа расчёта'),\n },\n ],\n },\n ],\n})\n\nconst isOneOf = (value: unknown, options: { value: string }[]): value is string =>\n typeof value === 'string' && options.some((option) => option.value === value)\n\n/**\n * Turns the saved settings into the adapter's receipt options, `false` when receipts are off.\n * Unknown or empty values fall back to the adapter defaults instead of breaking a payment.\n */\nexport const settingsToReceipt = (settings: unknown): false | ReceiptOptions => {\n if (typeof settings !== 'object' || settings === null) return false\n\n const data = settings as Record<string, unknown>\n\n if (data.receiptsEnabled !== true) return false\n\n const taxSystem = Number(data.taxSystemCode)\n const vatCode = Number(data.defaultVatCode)\n // Number(null) is 0, which is not a VAT code, so an empty select falls back to the default.\n const deliveryVatCode = Number(data.deliveryVatCode)\n\n return {\n ...(Number.isInteger(taxSystem) && taxSystem >= 1 && taxSystem <= 6\n ? { taxSystemCode: taxSystem as TaxSystemCode }\n : {}),\n ...(isVatCode(vatCode) ? { defaultVatCode: vatCode } : {}),\n ...(isVatCode(deliveryVatCode) ? { deliveryVatCode } : {}),\n ...(isOneOf(data.paymentSubject, PAYMENT_SUBJECT_OPTIONS)\n ? { paymentSubject: data.paymentSubject }\n : {}),\n ...(isOneOf(data.paymentMode, PAYMENT_MODE_OPTIONS) ? { paymentMode: data.paymentMode } : {}),\n }\n}\n\n/**\n * Reads the settings global for every payment, so a change in the admin panel\n * applies at once, without a restart.\n */\nexport const receiptFromSettings =\n (slug = DEFAULT_SLUG): ReceiptResolver =>\n async ({ req }) => {\n const settings = await req.payload.findGlobal({\n slug: slug as never,\n depth: 0,\n overrideAccess: true,\n req,\n })\n\n return settingsToReceipt(settings)\n }\n"],"names":["l","VAT_CODE_OPTIONS","isVatCode","DEFAULT_SLUG","TAX_SYSTEM_OPTIONS","value","label","PAYMENT_SUBJECT_OPTIONS","PAYMENT_MODE_OPTIONS","yookassaSettingsGlobal","access","group","slug","admin","fields","name","type","defaultValue","description","condition","data","receiptsEnabled","options","isOneOf","some","option","settingsToReceipt","settings","taxSystem","Number","taxSystemCode","vatCode","defaultVatCode","deliveryVatCode","isInteger","paymentSubject","paymentMode","receiptFromSettings","req","payload","findGlobal","depth","overrideAccess"],"mappings":"AAAA,SAASA,CAAC,QAAQ,6CAA4C;AAG9D,SAASC,gBAAgB,QAAQ,cAAa;AAE9C,SAASC,SAAS,QAAQ,eAAc;AAGxC,MAAMC,eAAe;AAErB,MAAMC,qBAAqB;IACzB;QAAEC,OAAO;QAAKC,OAAON,EAAE,iBAAiB;IAAuB;IAC/D;QAAEK,OAAO;QAAKC,OAAON,EAAE,4BAA4B;IAA4B;IAC/E;QACEK,OAAO;QACPC,OAAON,EAAE,2CAA2C;IACtD;IACA;QAAEK,OAAO;QAAKC,OAAON,EAAE,oCAAoC;IAAgC;IAC3F;QAAEK,OAAO;QAAKC,OAAON,EAAE,iCAAiC;IAA8B;IACtF;QAAEK,OAAO;QAAKC,OAAON,EAAE,UAAU;IAAqB;CACvD;AAED,MAAMO,0BAA0B;IAC9B;QAAEF,OAAO;QAAaC,OAAON,EAAE,SAAS;IAAS;IACjD;QAAEK,OAA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,CAAC,CAAC;QACzD,GAAIV,QAAQH,KAAKe,cAAc,EAAE5B,2BAC7B;YAAE4B,gBAAgBf,KAAKe,cAAc;QAAC,IACtC,CAAC,CAAC;QACN,GAAIZ,QAAQH,KAAKgB,WAAW,EAAE5B,wBAAwB;YAAE4B,aAAahB,KAAKgB,WAAW;QAAC,IAAI,CAAC,CAAC;IAC9F;AACF,EAAC;AAED;;;CAGC,GACD,OAAO,MAAMC,sBACX,CAACzB,OAAOT,YAAY,GACpB,OAAO,EAAEmC,GAAG,EAAE;QACZ,MAAMX,WAAW,MAAMW,IAAIC,OAAO,CAACC,UAAU,CAAC;YAC5C5B,MAAMA;YACN6B,OAAO;YACPC,gBAAgB;YAChBJ;QACF;QAEA,OAAOZ,kBAAkBC;IAC3B,EAAC"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { YooKassaPayment } from './api.js';
|
|
2
|
+
/** The buyer came back but the payment is not paid (yet): pending or canceled. */
|
|
3
|
+
export declare class PaymentNotCompletedError extends Error {
|
|
4
|
+
readonly status: string;
|
|
5
|
+
constructor(status: string);
|
|
6
|
+
}
|
|
7
|
+
export type SettlementInput = {
|
|
8
|
+
/** The transaction loaded from the database (depth 0). */
|
|
9
|
+
transaction: Record<string, unknown>;
|
|
10
|
+
/** The payment fetched from YooKassa by id. Never trust a webhook body or the browser. */
|
|
11
|
+
payment: YooKassaPayment;
|
|
12
|
+
/** The cart id resolved by the ecommerce confirm-order endpoint. */
|
|
13
|
+
canonicalCartID: unknown;
|
|
14
|
+
user?: {
|
|
15
|
+
id?: unknown;
|
|
16
|
+
} | null;
|
|
17
|
+
customerEmail?: unknown;
|
|
18
|
+
decimals?: number;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Checks that the YooKassa payment really settles this transaction for this buyer.
|
|
22
|
+
* Mirrors what the Stripe adapter of the ecommerce plugin verifies. Throws on any mismatch;
|
|
23
|
+
* a payment that is simply not paid yet throws PaymentNotCompletedError, after identity checks.
|
|
24
|
+
*/
|
|
25
|
+
export declare const validateSettlement: ({ transaction, payment, canonicalCartID, user, customerEmail, decimals, }: SettlementInput) => void;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { parseAmount } from './amount.js';
|
|
2
|
+
import { getRelationshipID, isRecord, normalizeEmail } from './utils.js';
|
|
3
|
+
/** The buyer came back but the payment is not paid (yet): pending or canceled. */ export class PaymentNotCompletedError extends Error {
|
|
4
|
+
status;
|
|
5
|
+
constructor(status){
|
|
6
|
+
super(`Payment is not completed (status: ${status})`);
|
|
7
|
+
this.name = 'PaymentNotCompletedError';
|
|
8
|
+
this.status = status;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Checks that the YooKassa payment really settles this transaction for this buyer.
|
|
13
|
+
* Mirrors what the Stripe adapter of the ecommerce plugin verifies. Throws on any mismatch;
|
|
14
|
+
* a payment that is simply not paid yet throws PaymentNotCompletedError, after identity checks.
|
|
15
|
+
*/ export const validateSettlement = ({ transaction, payment, canonicalCartID, user, customerEmail, decimals = 2 })=>{
|
|
16
|
+
if (transaction.paymentMethod !== 'yookassa') {
|
|
17
|
+
throw new Error('Transaction was not created for YooKassa');
|
|
18
|
+
}
|
|
19
|
+
const provider = isRecord(transaction.yookassa) ? transaction.yookassa : undefined;
|
|
20
|
+
if (!provider || typeof provider.paymentID !== 'string' || provider.paymentID !== payment.id) {
|
|
21
|
+
throw new Error('Payment does not match the transaction');
|
|
22
|
+
}
|
|
23
|
+
const transactionID = getRelationshipID(transaction.id);
|
|
24
|
+
if (!transactionID || payment.metadata?.transactionID !== transactionID) {
|
|
25
|
+
throw new Error('Payment metadata does not match the transaction');
|
|
26
|
+
}
|
|
27
|
+
const cartID = getRelationshipID(canonicalCartID);
|
|
28
|
+
if (!cartID || cartID !== getRelationshipID(transaction.cart)) {
|
|
29
|
+
throw new Error('Canonical cart does not match the transaction cart');
|
|
30
|
+
}
|
|
31
|
+
if (cartID !== payment.metadata?.cartID) {
|
|
32
|
+
throw new Error('Canonical cart does not match the payment cart');
|
|
33
|
+
}
|
|
34
|
+
const transactionCustomerID = getRelationshipID(transaction.customer);
|
|
35
|
+
if (user) {
|
|
36
|
+
const userID = getRelationshipID(user.id);
|
|
37
|
+
if (!userID) throw new Error('Authenticated customer ID is missing or invalid');
|
|
38
|
+
if (transactionCustomerID !== userID) {
|
|
39
|
+
throw new Error('Authenticated customer does not match the transaction customer');
|
|
40
|
+
}
|
|
41
|
+
} else {
|
|
42
|
+
if (transactionCustomerID) {
|
|
43
|
+
throw new Error('Guest transaction belongs to an authenticated customer');
|
|
44
|
+
}
|
|
45
|
+
const email = normalizeEmail(customerEmail);
|
|
46
|
+
if (!email || email !== normalizeEmail(transaction.customerEmail)) {
|
|
47
|
+
throw new Error('Guest email does not match the transaction email');
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const paidAmount = parseAmount(payment.amount?.value, decimals);
|
|
51
|
+
if (paidAmount === null || paidAmount !== transaction.amount) {
|
|
52
|
+
throw new Error('Payment amount does not match the transaction amount');
|
|
53
|
+
}
|
|
54
|
+
if (typeof payment.amount?.currency !== 'string' || typeof transaction.currency !== 'string' || payment.amount.currency.toUpperCase() !== transaction.currency.toUpperCase()) {
|
|
55
|
+
throw new Error('Payment currency does not match the transaction currency');
|
|
56
|
+
}
|
|
57
|
+
if (payment.status !== 'succeeded' || payment.paid !== true) {
|
|
58
|
+
throw new PaymentNotCompletedError(payment.status);
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
//# sourceMappingURL=settlement.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/settlement.ts"],"sourcesContent":["import { parseAmount } from './amount.js'\nimport type { YooKassaPayment } from './api.js'\nimport { getRelationshipID, isRecord, normalizeEmail } from './utils.js'\n\n/** The buyer came back but the payment is not paid (yet): pending or canceled. */\nexport class PaymentNotCompletedError extends Error {\n readonly status: string\n\n constructor(status: string) {\n super(`Payment is not completed (status: ${status})`)\n this.name = 'PaymentNotCompletedError'\n this.status = status\n }\n}\n\nexport type SettlementInput = {\n /** The transaction loaded from the database (depth 0). */\n transaction: Record<string, unknown>\n /** The payment fetched from YooKassa by id. Never trust a webhook body or the browser. */\n payment: YooKassaPayment\n /** The cart id resolved by the ecommerce confirm-order endpoint. */\n canonicalCartID: unknown\n user?: { id?: unknown } | null\n customerEmail?: unknown\n decimals?: number\n}\n\n/**\n * Checks that the YooKassa payment really settles this transaction for this buyer.\n * Mirrors what the Stripe adapter of the ecommerce plugin verifies. Throws on any mismatch;\n * a payment that is simply not paid yet throws PaymentNotCompletedError, after identity checks.\n */\nexport const validateSettlement = ({\n transaction,\n payment,\n canonicalCartID,\n user,\n customerEmail,\n decimals = 2,\n}: SettlementInput): void => {\n if (transaction.paymentMethod !== 'yookassa') {\n throw new Error('Transaction was not created for YooKassa')\n }\n\n const provider = isRecord(transaction.yookassa) ? transaction.yookassa : undefined\n\n if (!provider || typeof provider.paymentID !== 'string' || provider.paymentID !== payment.id) {\n throw new Error('Payment does not match the transaction')\n }\n\n const transactionID = getRelationshipID(transaction.id)\n\n if (!transactionID || payment.metadata?.transactionID !== transactionID) {\n throw new Error('Payment metadata does not match the transaction')\n }\n\n const cartID = getRelationshipID(canonicalCartID)\n\n if (!cartID || cartID !== getRelationshipID(transaction.cart)) {\n throw new Error('Canonical cart does not match the transaction cart')\n }\n\n if (cartID !== payment.metadata?.cartID) {\n throw new Error('Canonical cart does not match the payment cart')\n }\n\n const transactionCustomerID = getRelationshipID(transaction.customer)\n\n if (user) {\n const userID = getRelationshipID(user.id)\n\n if (!userID) throw new Error('Authenticated customer ID is missing or invalid')\n\n if (transactionCustomerID !== userID) {\n throw new Error('Authenticated customer does not match the transaction customer')\n }\n } else {\n if (transactionCustomerID) {\n throw new Error('Guest transaction belongs to an authenticated customer')\n }\n\n const email = normalizeEmail(customerEmail)\n\n if (!email || email !== normalizeEmail(transaction.customerEmail)) {\n throw new Error('Guest email does not match the transaction email')\n }\n }\n\n const paidAmount = parseAmount(payment.amount?.value, decimals)\n\n if (paidAmount === null || paidAmount !== transaction.amount) {\n throw new Error('Payment amount does not match the transaction amount')\n }\n\n if (\n typeof payment.amount?.currency !== 'string' ||\n typeof transaction.currency !== 'string' ||\n payment.amount.currency.toUpperCase() !== transaction.currency.toUpperCase()\n ) {\n throw new Error('Payment currency does not match the transaction currency')\n }\n\n if (payment.status !== 'succeeded' || payment.paid !== true) {\n throw new PaymentNotCompletedError(payment.status)\n }\n}\n"],"names":["parseAmount","getRelationshipID","isRecord","normalizeEmail","PaymentNotCompletedError","Error","status","name","validateSettlement","transaction","payment","canonicalCartID","user","customerEmail","decimals","paymentMethod","provider","yookassa","undefined","paymentID","id","transactionID","metadata","cartID","cart","transactionCustomerID","customer","userID","email","paidAmount","amount","value","currency","toUpperCase","paid"],"mappings":"AAAA,SAASA,WAAW,QAAQ,cAAa;AAEzC,SAASC,iBAAiB,EAAEC,QAAQ,EAAEC,cAAc,QAAQ,aAAY;AAExE,gFAAgF,GAChF,OAAO,MAAMC,iCAAiCC;IACnCC,OAAc;IAEvB,YAAYA,MAAc,CAAE;QAC1B,KAAK,CAAC,CAAC,kCAAkC,EAAEA,OAAO,CAAC,CAAC;QACpD,IAAI,CAACC,IAAI,GAAG;QACZ,IAAI,CAACD,MAAM,GAAGA;IAChB;AACF;AAcA;;;;CAIC,GACD,OAAO,MAAME,qBAAqB,CAAC,EACjCC,WAAW,EACXC,OAAO,EACPC,eAAe,EACfC,IAAI,EACJC,aAAa,EACbC,WAAW,CAAC,EACI;IAChB,IAAIL,YAAYM,aAAa,KAAK,YAAY;QAC5C,MAAM,IAAIV,MAAM;IAClB;IAEA,MAAMW,WAAWd,SAASO,YAAYQ,QAAQ,IAAIR,YAAYQ,QAAQ,GAAGC;IAEzE,IAAI,CAACF,YAAY,OAAOA,SAASG,SAAS,KAAK,YAAYH,SAASG,SAAS,KAAKT,QAAQU,EAAE,EAAE;QAC5F,MA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AAI9B,yBAAyBM,QAAQJ,MAAM;IACnD;AACF,EAAC"}
|
package/dist/status.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Endpoint } from 'payload';
|
|
2
|
+
import type { ResolvedConfig } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* GET /api/payments/yookassa/status?transaction=<id>&email=<guest email>
|
|
5
|
+
*
|
|
6
|
+
* For the page the buyer returns to: `succeeded`, `canceled` (with the reason) or `pending`.
|
|
7
|
+
* It lets the page stop waiting at once when the payment failed, and say why. The ecommerce
|
|
8
|
+
* confirm-order endpoint cannot do that: it answers any failure with a generic error.
|
|
9
|
+
*
|
|
10
|
+
* Only the buyer gets an answer: a logged-in buyer must own the transaction, a guest must send
|
|
11
|
+
* the email of the order. Anything else is `not_found`, the same as a missing transaction.
|
|
12
|
+
*/
|
|
13
|
+
export declare const statusEndpoint: (config: ResolvedConfig, transactionsSlug?: string) => Endpoint;
|