@serge-pro-dev/payload-payment-yookassa 0.0.0-stage → 0.1.0-beta.1

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 (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +146 -2
  3. package/README.ru.md +148 -0
  4. package/dist/amount.d.ts +11 -0
  5. package/dist/amount.js +29 -0
  6. package/dist/amount.js.map +1 -0
  7. package/dist/api.d.ts +51 -0
  8. package/dist/api.js +58 -0
  9. package/dist/api.js.map +1 -0
  10. package/dist/client.d.ts +49 -0
  11. package/dist/client.js +61 -0
  12. package/dist/client.js.map +1 -0
  13. package/dist/confirm.d.ts +4 -0
  14. package/dist/confirm.js +95 -0
  15. package/dist/confirm.js.map +1 -0
  16. package/dist/fields.d.ts +13 -0
  17. package/dist/fields.js +68 -0
  18. package/dist/fields.js.map +1 -0
  19. package/dist/finalize.d.ts +45 -0
  20. package/dist/finalize.js +207 -0
  21. package/dist/finalize.js.map +1 -0
  22. package/dist/index.d.ts +32 -0
  23. package/dist/index.js +164 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/initiate.d.ts +3 -0
  26. package/dist/initiate.js +221 -0
  27. package/dist/initiate.js.map +1 -0
  28. package/dist/messages.d.ts +3 -0
  29. package/dist/messages.js +77 -0
  30. package/dist/messages.js.map +1 -0
  31. package/dist/receipt.d.ts +57 -0
  32. package/dist/receipt.js +43 -0
  33. package/dist/receipt.js.map +1 -0
  34. package/dist/reconcile.d.ts +35 -0
  35. package/dist/reconcile.js +125 -0
  36. package/dist/reconcile.js.map +1 -0
  37. package/dist/settings.d.ts +29 -0
  38. package/dist/settings.js +207 -0
  39. package/dist/settings.js.map +1 -0
  40. package/dist/settlement.d.ts +25 -0
  41. package/dist/settlement.js +62 -0
  42. package/dist/settlement.js.map +1 -0
  43. package/dist/status.d.ts +13 -0
  44. package/dist/status.js +92 -0
  45. package/dist/status.js.map +1 -0
  46. package/dist/types.d.ts +84 -0
  47. package/dist/types.js +3 -0
  48. package/dist/types.js.map +1 -0
  49. package/dist/utils.d.ts +8 -0
  50. package/dist/utils.js +25 -0
  51. package/dist/utils.js.map +1 -0
  52. package/dist/webhooks.d.ts +16 -0
  53. package/dist/webhooks.js +83 -0
  54. package/dist/webhooks.js.map +1 -0
  55. package/package.json +54 -3
package/dist/index.js ADDED
@@ -0,0 +1,164 @@
1
+ import { l } from '@serge-pro-dev/payload-plugins-shared/i18n';
2
+ import { createYooKassaClient } from './api.js';
3
+ import { confirmOrder } from './confirm.js';
4
+ import { initiatePayment } from './initiate.js';
5
+ import { reconcileTask } from './reconcile.js';
6
+ import { statusEndpoint } from './status.js';
7
+ import { webhooksEndpoint } from './webhooks.js';
8
+ export { formatAmount, parseAmount } from './amount.js';
9
+ export { cancellationMessage } from './messages.js';
10
+ export { VAT_CODE_OPTIONS, vatCodeField } from './fields.js';
11
+ export { receiptFromSettings, settingsToReceipt, yookassaSettingsGlobal } from './settings.js';
12
+ const NAME = 'yookassa';
13
+ /**
14
+ * YooKassa payment adapter for @payloadcms/plugin-ecommerce.
15
+ *
16
+ * ecommercePlugin({ payments: { paymentMethods: [yookassaAdapter({ ... })] } })
17
+ *
18
+ * The buyer is redirected to the YooKassa payment page. The order is created by the
19
+ * webhook (POST /api/payments/yookassa/webhooks) as soon as the payment succeeds, or by
20
+ * the return page at `returnPath`, whichever comes first.
21
+ */ export const yookassaAdapter = (props)=>createYooKassa(props).adapter;
22
+ /**
23
+ * The adapter plus the job that checks unpaid transactions. Both share one configuration:
24
+ *
25
+ * const yookassa = createYooKassa({ ... })
26
+ * ecommercePlugin({ payments: { paymentMethods: [yookassa.adapter] } })
27
+ * buildConfig({ jobs: { tasks: [yookassa.reconcileTask()] } })
28
+ */ export const createYooKassa = (props)=>{
29
+ if (!props.shopId || !props.secretKey) {
30
+ throw new Error('yookassaAdapter: shopId and secretKey are required');
31
+ }
32
+ if (!props.returnBaseUrl) throw new Error('yookassaAdapter: returnBaseUrl is required');
33
+ const config = {
34
+ client: createYooKassaClient({
35
+ shopId: props.shopId,
36
+ secretKey: props.secretKey,
37
+ timeoutMs: props.timeoutMs
38
+ }),
39
+ returnBaseUrl: props.returnBaseUrl,
40
+ returnPath: props.returnPath ?? '/checkout/confirm-order',
41
+ receipt: props.receipt ?? false,
42
+ delivery: props.delivery,
43
+ vatCodeField: props.vatCodeField ?? 'vatCode',
44
+ productsSlug: props.productsSlug ?? 'products',
45
+ variantsSlug: props.variantsSlug ?? 'variants',
46
+ ordersSlug: props.ordersSlug ?? 'orders',
47
+ cartsSlug: props.cartsSlug ?? 'carts',
48
+ currency: (props.currency ?? 'RUB').toUpperCase(),
49
+ decimals: props.decimals ?? 2
50
+ };
51
+ const baseFields = [
52
+ {
53
+ name: 'paymentID',
54
+ type: 'text',
55
+ label: l('YooKassa payment ID', 'ID платежа ЮKassa'),
56
+ index: true
57
+ },
58
+ {
59
+ name: 'status',
60
+ type: 'text',
61
+ label: l('YooKassa status', 'Статус в ЮKassa'),
62
+ admin: {
63
+ readOnly: true
64
+ }
65
+ },
66
+ {
67
+ name: 'cancellation',
68
+ type: 'group',
69
+ label: l('Cancellation', 'Отмена платежа'),
70
+ admin: {
71
+ // Filled by the system; shown only for a payment that YooKassa canceled.
72
+ readOnly: true,
73
+ condition: (_data, siblingData)=>siblingData?.status === 'canceled' || Boolean(siblingData?.cancellation?.reason)
74
+ },
75
+ fields: [
76
+ {
77
+ name: 'reason',
78
+ type: 'text',
79
+ label: l('Reason', 'Причина')
80
+ },
81
+ {
82
+ name: 'party',
83
+ type: 'text',
84
+ label: l('Initiated by', 'Кто отменил')
85
+ }
86
+ ]
87
+ },
88
+ {
89
+ name: 'shippingAddress',
90
+ type: 'json',
91
+ label: l('Shipping address', 'Адрес доставки')
92
+ },
93
+ {
94
+ name: 'delivery',
95
+ type: 'group',
96
+ label: l('Delivery', 'Доставка'),
97
+ admin: {
98
+ // Filled by the system; shown only when the buyer chose a delivery method.
99
+ readOnly: true,
100
+ condition: (_data, siblingData)=>Boolean(siblingData?.delivery?.methodID)
101
+ },
102
+ fields: [
103
+ {
104
+ name: 'title',
105
+ type: 'text',
106
+ label: l('Delivery method', 'Способ доставки')
107
+ },
108
+ {
109
+ name: 'amount',
110
+ type: 'number',
111
+ label: l('Delivery cost (minor units)', 'Стоимость доставки (в копейках)')
112
+ },
113
+ {
114
+ name: 'methodID',
115
+ type: 'text',
116
+ label: l('Delivery method ID', 'ID способа доставки')
117
+ },
118
+ {
119
+ name: 'details',
120
+ type: 'json',
121
+ label: l('Details', 'Детали')
122
+ }
123
+ ]
124
+ },
125
+ {
126
+ name: 'utm',
127
+ type: 'json',
128
+ label: 'UTM',
129
+ admin: {
130
+ // Only when the visitor allowed attribution cookies.
131
+ condition: (_data, siblingData)=>typeof siblingData?.utm === 'object' && siblingData.utm !== null && Object.keys(siblingData.utm).length > 0
132
+ }
133
+ }
134
+ ];
135
+ const group = {
136
+ name: NAME,
137
+ type: 'group',
138
+ ...props.groupOverrides,
139
+ admin: {
140
+ condition: (data)=>data?.paymentMethod === NAME,
141
+ ...props.groupOverrides?.admin
142
+ },
143
+ fields: typeof props.groupOverrides?.fields === 'function' ? props.groupOverrides.fields({
144
+ defaultFields: baseFields
145
+ }) : baseFields
146
+ };
147
+ const adapter = {
148
+ name: NAME,
149
+ label: props.label ?? 'ЮKassa',
150
+ confirmOrder: confirmOrder(config),
151
+ endpoints: [
152
+ webhooksEndpoint(config),
153
+ statusEndpoint(config)
154
+ ],
155
+ group,
156
+ initiatePayment: initiatePayment(config)
157
+ };
158
+ return {
159
+ adapter,
160
+ reconcileTask: (options)=>reconcileTask(config, options)
161
+ };
162
+ };
163
+
164
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { PaymentAdapter } from '@payloadcms/plugin-ecommerce/types'\nimport { l } from '@serge-pro-dev/payload-plugins-shared/i18n'\nimport type { Field, GroupField, TaskConfig } from 'payload'\n\nimport { createYooKassaClient } from './api.js'\nimport { confirmOrder } from './confirm.js'\nimport { initiatePayment } from './initiate.js'\nimport { reconcileTask } from './reconcile.js'\nimport type { ReconcileOptions } from './reconcile.js'\nimport { statusEndpoint } from './status.js'\nimport type { ResolvedConfig, YooKassaAdapterProps } from './types.js'\nimport { webhooksEndpoint } from './webhooks.js'\n\nexport { formatAmount, parseAmount } from './amount.js'\nexport { cancellationMessage } from './messages.js'\nexport type { ReconcileOptions } from './reconcile.js'\nexport { VAT_CODE_OPTIONS, vatCodeField } from './fields.js'\nexport type { ReceiptOptions, TaxSystemCode } from './receipt.js'\nexport { receiptFromSettings, settingsToReceipt, yookassaSettingsGlobal } from './settings.js'\nexport type {\n DeliveryQuote,\n DeliveryResolver,\n ReceiptResolver,\n YooKassaAdapterProps,\n} from './types.js'\n\nconst NAME = 'yookassa'\n\n/**\n * YooKassa payment adapter for @payloadcms/plugin-ecommerce.\n *\n * ecommercePlugin({ payments: { paymentMethods: [yookassaAdapter({ ... })] } })\n *\n * The buyer is redirected to the YooKassa payment page. The order is created by the\n * webhook (POST /api/payments/yookassa/webhooks) as soon as the payment succeeds, or by\n * the return page at `returnPath`, whichever comes first.\n */\nexport const yookassaAdapter = (props: YooKassaAdapterProps): PaymentAdapter =>\n createYooKassa(props).adapter\n\n/**\n * The adapter plus the job that checks unpaid transactions. Both share one configuration:\n *\n * const yookassa = createYooKassa({ ... })\n * ecommercePlugin({ payments: { paymentMethods: [yookassa.adapter] } })\n * buildConfig({ jobs: { tasks: [yookassa.reconcileTask()] } })\n */\nexport const createYooKassa = (\n props: YooKassaAdapterProps,\n): {\n adapter: PaymentAdapter\n reconcileTask: (options?: Omit<ReconcileOptions, 'transactionsSlug'>) => TaskConfig<any>\n} => {\n if (!props.shopId || !props.secretKey) {\n throw new Error('yookassaAdapter: shopId and secretKey are required')\n }\n\n if (!props.returnBaseUrl) throw new Error('yookassaAdapter: returnBaseUrl is required')\n\n const config: ResolvedConfig = {\n client: createYooKassaClient({\n shopId: props.shopId,\n secretKey: props.secretKey,\n timeoutMs: props.timeoutMs,\n }),\n returnBaseUrl: props.returnBaseUrl,\n returnPath: props.returnPath ?? '/checkout/confirm-order',\n receipt: props.receipt ?? false,\n delivery: props.delivery,\n vatCodeField: props.vatCodeField ?? 'vatCode',\n productsSlug: props.productsSlug ?? 'products',\n variantsSlug: props.variantsSlug ?? 'variants',\n ordersSlug: props.ordersSlug ?? 'orders',\n cartsSlug: props.cartsSlug ?? 'carts',\n currency: (props.currency ?? 'RUB').toUpperCase(),\n decimals: props.decimals ?? 2,\n }\n\n const baseFields: Field[] = [\n {\n name: 'paymentID',\n type: 'text',\n label: l('YooKassa payment ID', 'ID платежа ЮKassa'),\n index: true,\n },\n {\n name: 'status',\n type: 'text',\n label: l('YooKassa status', 'Статус в ЮKassa'),\n admin: { readOnly: true },\n },\n {\n name: 'cancellation',\n type: 'group',\n label: l('Cancellation', 'Отмена платежа'),\n admin: {\n // Filled by the system; shown only for a payment that YooKassa canceled.\n readOnly: true,\n condition: (_data, siblingData) =>\n siblingData?.status === 'canceled' || Boolean(siblingData?.cancellation?.reason),\n },\n fields: [\n { name: 'reason', type: 'text', label: l('Reason', 'Причина') },\n { name: 'party', type: 'text', label: l('Initiated by', 'Кто отменил') },\n ],\n },\n { name: 'shippingAddress', type: 'json', label: l('Shipping address', 'Адрес доставки') },\n {\n name: 'delivery',\n type: 'group',\n label: l('Delivery', 'Доставка'),\n admin: {\n // Filled by the system; shown only when the buyer chose a delivery method.\n readOnly: true,\n condition: (_data, siblingData) => Boolean(siblingData?.delivery?.methodID),\n },\n fields: [\n { name: 'title', type: 'text', label: l('Delivery method', 'Способ доставки') },\n {\n name: 'amount',\n type: 'number',\n label: l('Delivery cost (minor units)', 'Стоимость доставки (в копейках)'),\n },\n { name: 'methodID', type: 'text', label: l('Delivery method ID', 'ID способа доставки') },\n { name: 'details', type: 'json', label: l('Details', 'Детали') },\n ],\n },\n {\n name: 'utm',\n type: 'json',\n label: 'UTM',\n admin: {\n // Only when the visitor allowed attribution cookies.\n condition: (_data, siblingData) =>\n typeof siblingData?.utm === 'object' &&\n siblingData.utm !== null &&\n Object.keys(siblingData.utm).length > 0,\n },\n },\n ]\n\n const group = {\n name: NAME,\n type: 'group',\n ...props.groupOverrides,\n admin: {\n condition: (data: Record<string, unknown> | undefined) => data?.paymentMethod === NAME,\n ...props.groupOverrides?.admin,\n },\n fields:\n typeof props.groupOverrides?.fields === 'function'\n ? props.groupOverrides.fields({ defaultFields: baseFields })\n : baseFields,\n } as GroupField\n\n const adapter: PaymentAdapter = {\n name: NAME,\n label: props.label ?? 'ЮKassa',\n confirmOrder: confirmOrder(config),\n endpoints: [webhooksEndpoint(config), statusEndpoint(config)],\n group,\n initiatePayment: initiatePayment(config),\n }\n\n return {\n adapter,\n reconcileTask: (options) => reconcileTask(config, options),\n }\n}\n"],"names":["l","createYooKassaClient","confirmOrder","initiatePayment","reconcileTask","statusEndpoint","webhooksEndpoint","formatAmount","parseAmount","cancellationMessage","VAT_CODE_OPTIONS","vatCodeField","receiptFromSettings","settingsToReceipt","yookassaSettingsGlobal","NAME","yookassaAdapter","props","createYooKassa","adapter","shopId","secretKey","Error","returnBaseUrl","config","client","timeoutMs","returnPath","receipt","delivery","productsSlug","variantsSlug","ordersSlug","cartsSlug","currency","toUpperCase","decimals","baseFields","name","type","label","index","admin","readOnly","condition","_data","siblingData","status","Boolean","cancellation","reason","fields","methodID","utm","Object","keys","length","group","groupOverrides","data","paymentMethod","defaultFields","endpoints","options"],"mappings":"AACA,SAASA,CAAC,QAAQ,6CAA4C;AAG9D,SAASC,oBAAoB,QAAQ,WAAU;AAC/C,SAASC,YAAY,QAAQ,eAAc;AAC3C,SAASC,eAAe,QAAQ,gBAAe;AAC/C,SAASC,aAAa,QAAQ,iBAAgB;AAE9C,SAASC,cAAc,QAAQ,cAAa;AAE5C,SAASC,gBAAgB,QAAQ,gBAAe;AAEhD,SAASC,YAAY,EAAEC,WAAW,QAAQ,cAAa;AACvD,SA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A,MAAMC,kBAAkB7C;YAClF,GAAGE,MAAMyC,cAAc,EAAEhB,KAAK;QAChC;QACAS,QACE,OAAOlC,MAAMyC,cAAc,EAAEP,WAAW,aACpClC,MAAMyC,cAAc,CAACP,MAAM,CAAC;YAAEU,eAAexB;QAAW,KACxDA;IACR;IAEA,MAAMlB,UAA0B;QAC9BmB,MAAMvB;QACNyB,OAAOvB,MAAMuB,KAAK,IAAI;QACtBtC,cAAcA,aAAasB;QAC3BsC,WAAW;YAACxD,iBAAiBkB;YAASnB,eAAemB;SAAQ;QAC7DiC;QACAtD,iBAAiBA,gBAAgBqB;IACnC;IAEA,OAAO;QACLL;QACAf,eAAe,CAAC2D,UAAY3D,cAAcoB,QAAQuC;IACpD;AACF,EAAC"}
@@ -0,0 +1,3 @@
1
+ import type { PaymentAdapter } from '@payloadcms/plugin-ecommerce/types';
2
+ import type { ResolvedConfig } from './types.js';
3
+ export declare const initiatePayment: (config: ResolvedConfig) => PaymentAdapter["initiatePayment"];
@@ -0,0 +1,221 @@
1
+ import { readAttribution } from '@serge-pro-dev/payload-plugins-shared/utm';
2
+ import { formatAmount } from './amount.js';
3
+ import { buildReceipt, isVatCode, sumLines, truncate } from './receipt.js';
4
+ import { buildReturnUrl, getDocumentID, isRecord } from './utils.js';
5
+ const toVatCode = (value)=>{
6
+ const code = typeof value === 'string' ? Number(value) : value;
7
+ return isVatCode(code) ? code : undefined;
8
+ };
9
+ /**
10
+ * Prices come from the database, not from the browser or the cart snapshot:
11
+ * the amount of the payment is the sum of these lines.
12
+ */ const loadLines = async (config, req, items, currency)=>{
13
+ const priceField = `priceIn${currency.toUpperCase()}`;
14
+ const select = {
15
+ title: true,
16
+ [priceField]: true,
17
+ [config.vatCodeField]: true
18
+ };
19
+ const lines = [];
20
+ for (const item of items){
21
+ if (!isRecord(item)) throw new Error('Cart item is invalid');
22
+ const productID = getDocumentID(item.product);
23
+ const variantID = item.variant ? getDocumentID(item.variant) : undefined;
24
+ const quantity = item.quantity;
25
+ if (productID === undefined) throw new Error('Cart item has no product');
26
+ if (typeof quantity !== 'number' || !Number.isInteger(quantity) || quantity < 1) {
27
+ throw new Error('Cart item quantity is invalid');
28
+ }
29
+ const product = await req.payload.findByID({
30
+ collection: config.productsSlug,
31
+ id: productID,
32
+ depth: 0,
33
+ overrideAccess: true,
34
+ select: select
35
+ });
36
+ const variant = variantID === undefined ? undefined : await req.payload.findByID({
37
+ collection: config.variantsSlug,
38
+ id: variantID,
39
+ depth: 0,
40
+ overrideAccess: true,
41
+ select: select
42
+ });
43
+ const price = typeof variant?.[priceField] === 'number' ? variant[priceField] : product[priceField];
44
+ if (typeof price !== 'number' || !Number.isSafeInteger(price) || price < 1) {
45
+ throw new Error(`Product ${String(productID)} has no price in ${currency.toUpperCase()}`);
46
+ }
47
+ const title = typeof product.title === 'string' && product.title ? product.title : `Товар ${String(productID)}`;
48
+ const variantTitle = typeof variant?.title === 'string' && variant.title ? variant.title : '';
49
+ lines.push({
50
+ description: variantTitle ? `${title} — ${variantTitle}` : title,
51
+ quantity,
52
+ unitAmount: price,
53
+ vatCode: toVatCode(variant?.[config.vatCodeField]) ?? toVatCode(product[config.vatCodeField])
54
+ });
55
+ }
56
+ return lines;
57
+ };
58
+ export const initiatePayment = (config)=>async ({ data, req, transactionsSlug })=>{
59
+ const payload = req.payload;
60
+ const { cart, customerEmail, billingAddress, shippingAddress } = data;
61
+ const currency = String(data.currency ?? '').toUpperCase();
62
+ if (currency !== config.currency) {
63
+ throw new Error(`YooKassa accepts ${config.currency} only, got ${currency || 'no currency'}`);
64
+ }
65
+ if (!customerEmail || typeof customerEmail !== 'string') {
66
+ throw new Error('A valid customer email is required to make a purchase.');
67
+ }
68
+ if (!cart || !Array.isArray(cart.items) || cart.items.length === 0) {
69
+ throw new Error('Cart is empty or not provided.');
70
+ }
71
+ const lines = await loadLines(config, req, cart.items, currency);
72
+ const total = sumLines(lines);
73
+ if (typeof cart.subtotal === 'number' && cart.subtotal !== total) {
74
+ throw new Error('Cart total is out of date. Refresh the cart and try again.');
75
+ }
76
+ const receiptOptions = typeof config.receipt === 'function' ? await config.receipt({
77
+ req
78
+ }) : config.receipt;
79
+ const shipping = isRecord(shippingAddress) ? shippingAddress : undefined;
80
+ // Delivery is priced on the server from the buyer's choice and the database prices.
81
+ const delivery = config.delivery ? await config.delivery({
82
+ req,
83
+ currency,
84
+ subtotal: total,
85
+ shippingAddress: shipping
86
+ }) : null;
87
+ if (delivery && (!Number.isSafeInteger(delivery.amount) || delivery.amount < 0)) {
88
+ throw new Error('Delivery cost is invalid');
89
+ }
90
+ const payable = total + (delivery?.amount ?? 0);
91
+ // The receipt must add up to the payment amount, so the delivery is a line of it.
92
+ const receiptLines = delivery && delivery.amount > 0 ? [
93
+ ...lines,
94
+ {
95
+ description: truncate(`Доставка: ${delivery.title}`, 128),
96
+ quantity: 1,
97
+ unitAmount: delivery.amount,
98
+ vatCode: receiptOptions ? receiptOptions.deliveryVatCode : undefined,
99
+ paymentSubject: 'service'
100
+ }
101
+ ] : lines;
102
+ // Attribution cookies exist only when the visitor allowed them.
103
+ const providerData = {
104
+ ...shippingAddress ? {
105
+ shippingAddress
106
+ } : {},
107
+ ...delivery ? {
108
+ delivery: {
109
+ methodID: delivery.methodID,
110
+ title: delivery.title,
111
+ amount: delivery.amount,
112
+ ...delivery.details ? {
113
+ details: delivery.details
114
+ } : {}
115
+ }
116
+ } : {},
117
+ utm: readAttribution(req.headers?.get('cookie'))
118
+ };
119
+ const items = cart.items.map((item)=>{
120
+ const variantID = item.variant ? getDocumentID(item.variant) : undefined;
121
+ return {
122
+ product: getDocumentID(item.product),
123
+ quantity: item.quantity,
124
+ ...variantID === undefined ? {} : {
125
+ variant: variantID
126
+ }
127
+ };
128
+ });
129
+ const transaction = await payload.create({
130
+ collection: transactionsSlug,
131
+ data: {
132
+ ...req.user ? {
133
+ customer: req.user.id
134
+ } : {
135
+ customerEmail
136
+ },
137
+ amount: payable,
138
+ billingAddress,
139
+ cart: cart.id,
140
+ currency,
141
+ items,
142
+ paymentMethod: 'yookassa',
143
+ status: 'pending',
144
+ yookassa: providerData
145
+ },
146
+ overrideAccess: true,
147
+ req
148
+ });
149
+ const transactionID = String(transaction.id);
150
+ try {
151
+ const returnUrl = buildReturnUrl(config.returnBaseUrl, config.returnPath, {
152
+ transaction: transactionID,
153
+ // Guests are matched by email when the order is confirmed.
154
+ email: req.user ? undefined : customerEmail
155
+ });
156
+ const payment = await config.client.createPayment({
157
+ amount: {
158
+ value: formatAmount(payable, config.decimals),
159
+ currency
160
+ },
161
+ capture: true,
162
+ confirmation: {
163
+ type: 'redirect',
164
+ return_url: returnUrl
165
+ },
166
+ description: truncate(`Заказ №${transactionID}`, 128),
167
+ metadata: {
168
+ transactionID,
169
+ cartID: String(cart.id)
170
+ },
171
+ ...receiptOptions ? {
172
+ receipt: buildReceipt({
173
+ lines: receiptLines,
174
+ currency,
175
+ decimals: config.decimals,
176
+ customerEmail,
177
+ options: receiptOptions
178
+ })
179
+ } : {}
180
+ }, // One key per payment attempt, so a retried request never creates a second payment.
181
+ // Random on purpose: transaction ids repeat when the database is recreated, and
182
+ // YooKassa remembers a key for 24 hours.
183
+ crypto.randomUUID());
184
+ const confirmationUrl = payment.confirmation?.confirmation_url;
185
+ if (!confirmationUrl) throw new Error('YooKassa did not return a confirmation URL');
186
+ await payload.update({
187
+ collection: transactionsSlug,
188
+ id: transactionID,
189
+ data: {
190
+ yookassa: {
191
+ paymentID: payment.id,
192
+ status: payment.status,
193
+ ...providerData
194
+ }
195
+ },
196
+ overrideAccess: true,
197
+ req
198
+ });
199
+ return {
200
+ message: 'Payment initiated successfully',
201
+ confirmationUrl,
202
+ paymentID: payment.id,
203
+ transactionID
204
+ };
205
+ } catch (error) {
206
+ payload.logger.error({
207
+ err: error,
208
+ msg: 'Error initiating payment with YooKassa'
209
+ });
210
+ // No payment exists at the provider: do not leave an orphan transaction behind.
211
+ await payload.delete({
212
+ collection: transactionsSlug,
213
+ id: transactionID,
214
+ overrideAccess: true,
215
+ req
216
+ }).catch(()=>undefined);
217
+ throw new Error(error instanceof Error ? error.message : 'Unknown error initiating payment');
218
+ }
219
+ };
220
+
221
+ //# sourceMappingURL=initiate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/initiate.ts"],"sourcesContent":["import type { PaymentAdapter } from '@payloadcms/plugin-ecommerce/types'\nimport { readAttribution } from '@serge-pro-dev/payload-plugins-shared/utm'\n\nimport { formatAmount } from './amount.js'\nimport { buildReceipt, isVatCode, sumLines, truncate, type OrderLine } from './receipt.js'\nimport type { ResolvedConfig } from './types.js'\nimport { buildReturnUrl, getDocumentID, isRecord } from './utils.js'\n\nconst toVatCode = (value: unknown): number | undefined => {\n const code = typeof value === 'string' ? Number(value) : value\n\n return isVatCode(code) ? code : undefined\n}\n\n/**\n * Prices come from the database, not from the browser or the cart snapshot:\n * the amount of the payment is the sum of these lines.\n */\nconst loadLines = async (\n config: ResolvedConfig,\n req: Parameters<PaymentAdapter['initiatePayment']>[0]['req'],\n items: unknown[],\n currency: string,\n): Promise<OrderLine[]> => {\n const priceField = `priceIn${currency.toUpperCase()}`\n const select = { title: true, [priceField]: true, [config.vatCodeField]: true }\n const lines: OrderLine[] = []\n\n for (const item of items) {\n if (!isRecord(item)) throw new Error('Cart item is invalid')\n\n const productID = getDocumentID(item.product)\n const variantID = item.variant ? getDocumentID(item.variant) : undefined\n const quantity = item.quantity\n\n if (productID === undefined) throw new Error('Cart item has no product')\n\n if (typeof quantity !== 'number' || !Number.isInteger(quantity) || quantity < 1) {\n throw new Error('Cart item quantity is invalid')\n }\n\n const product = (await req.payload.findByID({\n collection: config.productsSlug as never,\n id: productID,\n depth: 0,\n overrideAccess: true,\n select: select as never,\n })) as unknown as Record<string, unknown>\n\n const variant =\n variantID === undefined\n ? undefined\n : ((await req.payload.findByID({\n collection: config.variantsSlug as never,\n id: variantID,\n depth: 0,\n overrideAccess: true,\n select: select as never,\n })) as unknown as Record<string, unknown>)\n\n const price = typeof variant?.[priceField] === 'number' ? variant[priceField] : product[priceField]\n\n if (typeof price !== 'number' || !Number.isSafeInteger(price) || price < 1) {\n throw new Error(`Product ${String(productID)} has no price in ${currency.toUpperCase()}`)\n }\n\n const title = typeof product.title === 'string' && product.title ? product.title : `Товар ${String(productID)}`\n const variantTitle = typeof variant?.title === 'string' && variant.title ? variant.title : ''\n\n lines.push({\n description: variantTitle ? `${title} — ${variantTitle}` : title,\n quantity,\n unitAmount: price,\n vatCode: toVatCode(variant?.[config.vatCodeField]) ?? toVatCode(product[config.vatCodeField]),\n })\n }\n\n return lines\n}\n\nexport const initiatePayment =\n (config: ResolvedConfig): PaymentAdapter['initiatePayment'] =>\n async ({ data, req, transactionsSlug }) => {\n const payload = req.payload\n const { cart, customerEmail, billingAddress, shippingAddress } = data\n const currency = String(data.currency ?? '').toUpperCase()\n\n if (currency !== config.currency) {\n throw new Error(`YooKassa accepts ${config.currency} only, got ${currency || 'no currency'}`)\n }\n\n if (!customerEmail || typeof customerEmail !== 'string') {\n throw new Error('A valid customer email is required to make a purchase.')\n }\n\n if (!cart || !Array.isArray(cart.items) || cart.items.length === 0) {\n throw new Error('Cart is empty or not provided.')\n }\n\n const lines = await loadLines(config, req, cart.items, currency)\n const total = sumLines(lines)\n\n if (typeof cart.subtotal === 'number' && cart.subtotal !== total) {\n throw new Error('Cart total is out of date. Refresh the cart and try again.')\n }\n\n const receiptOptions =\n typeof config.receipt === 'function' ? await config.receipt({ req }) : config.receipt\n\n const shipping = isRecord(shippingAddress) ? shippingAddress : undefined\n\n // Delivery is priced on the server from the buyer's choice and the database prices.\n const delivery = config.delivery\n ? await config.delivery({ req, currency, subtotal: total, shippingAddress: shipping })\n : null\n\n if (delivery && (!Number.isSafeInteger(delivery.amount) || delivery.amount < 0)) {\n throw new Error('Delivery cost is invalid')\n }\n\n const payable = total + (delivery?.amount ?? 0)\n\n // The receipt must add up to the payment amount, so the delivery is a line of it.\n const receiptLines: OrderLine[] =\n delivery && delivery.amount > 0\n ? [\n ...lines,\n {\n description: truncate(`Доставка: ${delivery.title}`, 128),\n quantity: 1,\n unitAmount: delivery.amount,\n vatCode: receiptOptions ? receiptOptions.deliveryVatCode : undefined,\n paymentSubject: 'service',\n },\n ]\n : lines\n\n // Attribution cookies exist only when the visitor allowed them.\n const providerData = {\n ...(shippingAddress ? { shippingAddress } : {}),\n ...(delivery\n ? {\n delivery: {\n methodID: delivery.methodID,\n title: delivery.title,\n amount: delivery.amount,\n ...(delivery.details ? { details: delivery.details } : {}),\n },\n }\n : {}),\n utm: readAttribution(req.headers?.get('cookie')),\n }\n\n const items = cart.items.map((item) => {\n const variantID = item.variant ? getDocumentID(item.variant) : undefined\n\n return {\n product: getDocumentID(item.product),\n quantity: item.quantity,\n ...(variantID === undefined ? {} : { variant: variantID }),\n }\n })\n\n const transaction = await payload.create({\n collection: transactionsSlug as never,\n data: {\n ...(req.user ? { customer: req.user.id } : { customerEmail }),\n amount: payable,\n billingAddress,\n cart: cart.id,\n currency,\n items,\n paymentMethod: 'yookassa',\n status: 'pending',\n yookassa: providerData,\n } as never,\n overrideAccess: true,\n req,\n })\n\n const transactionID = String((transaction as { id: number | string }).id)\n\n try {\n const returnUrl = buildReturnUrl(config.returnBaseUrl, config.returnPath, {\n transaction: transactionID,\n // Guests are matched by email when the order is confirmed.\n email: req.user ? undefined : customerEmail,\n })\n\n const payment = await config.client.createPayment(\n {\n amount: { value: formatAmount(payable, config.decimals), currency },\n capture: true,\n confirmation: { type: 'redirect', return_url: returnUrl },\n description: truncate(`Заказ №${transactionID}`, 128),\n metadata: { transactionID, cartID: String(cart.id) },\n ...(receiptOptions\n ? {\n receipt: buildReceipt({\n lines: receiptLines,\n currency,\n decimals: config.decimals,\n customerEmail,\n options: receiptOptions,\n }),\n }\n : {}),\n },\n // One key per payment attempt, so a retried request never creates a second payment.\n // Random on purpose: transaction ids repeat when the database is recreated, and\n // YooKassa remembers a key for 24 hours.\n crypto.randomUUID(),\n )\n\n const confirmationUrl = payment.confirmation?.confirmation_url\n\n if (!confirmationUrl) throw new Error('YooKassa did not return a confirmation URL')\n\n await payload.update({\n collection: transactionsSlug as never,\n id: transactionID,\n data: {\n yookassa: {\n paymentID: payment.id,\n status: payment.status,\n ...providerData,\n },\n } as never,\n overrideAccess: true,\n req,\n })\n\n return {\n message: 'Payment initiated successfully',\n confirmationUrl,\n paymentID: payment.id,\n transactionID,\n }\n } catch (error) {\n payload.logger.error({ err: error, msg: 'Error initiating payment with YooKassa' })\n\n // No payment exists at the provider: do not leave an orphan transaction behind.\n await payload\n .delete({\n collection: transactionsSlug as never,\n id: transactionID,\n overrideAccess: true,\n req,\n })\n .catch(() => undefined)\n\n throw new Error(error instanceof Error ? error.message : 'Unknown error initiating payment')\n }\n }\n"],"names":["readAttribution","formatAmount","buildReceipt","isVatCode","sumLines","truncate","buildReturnUrl","getDocumentID","isRecord","toVatCode","value","code","Number","undefined","loadLines","config","req","items","currency","priceField","toUpperCase","select","title","vatCodeField","lines","item","Error","productID","product","variantID","variant","quantity","isInteger","payload","findByID","collection","productsSlug","id","depth","overrideAccess","variantsSlug","price","isSafeInteger","String","variantTitle","push","description","unitAmount","vatCode","initiatePayment","data","transactionsSlug","cart","customerEmail","billingAddress","shippingAddress","Array","isArray","length","total","subtotal","receiptOptions","receipt","shipping","delivery","amount","payable","receiptLines","deliveryVatCode","paymentSubject","providerData","methodID","details","utm","headers","get","map","transaction","create","user","customer","paymentMethod","status","yookassa","transactionID","returnUrl","returnBaseUrl","returnPath","email","payment","client","createPayment","decimals","capture","confirmation","type","return_url","metadata","cartID","options","crypto","randomUUID","confirmationUrl","confirmation_url","update","paymentID","message","error","logger","err","msg","delete","catch"],"mappings":"AACA,SAASA,eAAe,QAAQ,4CAA2C;AAE3E,SAASC,YAAY,QAAQ,cAAa;AAC1C,SAASC,YAAY,EAAEC,SAAS,EAAEC,QAAQ,EAAEC,QAAQ,QAAwB,eAAc;AAE1F,SAASC,cAAc,EAAEC,aAAa,EAAEC,QAAQ,QAAQ,aAAY;AAE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C,MAAM;oBAAYC,YAAYX;gBAAU;gBACxDvC,aAAazC,SAAS,CAAC,OAAO,EAAE+E,eAAe,EAAE;gBACjDa,UAAU;oBAAEb;oBAAec,QAAQvD,OAAOS,KAAKf,EAAE;gBAAE;gBACnD,GAAIwB,iBACA;oBACEC,SAAS5D,aAAa;wBACpBsB,OAAO2C;wBACPjD;wBACA0E,UAAU7E,OAAO6E,QAAQ;wBACzBvC;wBACA8C,SAAStC;oBACX;gBACF,IACA,CAAC,CAAC;YACR,GACA,oFAAoF;YACpF,gFAAgF;YAChF,yCAAyC;YACzCuC,OAAOC,UAAU;YAGnB,MAAMC,kBAAkBb,QAAQK,YAAY,EAAES;YAE9C,IAAI,CAACD,iBAAiB,MAAM,IAAI5E,MAAM;YAEtC,MAAMO,QAAQuE,MAAM,CAAC;gBACnBrE,YAAYgB;gBACZd,IAAI+C;gBACJlC,MAAM;oBACJiC,UAAU;wBACRsB,WAAWhB,QAAQpD,EAAE;wBACrB6C,QAAQO,QAAQP,MAAM;wBACtB,GAAGZ,YAAY;oBACjB;gBACF;gBACA/B,gBAAgB;gBAChBvB;YACF;YAEA,OAAO;gBACL0F,SAAS;gBACTJ;gBACAG,WAAWhB,QAAQpD,EAAE;gBACrB+C;YACF;QACF,EAAE,OAAOuB,OAAO;YACd1E,QAAQ2E,MAAM,CAACD,KAAK,CAAC;gBAAEE,KAAKF;gBAAOG,KAAK;YAAyC;YAEjF,gFAAgF;YAChF,MAAM7E,QACH8E,MAAM,CAAC;gBACN5E,YAAYgB;gBACZd,IAAI+C;gBACJ7C,gBAAgB;gBAChBvB;YACF,GACCgG,KAAK,CAAC,IAAMnG;YAEf,MAAM,IAAIa,MAAMiF,iBAAiBjF,QAAQiF,MAAMD,OAAO,GAAG;QAC3D;IACF,EAAC"}
@@ -0,0 +1,3 @@
1
+ export type MessageLanguage = 'en' | 'ru';
2
+ /** Buyer-friendly text for a YooKassa cancellation reason. Unknown reasons get a generic one. */
3
+ export declare const cancellationMessage: (reason: string | null | undefined, language?: MessageLanguage) => string;
@@ -0,0 +1,77 @@
1
+ const GENERIC = {
2
+ en: 'The payment was not completed. No money has been charged. You can try again or choose another payment method.',
3
+ ru: 'Оплата не прошла, деньги не списаны. Попробуйте ещё раз или выберите другой способ оплаты.'
4
+ };
5
+ const REASONS = {
6
+ '3d_secure_failed': {
7
+ en: 'The 3-D Secure check failed. Please try again and enter the confirmation code from your bank.',
8
+ ru: 'Не удалось пройти проверку 3-D Secure. Попробуйте ещё раз и введите код подтверждения из банка.'
9
+ },
10
+ call_issuer: {
11
+ en: 'The bank declined the payment. Please contact your bank or use another card.',
12
+ ru: 'Банк отклонил платёж. Свяжитесь с банком или используйте другую карту.'
13
+ },
14
+ card_expired: {
15
+ en: 'The card has expired. Please use another card.',
16
+ ru: 'Срок действия карты истёк. Используйте другую карту.'
17
+ },
18
+ country_forbidden: {
19
+ en: 'Payments from the country of this card are not accepted. Please use another payment method.',
20
+ ru: 'Платежи с карт этой страны не принимаются. Выберите другой способ оплаты.'
21
+ },
22
+ fraud_suspected: {
23
+ en: 'The payment was declined as suspicious. Please use another payment method.',
24
+ ru: 'Платёж отклонён как подозрительный. Выберите другой способ оплаты.'
25
+ },
26
+ general_decline: {
27
+ en: 'The bank declined the payment without giving a reason. Please contact your bank or use another card.',
28
+ ru: 'Банк отклонил платёж без объяснения причин. Свяжитесь с банком или используйте другую карту.'
29
+ },
30
+ identification_required: {
31
+ en: 'This payment method requires identification of its owner. Please use another payment method.',
32
+ ru: 'Для этого способа оплаты нужна идентификация владельца. Выберите другой способ оплаты.'
33
+ },
34
+ insufficient_funds: {
35
+ en: 'There are not enough funds. Top up the balance or use another payment method.',
36
+ ru: 'Недостаточно средств. Пополните баланс или выберите другой способ оплаты.'
37
+ },
38
+ invalid_card_number: {
39
+ en: 'The card number is wrong. Please check it and try again.',
40
+ ru: 'Неправильный номер карты. Проверьте его и попробуйте ещё раз.'
41
+ },
42
+ invalid_csc: {
43
+ en: 'The security code (CVC/CVV) is wrong. Please check it and try again.',
44
+ ru: 'Неправильный код безопасности (CVC/CVV). Проверьте его и попробуйте ещё раз.'
45
+ },
46
+ issuer_unavailable: {
47
+ en: 'The bank is unavailable right now. Please try again later or use another card.',
48
+ ru: 'Банк сейчас недоступен. Попробуйте позже или используйте другую карту.'
49
+ },
50
+ payment_method_limit_exceeded: {
51
+ en: 'The limit of this payment method is exceeded. Please use another payment method.',
52
+ ru: 'Превышен лимит для этого способа оплаты. Выберите другой способ оплаты.'
53
+ },
54
+ payment_method_restriction: {
55
+ en: 'This payment method is restricted by its issuer. Please use another payment method.',
56
+ ru: 'Этот способ оплаты ограничен банком. Выберите другой способ оплаты.'
57
+ },
58
+ permission_revoked: {
59
+ en: 'The payment permission was revoked. Please use another payment method.',
60
+ ru: 'Разрешение на платёж отозвано. Выберите другой способ оплаты.'
61
+ },
62
+ internal_timeout: {
63
+ en: 'The payment could not be processed in time. Please try again.',
64
+ ru: 'Платёж не удалось обработать вовремя. Попробуйте ещё раз.'
65
+ },
66
+ expired_on_confirmation: {
67
+ en: 'The payment was not completed in time and has expired. Please try again.',
68
+ ru: 'Время на оплату вышло. Попробуйте ещё раз.'
69
+ },
70
+ canceled_by_merchant: {
71
+ en: 'The payment was canceled by the shop. Please contact us.',
72
+ ru: 'Платёж отменён магазином. Свяжитесь с нами.'
73
+ }
74
+ };
75
+ /** Buyer-friendly text for a YooKassa cancellation reason. Unknown reasons get a generic one. */ export const cancellationMessage = (reason, language = 'ru')=>(reason ? REASONS[reason] ?? GENERIC : GENERIC)[language];
76
+
77
+ //# sourceMappingURL=messages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/messages.ts"],"sourcesContent":["export type MessageLanguage = 'en' | 'ru'\n\ntype Texts = Record<MessageLanguage, string>\n\nconst GENERIC: Texts = {\n en: 'The payment was not completed. No money has been charged. You can try again or choose another payment method.',\n ru: 'Оплата не прошла, деньги не списаны. Попробуйте ещё раз или выберите другой способ оплаты.',\n}\n\nconst REASONS: Record<string, Texts> = {\n '3d_secure_failed': {\n en: 'The 3-D Secure check failed. Please try again and enter the confirmation code from your bank.',\n ru: 'Не удалось пройти проверку 3-D Secure. Попробуйте ещё раз и введите код подтверждения из банка.',\n },\n call_issuer: {\n en: 'The bank declined the payment. Please contact your bank or use another card.',\n ru: 'Банк отклонил платёж. Свяжитесь с банком или используйте другую карту.',\n },\n card_expired: {\n en: 'The card has expired. Please use another card.',\n ru: 'Срок действия карты истёк. Используйте другую карту.',\n },\n country_forbidden: {\n en: 'Payments from the country of this card are not accepted. Please use another payment method.',\n ru: 'Платежи с карт этой страны не принимаются. Выберите другой способ оплаты.',\n },\n fraud_suspected: {\n en: 'The payment was declined as suspicious. Please use another payment method.',\n ru: 'Платёж отклонён как подозрительный. Выберите другой способ оплаты.',\n },\n general_decline: {\n en: 'The bank declined the payment without giving a reason. Please contact your bank or use another card.',\n ru: 'Банк отклонил платёж без объяснения причин. Свяжитесь с банком или используйте другую карту.',\n },\n identification_required: {\n en: 'This payment method requires identification of its owner. Please use another payment method.',\n ru: 'Для этого способа оплаты нужна идентификация владельца. Выберите другой способ оплаты.',\n },\n insufficient_funds: {\n en: 'There are not enough funds. Top up the balance or use another payment method.',\n ru: 'Недостаточно средств. Пополните баланс или выберите другой способ оплаты.',\n },\n invalid_card_number: {\n en: 'The card number is wrong. Please check it and try again.',\n ru: 'Неправильный номер карты. Проверьте его и попробуйте ещё раз.',\n },\n invalid_csc: {\n en: 'The security code (CVC/CVV) is wrong. Please check it and try again.',\n ru: 'Неправильный код безопасности (CVC/CVV). Проверьте его и попробуйте ещё раз.',\n },\n issuer_unavailable: {\n en: 'The bank is unavailable right now. Please try again later or use another card.',\n ru: 'Банк сейчас недоступен. Попробуйте позже или используйте другую карту.',\n },\n payment_method_limit_exceeded: {\n en: 'The limit of this payment method is exceeded. Please use another payment method.',\n ru: 'Превышен лимит для этого способа оплаты. Выберите другой способ оплаты.',\n },\n payment_method_restriction: {\n en: 'This payment method is restricted by its issuer. Please use another payment method.',\n ru: 'Этот способ оплаты ограничен банком. Выберите другой способ оплаты.',\n },\n permission_revoked: {\n en: 'The payment permission was revoked. Please use another payment method.',\n ru: 'Разрешение на платёж отозвано. Выберите другой способ оплаты.',\n },\n internal_timeout: {\n en: 'The payment could not be processed in time. Please try again.',\n ru: 'Платёж не удалось обработать вовремя. Попробуйте ещё раз.',\n },\n expired_on_confirmation: {\n en: 'The payment was not completed in time and has expired. Please try again.',\n ru: 'Время на оплату вышло. Попробуйте ещё раз.',\n },\n canceled_by_merchant: {\n en: 'The payment was canceled by the shop. Please contact us.',\n ru: 'Платёж отменён магазином. Свяжитесь с нами.',\n },\n}\n\n/** Buyer-friendly text for a YooKassa cancellation reason. Unknown reasons get a generic one. */\nexport const cancellationMessage = (\n reason: string | null | undefined,\n language: MessageLanguage = 'ru',\n): string => (reason ? (REASONS[reason] ?? GENERIC) : GENERIC)[language]\n"],"names":["GENERIC","en","ru","REASONS","call_issuer","card_expired","country_forbidden","fraud_suspected","general_decline","identification_required","insufficient_funds","invalid_card_number","invalid_csc","issuer_unavailable","payment_method_limit_exceeded","payment_method_restriction","permission_revoked","internal_timeout","expired_on_confirmation","canceled_by_merchant","cancellationMessage","reason","language"],"mappings":"AAIA,MAAMA,UAAiB;IACrBC,IAAI;IACJC,IAAI;AACN;AAEA,MAAMC,UAAiC;IACrC,oBAAoB;QAClBF,IAAI;QACJC,IAAI;IACN;IACAE,aAAa;QACXH,IAAI;QACJC,IAAI;IACN;IACAG,cAAc;QACZJ,IAAI;QACJC,IAAI;IACN;IACAI,mBAAmB;QACjBL,IAAI;QACJC,IAAI;IACN;IACAK,iBAAiB;QACfN,IAAI;QACJC,IAAI;IACN;IACAM,iBAAiB;QACfP,IAAI;QACJC,IAAI;IACN;IACAO,yBAAyB;QACvBR,IAAI;QACJC,IAAI;IACN;IACAQ,oBAAoB;QAClBT,IAAI;QACJC,IAAI;IACN;IACAS,qBAAqB;QACnBV,IAAI;QACJC,IAAI;IACN;IACAU,aAAa;QACXX,IAAI;QACJC,IAAI;IACN;IACAW,oBAAoB;QAClBZ,IAAI;QACJC,IAAI;IACN;IACAY,+BAA+B;QAC7Bb,IAAI;QACJC,IAAI;IACN;IACAa,4BAA4B;QAC1Bd,IAAI;QACJC,IAAI;IACN;IACAc,oBAAoB;QAClBf,IAAI;QACJC,IAAI;IACN;IACAe,kBAAkB;QAChBhB,IAAI;QACJC,IAAI;IACN;IACAgB,yBAAyB;QACvBjB,IAAI;QACJC,IAAI;IACN;IACAiB,sBAAsB;QACpBlB,IAAI;QACJC,IAAI;IACN;AACF;AAEA,+FAA+F,GAC/F,OAAO,MAAMkB,sBAAsB,CACjCC,QACAC,WAA4B,IAAI,GACrB,AAACD,CAAAA,SAAUlB,OAAO,CAACkB,OAAO,IAAIrB,UAAWA,OAAM,CAAE,CAACsB,SAAS,CAAA"}
@@ -0,0 +1,57 @@
1
+ export type TaxSystemCode = 1 | 2 | 3 | 4 | 5 | 6;
2
+ export type ReceiptOptions = {
3
+ /**
4
+ * Tax system of the shop (1 general, 2 USN income, 3 USN income-expenses,
5
+ * 4 ENVD, 5 ESN, 6 patent). Send it only when the shop has several tax systems.
6
+ */
7
+ taxSystemCode?: TaxSystemCode;
8
+ /** VAT code used when a product has none. 1 = without VAT. Default 1. */
9
+ defaultVatCode?: number;
10
+ /** Default "commodity". */
11
+ paymentSubject?: string;
12
+ /** Default "full_payment". */
13
+ paymentMode?: string;
14
+ /** VAT code of the delivery line. Default: `defaultVatCode`. */
15
+ deliveryVatCode?: number;
16
+ };
17
+ /** One purchased line. `unitAmount` is in minor units. */
18
+ export type OrderLine = {
19
+ description: string;
20
+ quantity: number;
21
+ unitAmount: number;
22
+ vatCode?: number;
23
+ /** Overrides the subject of payment for this line (the delivery is a "service"). */
24
+ paymentSubject?: string;
25
+ };
26
+ export declare const isVatCode: (value: unknown) => value is number;
27
+ export declare const sumLines: (lines: OrderLine[]) => number;
28
+ export declare const truncate: (value: string, max: number) => string;
29
+ type BuildReceiptArgs = {
30
+ lines: OrderLine[];
31
+ currency: string;
32
+ decimals?: number;
33
+ customerEmail: string;
34
+ options: ReceiptOptions;
35
+ };
36
+ /**
37
+ * Builds the `receipt` object of a YooKassa payment. The sum of all lines is the
38
+ * payment amount, so the caller must compute the payment amount from the same lines.
39
+ */
40
+ export declare const buildReceipt: ({ lines, currency, decimals, customerEmail, options, }: BuildReceiptArgs) => {
41
+ tax_system_code?: TaxSystemCode | undefined;
42
+ customer: {
43
+ email: string;
44
+ };
45
+ items: {
46
+ description: string;
47
+ quantity: number;
48
+ amount: {
49
+ value: string;
50
+ currency: string;
51
+ };
52
+ vat_code: number;
53
+ payment_mode: string;
54
+ payment_subject: string;
55
+ }[];
56
+ };
57
+ export {};
@@ -0,0 +1,43 @@
1
+ import { formatAmount } from './amount.js';
2
+ const MAX_DESCRIPTION_LENGTH = 128;
3
+ export const isVatCode = (value)=>typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= 12;
4
+ export const sumLines = (lines)=>lines.reduce((total, line)=>total + line.unitAmount * line.quantity, 0);
5
+ export const truncate = (value, max)=>value.length <= max ? value : `${value.slice(0, max - 1)}…`;
6
+ /**
7
+ * Builds the `receipt` object of a YooKassa payment. The sum of all lines is the
8
+ * payment amount, so the caller must compute the payment amount from the same lines.
9
+ */ export const buildReceipt = ({ lines, currency, decimals = 2, customerEmail, options })=>{
10
+ if (lines.length === 0) throw new Error('Receipt needs at least one item');
11
+ if (lines.length > 100) throw new Error('A receipt cannot have more than 100 items');
12
+ const defaultVatCode = options.defaultVatCode ?? 1;
13
+ if (!isVatCode(defaultVatCode)) throw new Error('defaultVatCode must be an integer from 1 to 12');
14
+ return {
15
+ customer: {
16
+ email: customerEmail
17
+ },
18
+ items: lines.map((line)=>{
19
+ if (!Number.isInteger(line.quantity) || line.quantity < 1) {
20
+ throw new Error('Receipt item quantity must be a positive integer');
21
+ }
22
+ if (!Number.isSafeInteger(line.unitAmount) || line.unitAmount < 1) {
23
+ throw new Error('Receipt item price must be a positive amount');
24
+ }
25
+ return {
26
+ description: truncate(line.description, MAX_DESCRIPTION_LENGTH),
27
+ quantity: line.quantity,
28
+ amount: {
29
+ value: formatAmount(line.unitAmount, decimals),
30
+ currency
31
+ },
32
+ vat_code: isVatCode(line.vatCode) ? line.vatCode : defaultVatCode,
33
+ payment_mode: options.paymentMode ?? 'full_payment',
34
+ payment_subject: line.paymentSubject ?? options.paymentSubject ?? 'commodity'
35
+ };
36
+ }),
37
+ ...options.taxSystemCode ? {
38
+ tax_system_code: options.taxSystemCode
39
+ } : {}
40
+ };
41
+ };
42
+
43
+ //# sourceMappingURL=receipt.js.map