@payloadcms/plugin-ecommerce 4.0.0-internal.77191e5 → 4.0.0-internal.7d5c665
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/dist/collections/addresses/createAddressesCollection.d.ts.map +1 -1
- package/dist/collections/addresses/createAddressesCollection.js +1 -0
- package/dist/collections/addresses/createAddressesCollection.js.map +1 -1
- package/dist/collections/carts/beforeChange.d.ts.map +1 -1
- package/dist/collections/carts/beforeChange.js +2 -0
- package/dist/collections/carts/beforeChange.js.map +1 -1
- package/dist/collections/carts/createCartsCollection.d.ts.map +1 -1
- package/dist/collections/carts/createCartsCollection.js +1 -0
- package/dist/collections/carts/createCartsCollection.js.map +1 -1
- package/dist/collections/orders/createOrdersCollection.d.ts.map +1 -1
- package/dist/collections/orders/createOrdersCollection.js +1 -0
- package/dist/collections/orders/createOrdersCollection.js.map +1 -1
- package/dist/collections/products/createProductsCollection.d.ts.map +1 -1
- package/dist/collections/products/createProductsCollection.js +1 -0
- package/dist/collections/products/createProductsCollection.js.map +1 -1
- package/dist/collections/transactions/createTransactionsCollection.d.ts.map +1 -1
- package/dist/collections/transactions/createTransactionsCollection.js +1 -0
- package/dist/collections/transactions/createTransactionsCollection.js.map +1 -1
- package/dist/collections/variants/createVariantOptionsCollection.d.ts.map +1 -1
- package/dist/collections/variants/createVariantOptionsCollection.js +1 -0
- package/dist/collections/variants/createVariantOptionsCollection.js.map +1 -1
- package/dist/collections/variants/createVariantTypesCollection.d.ts.map +1 -1
- package/dist/collections/variants/createVariantTypesCollection.js +1 -0
- package/dist/collections/variants/createVariantTypesCollection.js.map +1 -1
- package/dist/collections/variants/createVariantsCollection/hooks/beforeChange.d.ts.map +1 -1
- package/dist/collections/variants/createVariantsCollection/hooks/beforeChange.js +2 -0
- package/dist/collections/variants/createVariantsCollection/hooks/beforeChange.js.map +1 -1
- package/dist/collections/variants/createVariantsCollection/hooks/validateOptions.d.ts.map +1 -1
- package/dist/collections/variants/createVariantsCollection/hooks/validateOptions.js +1 -0
- package/dist/collections/variants/createVariantsCollection/hooks/validateOptions.js.map +1 -1
- package/dist/collections/variants/createVariantsCollection/index.d.ts.map +1 -1
- package/dist/collections/variants/createVariantsCollection/index.js +1 -0
- package/dist/collections/variants/createVariantsCollection/index.js.map +1 -1
- package/dist/endpoints/confirmOrder.js +7 -0
- package/dist/endpoints/confirmOrder.js.map +1 -1
- package/dist/endpoints/initiatePayment.d.ts.map +1 -1
- package/dist/endpoints/initiatePayment.js +2 -0
- package/dist/endpoints/initiatePayment.js.map +1 -1
- package/dist/payments/adapters/stripe/confirmOrder.js +1 -0
- package/dist/payments/adapters/stripe/confirmOrder.js.map +1 -1
- package/dist/payments/adapters/stripe/initiatePayment.d.ts.map +1 -1
- package/dist/payments/adapters/stripe/initiatePayment.js +1 -0
- package/dist/payments/adapters/stripe/initiatePayment.js.map +1 -1
- package/dist/ui/VariantOptionsSelector/index.d.ts.map +1 -1
- package/dist/ui/VariantOptionsSelector/index.js +3 -1
- package/dist/ui/VariantOptionsSelector/index.js.map +1 -1
- package/package.json +9 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAddressesCollection.d.ts","sourceRoot":"","sources":["../../../src/collections/addresses/createAddressesCollection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAMrE,KAAK,KAAK,GAAG;IACX,MAAM,EAAE,IAAI,CACV,YAAY,EACZ,yBAAyB,GAAG,SAAS,GAAG,iBAAiB,GAAG,YAAY,GAAG,iBAAiB,CAC7F,CAAA;IACD;;OAEG;IACH,aAAa,EAAE,KAAK,EAAE,CAAA;IACtB;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,kBAAkB,CAAC,EAAE,WAAW,EAAE,CAAA;CACnC,CAAA;AAED,eAAO,MAAM,yBAAyB,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,
|
|
1
|
+
{"version":3,"file":"createAddressesCollection.d.ts","sourceRoot":"","sources":["../../../src/collections/addresses/createAddressesCollection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAMrE,KAAK,KAAK,GAAG;IACX,MAAM,EAAE,IAAI,CACV,YAAY,EACZ,yBAAyB,GAAG,SAAS,GAAG,iBAAiB,GAAG,YAAY,GAAG,iBAAiB,CAC7F,CAAA;IACD;;OAEG;IACH,aAAa,EAAE,KAAK,EAAE,CAAA;IACtB;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,kBAAkB,CAAC,EAAE,WAAW,EAAE,CAAA;CACnC,CAAA;AAED,eAAO,MAAM,yBAAyB,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,gBA4EzD,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/addresses/createAddressesCollection.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { AccessConfig, CountryType } from '../../types/index.js'\n\nimport { accessOR } from '../../utilities/accessComposition.js'\nimport { defaultCountries } from './defaultCountries.js'\nimport { beforeChange } from './hooks/beforeChange.js'\n\ntype Props = {\n access: Pick<\n AccessConfig,\n 'customerOnlyFieldAccess' | 'isAdmin' | 'isAuthenticated' | 'isCustomer' | 'isDocumentOwner'\n >\n /**\n * Array of fields used for capturing the address data. Use this over overrides to customise the fields here as it's reused across the plugin.\n */\n addressFields: Field[]\n /**\n * Slug of the customers collection, defaults to 'users'.\n */\n customersSlug?: string\n supportedCountries?: CountryType[]\n}\n\nexport const createAddressesCollection: (props: Props) => CollectionConfig = (props) => {\n const { access, addressFields, customersSlug = 'users' } = props || {}\n\n const { supportedCountries: supportedCountriesFromProps } = props || {}\n const supportedCountries = supportedCountriesFromProps || defaultCountries\n const hasOnlyOneCountry = supportedCountries && supportedCountries.length === 1\n\n const fields: Field[] = [\n {\n name: 'customer',\n type: 'relationship',\n admin: {\n position: 'sidebar',\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:customer'),\n relationTo: customersSlug,\n },\n ...addressFields.map((field) => {\n if ('name' in field && field.name === 'country') {\n return {\n name: 'country',\n type: 'select',\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:addressCountry'),\n options: supportedCountries || defaultCountries,\n required: true,\n ...(supportedCountries && supportedCountries?.[0] && hasOnlyOneCountry\n ? {\n defaultValue: supportedCountries?.[0].value,\n }\n : {}),\n } as Field\n }\n\n return field\n }),\n ]\n\n const baseConfig: CollectionConfig = {\n slug: 'addresses',\n access: {\n create: access.isAuthenticated,\n delete: accessOR(access.isAdmin, access.isDocumentOwner),\n read: accessOR(access.isAdmin, access.isDocumentOwner),\n update: accessOR(access.isAdmin, access.isDocumentOwner),\n },\n admin: {\n description: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:addressesCollectionDescription'),\n group: 'Ecommerce',\n hidden: true,\n useAsTitle: 'createdAt',\n },\n fields,\n hooks: {\n beforeChange: [\n beforeChange({ isCustomer: access.isCustomer ?? access.customerOnlyFieldAccess }),\n ],\n },\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:addresses'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:address'),\n },\n timestamps: true,\n }\n\n return { ...baseConfig }\n}\n"],"names":["accessOR","defaultCountries","beforeChange","createAddressesCollection","props","access","addressFields","customersSlug","supportedCountries","supportedCountriesFromProps","hasOnlyOneCountry","length","fields","name","type","admin","position","label","t","relationTo","map","field","options","required","defaultValue","value","baseConfig","slug","create","isAuthenticated","delete","isAdmin","isDocumentOwner","read","update","description","group","hidden","useAsTitle","hooks","isCustomer","customerOnlyFieldAccess","labels","plural","singular","timestamps"],"mappings":"AAIA,SAASA,QAAQ,QAAQ,uCAAsC;AAC/D,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,YAAY,QAAQ,0BAAyB;AAkBtD,OAAO,MAAMC,4BAAgE,CAACC;IAC5E,MAAM,EAAEC,MAAM,EAAEC,aAAa,EAAEC,gBAAgB,OAAO,EAAE,GAAGH,SAAS,CAAC;IAErE,MAAM,EAAEI,oBAAoBC,2BAA2B,EAAE,GAAGL,SAAS,CAAC;IACtE,MAAMI,qBAAqBC,+BAA+BR;IAC1D,MAAMS,oBAAoBF,sBAAsBA,mBAAmBG,MAAM,KAAK;IAE9E,MAAMC,SAAkB;QACtB;YACEC,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLC,UAAU;YACZ;YACAC,OAAO,CAAC,EAAEC,CAAC,EAAE,GACX,+DAA+D;gBAC/DA,EAAE;YACJC,YAAYZ;QACd;WACGD,cAAcc,GAAG,CAAC,CAACC;YACpB,IAAI,UAAUA,SAASA,MAAMR,IAAI,KAAK,WAAW;gBAC/C,OAAO;oBACLA,MAAM;oBACNC,MAAM;oBACNG,OAAO,CAAC,EAAEC,CAAC,EAAE,GACX,+DAA+D;wBAC/DA,EAAE;oBACJI,SAASd,sBAAsBP;oBAC/BsB,UAAU;oBACV,GAAIf,sBAAsBA,oBAAoB,CAAC,EAAE,IAAIE,oBACjD;wBACEc,cAAchB,oBAAoB,CAAC,EAAE,CAACiB;oBACxC,IACA,CAAC,CAAC;gBACR;YACF;YAEA,OAAOJ;QACT;KACD;IAED,MAAMK,aAA+B;QACnCC,MAAM;QACNtB,QAAQ;YACNuB,QAAQvB,OAAOwB,eAAe;YAC9BC,QAAQ9B,SAASK,OAAO0B,OAAO,EAAE1B,OAAO2B,eAAe;YACvDC,MAAMjC,SAASK,OAAO0B,OAAO,EAAE1B,OAAO2B,eAAe;YACrDE,QAAQlC,SAASK,OAAO0B,OAAO,EAAE1B,OAAO2B,eAAe;QACzD;QACAjB,OAAO;YACLoB,aAAa,CAAC,EAAEjB,CAAC,EAAE,GACjB,+DAA+D;gBAC/DA,EAAE;YACJkB,OAAO;YACPC,QAAQ;YACRC,YAAY;QACd;
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/addresses/createAddressesCollection.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { AccessConfig, CountryType } from '../../types/index.js'\n\nimport { accessOR } from '../../utilities/accessComposition.js'\nimport { defaultCountries } from './defaultCountries.js'\nimport { beforeChange } from './hooks/beforeChange.js'\n\ntype Props = {\n access: Pick<\n AccessConfig,\n 'customerOnlyFieldAccess' | 'isAdmin' | 'isAuthenticated' | 'isCustomer' | 'isDocumentOwner'\n >\n /**\n * Array of fields used for capturing the address data. Use this over overrides to customise the fields here as it's reused across the plugin.\n */\n addressFields: Field[]\n /**\n * Slug of the customers collection, defaults to 'users'.\n */\n customersSlug?: string\n supportedCountries?: CountryType[]\n}\n\nexport const createAddressesCollection: (props: Props) => CollectionConfig = (props) => {\n const { access, addressFields, customersSlug = 'users' } = props || {}\n\n const { supportedCountries: supportedCountriesFromProps } = props || {}\n const supportedCountries = supportedCountriesFromProps || defaultCountries\n const hasOnlyOneCountry = supportedCountries && supportedCountries.length === 1\n\n const fields: Field[] = [\n {\n name: 'customer',\n type: 'relationship',\n admin: {\n position: 'sidebar',\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:customer'),\n relationTo: customersSlug,\n },\n ...addressFields.map((field) => {\n if ('name' in field && field.name === 'country') {\n return {\n name: 'country',\n type: 'select',\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:addressCountry'),\n options: supportedCountries || defaultCountries,\n required: true,\n ...(supportedCountries && supportedCountries?.[0] && hasOnlyOneCountry\n ? {\n defaultValue: supportedCountries?.[0].value,\n }\n : {}),\n } as Field\n }\n\n return field\n }),\n ]\n\n const baseConfig: CollectionConfig = {\n slug: 'addresses',\n access: {\n create: access.isAuthenticated,\n delete: accessOR(access.isAdmin, access.isDocumentOwner),\n read: accessOR(access.isAdmin, access.isDocumentOwner),\n update: accessOR(access.isAdmin, access.isDocumentOwner),\n },\n admin: {\n description: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:addressesCollectionDescription'),\n group: 'Ecommerce',\n hidden: true,\n useAsTitle: 'createdAt',\n },\n authorship: false,\n fields,\n hooks: {\n beforeChange: [\n beforeChange({ isCustomer: access.isCustomer ?? access.customerOnlyFieldAccess }),\n ],\n },\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:addresses'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:address'),\n },\n timestamps: true,\n }\n\n return { ...baseConfig }\n}\n"],"names":["accessOR","defaultCountries","beforeChange","createAddressesCollection","props","access","addressFields","customersSlug","supportedCountries","supportedCountriesFromProps","hasOnlyOneCountry","length","fields","name","type","admin","position","label","t","relationTo","map","field","options","required","defaultValue","value","baseConfig","slug","create","isAuthenticated","delete","isAdmin","isDocumentOwner","read","update","description","group","hidden","useAsTitle","authorship","hooks","isCustomer","customerOnlyFieldAccess","labels","plural","singular","timestamps"],"mappings":"AAIA,SAASA,QAAQ,QAAQ,uCAAsC;AAC/D,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,YAAY,QAAQ,0BAAyB;AAkBtD,OAAO,MAAMC,4BAAgE,CAACC;IAC5E,MAAM,EAAEC,MAAM,EAAEC,aAAa,EAAEC,gBAAgB,OAAO,EAAE,GAAGH,SAAS,CAAC;IAErE,MAAM,EAAEI,oBAAoBC,2BAA2B,EAAE,GAAGL,SAAS,CAAC;IACtE,MAAMI,qBAAqBC,+BAA+BR;IAC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AAC,EAAE3B,CAAC,EAAE,GACd,+DAA+D;gBAC/DA,EAAE;QACN;QACA4B,YAAY;IACd;IAEA,OAAO;QAAE,GAAGpB,UAAU;IAAC;AACzB,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"beforeChange.d.ts","sourceRoot":"","sources":["../../../src/collections/carts/beforeChange.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,SAAS,CAAA;AAIzD,KAAK,KAAK,GAAG;IACX,YAAY,EAAE,MAAM,CAAA;IACpB,YAAY,EAAE,MAAM,CAAA;CACrB,CAAA;AAED,eAAO,MAAM,gBAAgB,EAAE,CAAC,IAAI,EAAE,KAAK,KAAK,
|
|
1
|
+
{"version":3,"file":"beforeChange.d.ts","sourceRoot":"","sources":["../../../src/collections/carts/beforeChange.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,SAAS,CAAA;AAIzD,KAAK,KAAK,GAAG;IACX,YAAY,EAAE,MAAM,CAAA;IACpB,YAAY,EAAE,MAAM,CAAA;CACrB,CAAA;AAED,eAAO,MAAM,gBAAgB,EAAE,CAAC,IAAI,EAAE,KAAK,KAAK,0BA0D7C,CAAA"}
|
|
@@ -22,6 +22,7 @@ export const beforeChangeCart = ({ productsSlug, variantsSlug })=>async ({ data,
|
|
|
22
22
|
id,
|
|
23
23
|
collection: variantsSlug,
|
|
24
24
|
depth: 0,
|
|
25
|
+
overrideAccess: true,
|
|
25
26
|
select: {
|
|
26
27
|
[priceField]: true
|
|
27
28
|
}
|
|
@@ -33,6 +34,7 @@ export const beforeChangeCart = ({ productsSlug, variantsSlug })=>async ({ data,
|
|
|
33
34
|
id,
|
|
34
35
|
collection: productsSlug,
|
|
35
36
|
depth: 0,
|
|
37
|
+
overrideAccess: true,
|
|
36
38
|
select: {
|
|
37
39
|
[priceField]: true
|
|
38
40
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/carts/beforeChange.ts"],"sourcesContent":["import type { CollectionBeforeChangeHook } from 'payload'\n\nimport crypto from 'crypto'\n\ntype Props = {\n productsSlug: string\n variantsSlug: string\n}\n\nexport const beforeChangeCart: (args: Props) => CollectionBeforeChangeHook =\n ({ productsSlug, variantsSlug }) =>\n async ({ data, operation, req }) => {\n // Generate a secret for guest cart access on creation\n if (operation === 'create' && !data.customer && !data.secret) {\n // Generate a cryptographically secure random string\n const secret = crypto.randomBytes(20).toString('hex')\n data.secret = secret\n\n // Store in context so afterRead hook can include it in the creation response\n if (!req.context) {\n req.context = {}\n }\n req.context.newCartSecret = secret\n }\n\n // Update subtotal based on items in the cart\n if (data.items && Array.isArray(data.items)) {\n const priceField = `priceIn${data.currency}`\n\n let subtotal = 0\n\n for (const item of data.items) {\n if (item.variant) {\n const id = typeof item.variant === 'object' ? item.variant.id : item.variant\n\n const variant = await req.payload.findByID({\n id,\n collection: variantsSlug,\n depth: 0,\n select: {\n [priceField]: true,\n },\n })\n\n subtotal += variant[priceField] * item.quantity\n } else {\n const id = typeof item.product === 'object' ? item.product.id : item.product\n\n const product = await req.payload.findByID({\n id,\n collection: productsSlug,\n depth: 0,\n select: {\n [priceField]: true,\n },\n })\n\n subtotal += product[priceField] * item.quantity\n }\n }\n\n data.subtotal = subtotal\n } else {\n data.subtotal = 0\n }\n }\n"],"names":["crypto","beforeChangeCart","productsSlug","variantsSlug","data","operation","req","customer","secret","randomBytes","toString","context","newCartSecret","items","Array","isArray","priceField","currency","subtotal","item","variant","id","payload","findByID","collection","depth","select","quantity","product"],"mappings":"AAEA,OAAOA,YAAY,SAAQ;AAO3B,OAAO,MAAMC,mBACX,CAAC,EAAEC,YAAY,EAAEC,YAAY,EAAE,GAC/B,OAAO,EAAEC,IAAI,EAAEC,SAAS,EAAEC,GAAG,EAAE;QAC7B,sDAAsD;QACtD,IAAID,cAAc,YAAY,CAACD,KAAKG,QAAQ,IAAI,CAACH,KAAKI,MAAM,EAAE;YAC5D,oDAAoD;YACpD,MAAMA,SAASR,OAAOS,WAAW,CAAC,IAAIC,QAAQ,CAAC;YAC/CN,KAAKI,MAAM,GAAGA;YAEd,6EAA6E;YAC7E,IAAI,CAACF,IAAIK,OAAO,EAAE;gBAChBL,IAAIK,OAAO,GAAG,CAAC;YACjB;YACAL,IAAIK,OAAO,CAACC,aAAa,GAAGJ;QAC9B;QAEA,6CAA6C;QAC7C,IAAIJ,KAAKS,KAAK,IAAIC,MAAMC,OAAO,CAACX,KAAKS,KAAK,GAAG;YAC3C,MAAMG,aAAa,CAAC,OAAO,EAAEZ,KAAKa,QAAQ,EAAE;YAE5C,IAAIC,WAAW;YAEf,KAAK,MAAMC,QAAQf,KAAKS,KAAK,CAAE;gBAC7B,IAAIM,KAAKC,OAAO,EAAE;oBAChB,MAAMC,KAAK,OAAOF,KAAKC,OAAO,KAAK,WAAWD,KAAKC,OAAO,CAACC,EAAE,GAAGF,KAAKC,OAAO;oBAE5E,MAAMA,UAAU,MAAMd,IAAIgB,OAAO,CAACC,QAAQ,CAAC;wBACzCF;wBACAG,YAAYrB;wBACZsB,OAAO;wBACPC,QAAQ;4BACN,
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/carts/beforeChange.ts"],"sourcesContent":["import type { CollectionBeforeChangeHook } from 'payload'\n\nimport crypto from 'crypto'\n\ntype Props = {\n productsSlug: string\n variantsSlug: string\n}\n\nexport const beforeChangeCart: (args: Props) => CollectionBeforeChangeHook =\n ({ productsSlug, variantsSlug }) =>\n async ({ data, operation, req }) => {\n // Generate a secret for guest cart access on creation\n if (operation === 'create' && !data.customer && !data.secret) {\n // Generate a cryptographically secure random string\n const secret = crypto.randomBytes(20).toString('hex')\n data.secret = secret\n\n // Store in context so afterRead hook can include it in the creation response\n if (!req.context) {\n req.context = {}\n }\n req.context.newCartSecret = secret\n }\n\n // Update subtotal based on items in the cart\n if (data.items && Array.isArray(data.items)) {\n const priceField = `priceIn${data.currency}`\n\n let subtotal = 0\n\n for (const item of data.items) {\n if (item.variant) {\n const id = typeof item.variant === 'object' ? item.variant.id : item.variant\n\n const variant = await req.payload.findByID({\n id,\n collection: variantsSlug,\n depth: 0,\n overrideAccess: true,\n select: {\n [priceField]: true,\n },\n })\n\n subtotal += variant[priceField] * item.quantity\n } else {\n const id = typeof item.product === 'object' ? item.product.id : item.product\n\n const product = await req.payload.findByID({\n id,\n collection: productsSlug,\n depth: 0,\n overrideAccess: true,\n select: {\n [priceField]: true,\n },\n })\n\n subtotal += product[priceField] * item.quantity\n }\n }\n\n data.subtotal = subtotal\n } else {\n data.subtotal = 0\n }\n }\n"],"names":["crypto","beforeChangeCart","productsSlug","variantsSlug","data","operation","req","customer","secret","randomBytes","toString","context","newCartSecret","items","Array","isArray","priceField","currency","subtotal","item","variant","id","payload","findByID","collection","depth","overrideAccess","select","quantity","product"],"mappings":"AAEA,OAAOA,YAAY,SAAQ;AAO3B,OAAO,MAAMC,mBACX,CAAC,EAAEC,YAAY,EAAEC,YAAY,EAAE,GAC/B,OAAO,EAAEC,IAAI,EAAEC,SAAS,EAAEC,GAAG,EAAE;QAC7B,sDAAsD;QACtD,IAAID,cAAc,YAAY,CAACD,KAAKG,QAAQ,IAAI,CAACH,KAAKI,MAAM,EAAE;YAC5D,oDAAoD;YACpD,MAAMA,SAASR,OAAOS,WAAW,CAAC,IAAIC,QAAQ,CAAC;YAC/CN,KAAKI,MAAM,GAAGA;YAEd,6EAA6E;YAC7E,IAAI,CAACF,IAAIK,OAAO,EAAE;gBAChBL,IAAIK,OAAO,GAAG,CAAC;YACjB;YACAL,IAAIK,OAAO,CAACC,aAAa,GAAGJ;QAC9B;QAEA,6CAA6C;QAC7C,IAAIJ,KAAKS,KAAK,IAAIC,MAAMC,OAAO,CAACX,KAAKS,KAAK,GAAG;YAC3C,MAAMG,aAAa,CAAC,OAAO,EAAEZ,KAAKa,QAAQ,EAAE;YAE5C,IAAIC,WAAW;YAEf,KAAK,MAAMC,QAAQf,KAAKS,KAAK,CAAE;gBAC7B,IAAIM,KAAKC,OAAO,EAAE;oBAChB,MAAMC,KAAK,OAAOF,KAAKC,OAAO,KAAK,WAAWD,KAAKC,OAAO,CAACC,EAAE,GAAGF,KAAKC,OAAO;oBAE5E,MAAMA,UAAU,MAAMd,IAAIgB,OAAO,CAACC,QAAQ,CAAC;wBACzCF;wBACAG,YAAYrB;wBACZsB,OAAO;wBACPC,gBAAgB;wBAChBC,QAAQ;4BACN,CAACX,WAAW,EAAE;wBAChB;oBACF;oBAEAE,YAAYE,OAAO,CAACJ,WAAW,GAAGG,KAAKS,QAAQ;gBACjD,OAAO;oBACL,MAAMP,KAAK,OAAOF,KAAKU,OAAO,KAAK,WAAWV,KAAKU,OAAO,CAACR,EAAE,GAAGF,KAAKU,OAAO;oBAE5E,MAAMA,UAAU,MAAMvB,IAAIgB,OAAO,CAACC,QAAQ,CAAC;wBACzCF;wBACAG,YAAYtB;wBACZuB,OAAO;wBACPC,gBAAgB;wBAChBC,QAAQ;4BACN,CAACX,WAAW,EAAE;wBAChB;oBACF;oBAEAE,YAAYW,OAAO,CAACb,WAAW,GAAGG,KAAKS,QAAQ;gBACjD;YACF;YAEAxB,KAAKc,QAAQ,GAAGA;QAClB,OAAO;YACLd,KAAKc,QAAQ,GAAG;QAClB;IACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createCartsCollection.d.ts","sourceRoot":"","sources":["../../../src/collections/carts/createCartsCollection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAU,gBAAgB,EAAS,MAAM,SAAS,CAAA;AAE9D,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAA;AAC1E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AAe5D,KAAK,KAAK,GAAG;IACX,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE,SAAS,GAAG,iBAAiB,GAAG,iBAAiB,CAAC,CAAA;IACvF;;;OAGG;IACH,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB;;;;;;;;;;;;;;;;;;OAkBG;IACH,eAAe,CAAC,EAAE,eAAe,CAAA;IACjC,gBAAgB,CAAC,EAAE,gBAAgB,CAAA;IACnC;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB;;;OAGG;IACH,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB,CAAA;AAED,eAAO,MAAM,qBAAqB,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,
|
|
1
|
+
{"version":3,"file":"createCartsCollection.d.ts","sourceRoot":"","sources":["../../../src/collections/carts/createCartsCollection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAU,gBAAgB,EAAS,MAAM,SAAS,CAAA;AAE9D,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAA;AAC1E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AAe5D,KAAK,KAAK,GAAG;IACX,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE,SAAS,GAAG,iBAAiB,GAAG,iBAAiB,CAAC,CAAA;IACvF;;;OAGG;IACH,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB;;;;;;;;;;;;;;;;;;OAkBG;IACH,eAAe,CAAC,EAAE,eAAe,CAAA;IACjC,gBAAgB,CAAC,EAAE,gBAAgB,CAAA;IACnC;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB;;;OAGG;IACH,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB,CAAA;AAED,eAAO,MAAM,qBAAqB,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,gBAsMrD,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/carts/createCartsCollection.ts"],"sourcesContent":["import type { Access, CollectionConfig, Field } from 'payload'\n\nimport type { AccessConfig, CurrenciesConfig } from '../../types/index.js'\nimport type { CartItemMatcher } from './operations/types.js'\n\nimport { amountField } from '../../fields/amountField.js'\nimport { cartItemsField } from '../../fields/cartItemsField.js'\nimport { currencyField } from '../../fields/currencyField.js'\nimport { accessOR, conditional } from '../../utilities/accessComposition.js'\nimport { beforeChangeCart } from './beforeChange.js'\nimport { addItemEndpoint } from './endpoints/addItem.js'\nimport { clearCartEndpoint } from './endpoints/clearCart.js'\nimport { mergeCartEndpoint } from './endpoints/mergeCart.js'\nimport { removeItemEndpoint } from './endpoints/removeItem.js'\nimport { updateItemEndpoint } from './endpoints/updateItem.js'\nimport { hasCartSecretAccess } from './hasCartSecretAccess.js'\nimport { statusBeforeRead } from './statusBeforeRead.js'\n\ntype Props = {\n access: Pick<Required<AccessConfig>, 'isAdmin' | 'isAuthenticated' | 'isDocumentOwner'>\n /**\n * Allow guest (unauthenticated) users to create carts.\n * Defaults to false.\n */\n allowGuestCarts?: boolean\n /**\n * Custom function to determine if two cart items should be considered the same.\n * When items match, their quantities are combined instead of creating separate entries.\n *\n * Use this to add custom uniqueness criteria beyond product and variant IDs.\n *\n * @default defaultCartItemMatcher (matches by product and variant ID only)\n *\n * @example\n * ```ts\n * cartItemMatcher: ({ existingItem, newItem }) => {\n * // Match by product, variant, AND custom delivery option\n * const productMatch = existingItem.product === newItem.product\n * const variantMatch = existingItem.variant === newItem.variant\n * const deliveryMatch = existingItem.deliveryOption === newItem.deliveryOption\n * return productMatch && variantMatch && deliveryMatch\n * }\n * ```\n */\n cartItemMatcher?: CartItemMatcher\n currenciesConfig?: CurrenciesConfig\n /**\n * Slug of the customers collection, defaults to 'users'.\n */\n customersSlug?: string\n /**\n * Enables support for variants in the cart.\n * Defaults to false.\n */\n enableVariants?: boolean\n /**\n * Slug of the products collection, defaults to 'products'.\n */\n productsSlug?: string\n /**\n * Slug of the variants collection, defaults to 'variants'.\n */\n variantsSlug?: string\n}\n\nexport const createCartsCollection: (props: Props) => CollectionConfig = (props) => {\n const {\n access,\n allowGuestCarts = false,\n cartItemMatcher,\n currenciesConfig,\n customersSlug = 'users',\n enableVariants = false,\n productsSlug = 'products',\n variantsSlug = 'variants',\n } = props || {}\n\n const cartsSlug = 'carts'\n\n const fields: Field[] = [\n cartItemsField({\n enableVariants,\n overrides: {\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:items'),\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:items'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:item'),\n },\n },\n productsSlug,\n variantsSlug,\n }),\n {\n name: 'secret',\n type: 'text',\n access: {\n create: () => false, // Users can't set it manually\n read: () => false, // Never readable via field access (only through afterRead hook)\n update: () => false, // Users can't update it\n },\n admin: {\n hidden: true,\n position: 'sidebar',\n readOnly: true,\n },\n index: true,\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:cartSecret'),\n },\n {\n name: 'customer',\n type: 'relationship',\n admin: {\n position: 'sidebar',\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:customer'),\n relationTo: customersSlug,\n },\n {\n name: 'purchasedAt',\n type: 'date',\n admin: {\n date: { pickerAppearance: 'dayAndTime' },\n position: 'sidebar',\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:purchasedAt'),\n },\n {\n name: 'status',\n type: 'select',\n admin: {\n position: 'sidebar',\n readOnly: true,\n },\n hooks: {\n afterRead: [statusBeforeRead],\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:status'),\n options: [\n {\n // @ts-expect-error - translations are not typed in plugins yet\n label: ({ t }) => t('plugin-ecommerce:active'),\n value: 'active',\n },\n {\n // @ts-expect-error - translations are not typed in plugins yet\n label: ({ t }) => t('plugin-ecommerce:purchased'),\n value: 'purchased',\n },\n {\n // @ts-expect-error - translations are not typed in plugins yet\n label: ({ t }) => t('plugin-ecommerce:abandoned'),\n value: 'abandoned',\n },\n ],\n virtual: true,\n },\n ...(currenciesConfig\n ? [\n {\n type: 'row',\n admin: { position: 'sidebar' },\n fields: [\n amountField({\n currenciesConfig,\n overrides: {\n name: 'subtotal',\n\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:subtotal'),\n },\n }),\n currencyField({\n currenciesConfig,\n }),\n ],\n } as Field,\n ]\n : []),\n ]\n\n // Internal access function for guest users (unauthenticated)\n const isGuest: Access = ({ req }) => !req.user\n\n const baseConfig: CollectionConfig = {\n slug: cartsSlug,\n access: {\n create: accessOR(\n access.isAdmin,\n access.isAuthenticated,\n conditional(allowGuestCarts, isGuest),\n ),\n delete: accessOR(\n access.isAdmin,\n access.isDocumentOwner,\n hasCartSecretAccess(allowGuestCarts),\n ),\n read: accessOR(access.isAdmin, access.isDocumentOwner, hasCartSecretAccess(allowGuestCarts)),\n update: accessOR(\n access.isAdmin,\n access.isDocumentOwner,\n hasCartSecretAccess(allowGuestCarts),\n ),\n },\n admin: {\n description: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:cartsCollectionDescription'),\n group: 'Ecommerce',\n useAsTitle: 'createdAt',\n },\n endpoints: [\n addItemEndpoint({ cartItemMatcher, cartsSlug }),\n clearCartEndpoint({ cartsSlug }),\n // mergeCartEndpoint uses its own matcher that handles CartItemData for both items\n mergeCartEndpoint({ cartsSlug }),\n removeItemEndpoint({ cartsSlug }),\n updateItemEndpoint({ cartsSlug }),\n ],\n fields,\n hooks: {\n afterRead: [\n ({ doc, req }) => {\n // Include secret only if this was just created (stored in context by beforeChange)\n if (req.context?.newCartSecret) {\n doc.secret = req.context.newCartSecret\n }\n // Secret is otherwise never exposed (field access is locked)\n return doc\n },\n ],\n beforeChange: [\n // This hook can be used to update the subtotal before saving the cart\n beforeChangeCart({ productsSlug, variantsSlug }),\n ],\n },\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:carts'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:cart'),\n },\n timestamps: true,\n }\n\n return { ...baseConfig }\n}\n"],"names":["amountField","cartItemsField","currencyField","accessOR","conditional","beforeChangeCart","addItemEndpoint","clearCartEndpoint","mergeCartEndpoint","removeItemEndpoint","updateItemEndpoint","hasCartSecretAccess","statusBeforeRead","createCartsCollection","props","access","allowGuestCarts","cartItemMatcher","currenciesConfig","customersSlug","enableVariants","productsSlug","variantsSlug","cartsSlug","fields","overrides","label","t","labels","plural","singular","name","type","create","read","update","admin","hidden","position","readOnly","index","relationTo","date","pickerAppearance","hooks","afterRead","options","value","virtual","isGuest","req","user","baseConfig","slug","isAdmin","isAuthenticated","delete","isDocumentOwner","description","group","useAsTitle","endpoints","doc","context","newCartSecret","secret","beforeChange","timestamps"],"mappings":"AAKA,SAASA,WAAW,QAAQ,8BAA6B;AACzD,SAASC,cAAc,QAAQ,iCAAgC;AAC/D,SAASC,aAAa,QAAQ,gCAA+B;AAC7D,SAASC,QAAQ,EAAEC,WAAW,QAAQ,uCAAsC;AAC5E,SAASC,gBAAgB,QAAQ,oBAAmB;AACpD,SAASC,eAAe,QAAQ,yBAAwB;AACxD,SAASC,iBAAiB,QAAQ,2BAA0B;AAC5D,SAASC,iBAAiB,QAAQ,2BAA0B;AAC5D,SAASC,kBAAkB,QAAQ,4BAA2B;AAC9D,SAASC,kBAAkB,QAAQ,4BAA2B;AAC9D,SAASC,mBAAmB,QAAQ,2BAA0B;A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AC/DA,EAAE;YACJgC,OAAO;YACPC,YAAY;QACd;QACAC,WAAW;YACTvD,gBAAgB;gBAAEW;gBAAiBM;YAAU;YAC7ChB,kBAAkB;gBAAEgB;YAAU;YAC9B,kFAAkF;YAClFf,kBAAkB;gBAAEe;YAAU;YAC9Bd,mBAAmB;gBAAEc;YAAU;YAC/Bb,mBAAmB;gBAAEa;YAAU;SAChC;QACDC;QACAoB,OAAO;YACLC,WAAW;gBACT,CAAC,EAAEiB,GAAG,EAAEZ,GAAG,EAAE;oBACX,mFAAmF;oBACnF,IAAIA,IAAIa,OAAO,EAAEC,eAAe;wBAC9BF,IAAIG,MAAM,GAAGf,IAAIa,OAAO,CAACC,aAAa;oBACxC;oBACA,6DAA6D;oBAC7D,OAAOF;gBACT;aACD;YACDI,cAAc;gBACZ,sEAAsE;gBACtE7D,iBAAiB;oBAAEgB;oBAAcC;gBAAa;aAC/C;QACH;QACAM,QAAQ;YACNC,QAAQ,CAAC,EAAEF,CAAC,EAAE,GACZ,+DAA+D;gBAC/DA,EAAE;YACJG,UAAU,CAAC,EAAEH,CAAC,EAAE,GACd,+DAA+D;gBAC/DA,EAAE;QACN;QACAwC,YAAY;IACd;IAEA,OAAO;QAAE,GAAGf,UAAU;IAAC;AACzB,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/carts/createCartsCollection.ts"],"sourcesContent":["import type { Access, CollectionConfig, Field } from 'payload'\n\nimport type { AccessConfig, CurrenciesConfig } from '../../types/index.js'\nimport type { CartItemMatcher } from './operations/types.js'\n\nimport { amountField } from '../../fields/amountField.js'\nimport { cartItemsField } from '../../fields/cartItemsField.js'\nimport { currencyField } from '../../fields/currencyField.js'\nimport { accessOR, conditional } from '../../utilities/accessComposition.js'\nimport { beforeChangeCart } from './beforeChange.js'\nimport { addItemEndpoint } from './endpoints/addItem.js'\nimport { clearCartEndpoint } from './endpoints/clearCart.js'\nimport { mergeCartEndpoint } from './endpoints/mergeCart.js'\nimport { removeItemEndpoint } from './endpoints/removeItem.js'\nimport { updateItemEndpoint } from './endpoints/updateItem.js'\nimport { hasCartSecretAccess } from './hasCartSecretAccess.js'\nimport { statusBeforeRead } from './statusBeforeRead.js'\n\ntype Props = {\n access: Pick<Required<AccessConfig>, 'isAdmin' | 'isAuthenticated' | 'isDocumentOwner'>\n /**\n * Allow guest (unauthenticated) users to create carts.\n * Defaults to false.\n */\n allowGuestCarts?: boolean\n /**\n * Custom function to determine if two cart items should be considered the same.\n * When items match, their quantities are combined instead of creating separate entries.\n *\n * Use this to add custom uniqueness criteria beyond product and variant IDs.\n *\n * @default defaultCartItemMatcher (matches by product and variant ID only)\n *\n * @example\n * ```ts\n * cartItemMatcher: ({ existingItem, newItem }) => {\n * // Match by product, variant, AND custom delivery option\n * const productMatch = existingItem.product === newItem.product\n * const variantMatch = existingItem.variant === newItem.variant\n * const deliveryMatch = existingItem.deliveryOption === newItem.deliveryOption\n * return productMatch && variantMatch && deliveryMatch\n * }\n * ```\n */\n cartItemMatcher?: CartItemMatcher\n currenciesConfig?: CurrenciesConfig\n /**\n * Slug of the customers collection, defaults to 'users'.\n */\n customersSlug?: string\n /**\n * Enables support for variants in the cart.\n * Defaults to false.\n */\n enableVariants?: boolean\n /**\n * Slug of the products collection, defaults to 'products'.\n */\n productsSlug?: string\n /**\n * Slug of the variants collection, defaults to 'variants'.\n */\n variantsSlug?: string\n}\n\nexport const createCartsCollection: (props: Props) => CollectionConfig = (props) => {\n const {\n access,\n allowGuestCarts = false,\n cartItemMatcher,\n currenciesConfig,\n customersSlug = 'users',\n enableVariants = false,\n productsSlug = 'products',\n variantsSlug = 'variants',\n } = props || {}\n\n const cartsSlug = 'carts'\n\n const fields: Field[] = [\n cartItemsField({\n enableVariants,\n overrides: {\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:items'),\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:items'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:item'),\n },\n },\n productsSlug,\n variantsSlug,\n }),\n {\n name: 'secret',\n type: 'text',\n access: {\n create: () => false, // Users can't set it manually\n read: () => false, // Never readable via field access (only through afterRead hook)\n update: () => false, // Users can't update it\n },\n admin: {\n hidden: true,\n position: 'sidebar',\n readOnly: true,\n },\n index: true,\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:cartSecret'),\n },\n {\n name: 'customer',\n type: 'relationship',\n admin: {\n position: 'sidebar',\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:customer'),\n relationTo: customersSlug,\n },\n {\n name: 'purchasedAt',\n type: 'date',\n admin: {\n date: { pickerAppearance: 'dayAndTime' },\n position: 'sidebar',\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:purchasedAt'),\n },\n {\n name: 'status',\n type: 'select',\n admin: {\n position: 'sidebar',\n readOnly: true,\n },\n hooks: {\n afterRead: [statusBeforeRead],\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:status'),\n options: [\n {\n // @ts-expect-error - translations are not typed in plugins yet\n label: ({ t }) => t('plugin-ecommerce:active'),\n value: 'active',\n },\n {\n // @ts-expect-error - translations are not typed in plugins yet\n label: ({ t }) => t('plugin-ecommerce:purchased'),\n value: 'purchased',\n },\n {\n // @ts-expect-error - translations are not typed in plugins yet\n label: ({ t }) => t('plugin-ecommerce:abandoned'),\n value: 'abandoned',\n },\n ],\n virtual: true,\n },\n ...(currenciesConfig\n ? [\n {\n type: 'row',\n admin: { position: 'sidebar' },\n fields: [\n amountField({\n currenciesConfig,\n overrides: {\n name: 'subtotal',\n\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:subtotal'),\n },\n }),\n currencyField({\n currenciesConfig,\n }),\n ],\n } as Field,\n ]\n : []),\n ]\n\n // Internal access function for guest users (unauthenticated)\n const isGuest: Access = ({ req }) => !req.user\n\n const baseConfig: CollectionConfig = {\n slug: cartsSlug,\n access: {\n create: accessOR(\n access.isAdmin,\n access.isAuthenticated,\n conditional(allowGuestCarts, isGuest),\n ),\n delete: accessOR(\n access.isAdmin,\n access.isDocumentOwner,\n hasCartSecretAccess(allowGuestCarts),\n ),\n read: accessOR(access.isAdmin, access.isDocumentOwner, hasCartSecretAccess(allowGuestCarts)),\n update: accessOR(\n access.isAdmin,\n access.isDocumentOwner,\n hasCartSecretAccess(allowGuestCarts),\n ),\n },\n admin: {\n description: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:cartsCollectionDescription'),\n group: 'Ecommerce',\n useAsTitle: 'createdAt',\n },\n authorship: false,\n endpoints: [\n addItemEndpoint({ cartItemMatcher, cartsSlug }),\n clearCartEndpoint({ cartsSlug }),\n // mergeCartEndpoint uses its own matcher that handles CartItemData for both items\n mergeCartEndpoint({ cartsSlug }),\n removeItemEndpoint({ cartsSlug }),\n updateItemEndpoint({ cartsSlug }),\n ],\n fields,\n hooks: {\n afterRead: [\n ({ doc, req }) => {\n // Include secret only if this was just created (stored in context by beforeChange)\n if (req.context?.newCartSecret) {\n doc.secret = req.context.newCartSecret\n }\n // Secret is otherwise never exposed (field access is locked)\n return doc\n },\n ],\n beforeChange: [\n // This hook can be used to update the subtotal before saving the cart\n beforeChangeCart({ productsSlug, variantsSlug }),\n ],\n },\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:carts'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:cart'),\n },\n timestamps: true,\n }\n\n return { ...baseConfig }\n}\n"],"names":["amountField","cartItemsField","currencyField","accessOR","conditional","beforeChangeCart","addItemEndpoint","clearCartEndpoint","mergeCartEndpoint","removeItemEndpoint","updateItemEndpoint","hasCartSecretAccess","statusBeforeRead","createCartsCollection","props","access","allowGuestCarts","cartItemMatcher","currenciesConfig","customersSlug","enableVariants","productsSlug","variantsSlug","cartsSlug","fields","overrides","label","t","labels","plural","singular","name","type","create","read","update","admin","hidden","position","readOnly","index","relationTo","date","pickerAppearance","hooks","afterRead","options","value","virtual","isGuest","req","user","baseConfig","slug","isAdmin","isAuthenticated","delete","isDocumentOwner","description","group","useAsTitle","authorship","endpoints","doc","context","newCartSecret","secret","beforeChange","timestamps"],"mappings":"AAKA,SAASA,WAAW,QAAQ,8BAA6B;AACzD,SAASC,cAAc,QAAQ,iCAAgC;AAC/D,SAASC,aAAa,QAAQ,gCAA+B;AAC7D,SAASC,QAAQ,EAAEC,WAAW,QAAQ,uCAAsC;AAC5E,SAASC,gBAAgB,QAAQ,oBAAmB;AACpD,SAASC,eAAe,QAAQ,yBAAwB;AACxD,SAASC,iBAAiB,QAAQ,2BAA0B;AAC5D,SAASC,iBAAiB,QAAQ,2BAA0B;AAC5D,SAASC,kBAAkB,QAAQ,4BAA2B;AAC9D,SAASC,kBAAkB,QAAQ,4BAA2B;AAC9D,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,gBAAgB,QAAQ,wBAAuB;AAiDxD,OAAO,MAAMC,wBAA4D,CAACC;IACxE,MAAM,EACJC,MAAM,EACNC,kBAAkB,KAAK,EACvBC,eAAe,EACfC,gBAAgB,EAChBC,gBAAgB,OAAO,EACvBC,iBAAiB,KAAK,EACtBC,eAAe,UAAU,EACzBC,eAAe,UAAU,EAC1B,GAAGR,SAAS,CAAC;IAEd,MAAMS,YAAY;IAElB,MAAMC,SAAkB;QACtBvB,eAAe;YACbmB;YACAK,WAAW;gBACTC,OAAO,CAAC,EAAEC,CAAC,EAAE,GACX,+DAA+D;oBAC/DA,EAAE;gBACJC,QAAQ;oBACNC,QAAQ,CAAC,EAAEF,CAAC,EAAE,GACZ,+DAA+D;wBAC/DA,EAAE;oBACJG,UAAU,CAAC,EAAEH,CAAC,E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,sEAAsE;gBACtE9D,iBAAiB;oBAAEgB;oBAAcC;gBAAa;aAC/C;QACH;QACAM,QAAQ;YACNC,QAAQ,CAAC,EAAEF,CAAC,EAAE,GACZ,+DAA+D;gBAC/DA,EAAE;YACJG,UAAU,CAAC,EAAEH,CAAC,EAAE,GACd,+DAA+D;gBAC/DA,EAAE;QACN;QACAyC,YAAY;IACd;IAEA,OAAO;QAAE,GAAGhB,UAAU;IAAC;AACzB,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createOrdersCollection.d.ts","sourceRoot":"","sources":["../../../src/collections/orders/createOrdersCollection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAA;AAO1E,KAAK,KAAK,GAAG;IACX,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,sBAAsB,GAAG,SAAS,GAAG,iBAAiB,CAAC,CAAA;IAClF;;OAEG;IACH,aAAa,CAAC,EAAE,KAAK,EAAE,CAAA;IACvB,gBAAgB,CAAC,EAAE,gBAAgB,CAAA;IACnC;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB,CAAA;AAED,eAAO,MAAM,sBAAsB,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,
|
|
1
|
+
{"version":3,"file":"createOrdersCollection.d.ts","sourceRoot":"","sources":["../../../src/collections/orders/createOrdersCollection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAA;AAO1E,KAAK,KAAK,GAAG;IACX,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,sBAAsB,GAAG,SAAS,GAAG,iBAAiB,CAAC,CAAA;IAClF;;OAEG;IACH,aAAa,CAAC,EAAE,KAAK,EAAE,CAAA;IACvB,gBAAgB,CAAC,EAAE,gBAAgB,CAAA;IACnC;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB,CAAA;AAED,eAAO,MAAM,sBAAsB,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,gBAyLtD,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/orders/createOrdersCollection.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { AccessConfig, CurrenciesConfig } from '../../types/index.js'\n\nimport { amountField } from '../../fields/amountField.js'\nimport { cartItemsField } from '../../fields/cartItemsField.js'\nimport { currencyField } from '../../fields/currencyField.js'\nimport { accessOR } from '../../utilities/accessComposition.js'\n\ntype Props = {\n access: Pick<AccessConfig, 'adminOnlyFieldAccess' | 'isAdmin' | 'isDocumentOwner'>\n /**\n * Array of fields used for capturing the shipping address data.\n */\n addressFields?: Field[]\n currenciesConfig?: CurrenciesConfig\n /**\n * Slug of the customers collection, defaults to 'users'.\n */\n customersSlug?: string\n enableVariants?: boolean\n /**\n * Slug of the products collection, defaults to 'products'.\n */\n productsSlug?: string\n /**\n * Slug of the transactions collection, defaults to 'transactions'.\n */\n transactionsSlug?: string\n /**\n * Slug of the variants collection, defaults to 'variants'.\n */\n variantsSlug?: string\n}\n\nexport const createOrdersCollection: (props: Props) => CollectionConfig = (props) => {\n const {\n access,\n addressFields,\n currenciesConfig,\n customersSlug = 'users',\n enableVariants = false,\n productsSlug = 'products',\n transactionsSlug = 'transactions',\n variantsSlug = 'variants',\n } = props || {}\n\n const fields: Field[] = [\n {\n type: 'tabs',\n tabs: [\n {\n fields: [\n cartItemsField({\n enableVariants,\n overrides: {\n name: 'items',\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:items'),\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:items'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:item'),\n },\n },\n productsSlug,\n variantsSlug,\n }),\n ],\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:orderDetails'),\n },\n {\n fields: [\n ...(addressFields\n ? [\n {\n name: 'shippingAddress',\n type: 'group',\n fields: addressFields,\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:shippingAddress'),\n } as Field,\n ]\n : []),\n ],\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:shipping'),\n },\n ],\n },\n {\n name: 'customer',\n type: 'relationship',\n admin: {\n position: 'sidebar',\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:customer'),\n relationTo: customersSlug,\n },\n {\n name: 'customerEmail',\n type: 'email',\n admin: {\n position: 'sidebar',\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:customerEmail'),\n },\n {\n name: 'transactions',\n type: 'relationship',\n access: {\n create: access.adminOnlyFieldAccess,\n read: access.adminOnlyFieldAccess,\n update: access.adminOnlyFieldAccess,\n },\n admin: {\n position: 'sidebar',\n },\n hasMany: true,\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:transactions'),\n relationTo: transactionsSlug,\n },\n {\n name: 'status',\n type: 'select',\n admin: {\n position: 'sidebar',\n },\n defaultValue: 'processing',\n interfaceName: 'OrderStatus',\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:status'),\n options: [\n {\n // @ts-expect-error - translations are not typed in plugins yet\n label: ({ t }) => t('plugin-ecommerce:processing'),\n value: 'processing',\n },\n {\n // @ts-expect-error - translations are not typed in plugins yet\n label: ({ t }) => t('plugin-ecommerce:completed'),\n value: 'completed',\n },\n {\n // @ts-expect-error - translations are not typed in plugins yet\n label: ({ t }) => t('plugin-ecommerce:cancelled'),\n value: 'cancelled',\n },\n {\n // @ts-expect-error - translations are not typed in plugins yet\n label: ({ t }) => t('plugin-ecommerce:refunded'),\n value: 'refunded',\n },\n ],\n },\n\n ...(currenciesConfig\n ? [\n {\n type: 'row',\n admin: {\n position: 'sidebar',\n },\n fields: [\n amountField({\n currenciesConfig,\n }),\n currencyField({\n currenciesConfig,\n }),\n ],\n } as Field,\n ]\n : []),\n ]\n\n const baseConfig: CollectionConfig = {\n slug: 'orders',\n access: {\n create: access.isAdmin,\n delete: access.isAdmin,\n read: accessOR(access.isAdmin, access.isDocumentOwner),\n update: access.isAdmin,\n },\n admin: {\n description: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:ordersCollectionDescription'),\n group: 'Ecommerce',\n useAsTitle: 'createdAt',\n },\n fields,\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:orders'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:order'),\n },\n timestamps: true,\n }\n\n return { ...baseConfig }\n}\n"],"names":["amountField","cartItemsField","currencyField","accessOR","createOrdersCollection","props","access","addressFields","currenciesConfig","customersSlug","enableVariants","productsSlug","transactionsSlug","variantsSlug","fields","type","tabs","overrides","name","label","t","labels","plural","singular","admin","position","relationTo","create","adminOnlyFieldAccess","read","update","hasMany","defaultValue","interfaceName","options","value","baseConfig","slug","isAdmin","delete","isDocumentOwner","description","group","useAsTitle","timestamps"],"mappings":"AAIA,SAASA,WAAW,QAAQ,8BAA6B;AACzD,SAASC,cAAc,QAAQ,iCAAgC;AAC/D,SAASC,aAAa,QAAQ,gCAA+B;AAC7D,SAASC,QAAQ,QAAQ,uCAAsC;AA4B/D,OAAO,MAAMC,yBAA6D,CAACC;IACzE,MAAM,EACJC,MAAM,EACNC,aAAa,EACbC,gBAAgB,EAChBC,gBAAgB,OAAO,EACvBC,iBAAiB,KAAK,EACtBC,eAAe,UAAU,EACzBC,mBAAmB,cAAc,EACjCC,eAAe,UAAU,EAC1B,GAAGR,SAAS,CAAC;IAEd,MAAMS,SAAkB;QACtB;YACEC,MAAM;YACNC,MAAM;gBACJ;oBACEF,QAAQ;wBACNb,eAAe;4BACbS;4BACAO,WAAW;gCACTC,MAAM;gCACNC,OAAO,CAAC,EAAEC,CAAC,EAAE,GACX,+DAA+D;oCAC/DA,EAAE;gCACJC,QAAQ;oCACNC,QAAQ,CAAC,EAAEF,CAAC,EAAE,GACZ,+DAA+D;wCAC/DA,EAAE;oCACJG,UAAU,CAAC,EAAEH,CAAC,EAAE,GACd,+DAA+D;wCAC/DA,EAAE;gCACN;4BACF;4BACAT;4BACAE;wBACF;qBACD;oBACDM,OAAO,CAAC,EAAEC,CAAC,EAAE,GACX,+DAA+D;wBAC/DA,EAAE;gBACN;gBACA;oBACEN,QAAQ;2BACFP,gBACA;4BACE;gCACEW,MAAM;gCACNH,MAAM;gCACND,QAAQP;gCACRY,OAAO,CAAC,EAAEC,CAAC,EAAE,GACX,+DAA+D;oCAC/DA,EAAE;4BACN;yBACD,GACD,EAAE;qBACP;oBACDD,OAAO,CAAC,EAAEC,CAAC,EAAE,GACX,+DAA+D;wBAC/DA,EAAE;gBACN;aACD;QACH;QACA;YACEF,MAAM;YACN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ACH;SACD,GACD,EAAE;KACP;IAED,MAAM4B,aAA+B;QACnCC,MAAM;QACN/B,QAAQ;YACNqB,QAAQrB,OAAOgC,OAAO;YACtBC,QAAQjC,OAAOgC,OAAO;YACtBT,MAAM1B,SAASG,OAAOgC,OAAO,EAAEhC,OAAOkC,eAAe;YACrDV,QAAQxB,OAAOgC,OAAO;QACxB;QACAd,OAAO;YACLiB,aAAa,CAAC,EAAErB,CAAC,EAAE,GACjB,+DAA+D;gBAC/DA,EAAE;YACJsB,OAAO;YACPC,YAAY;QACd;
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/orders/createOrdersCollection.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { AccessConfig, CurrenciesConfig } from '../../types/index.js'\n\nimport { amountField } from '../../fields/amountField.js'\nimport { cartItemsField } from '../../fields/cartItemsField.js'\nimport { currencyField } from '../../fields/currencyField.js'\nimport { accessOR } from '../../utilities/accessComposition.js'\n\ntype Props = {\n access: Pick<AccessConfig, 'adminOnlyFieldAccess' | 'isAdmin' | 'isDocumentOwner'>\n /**\n * Array of fields used for capturing the shipping address data.\n */\n addressFields?: Field[]\n currenciesConfig?: CurrenciesConfig\n /**\n * Slug of the customers collection, defaults to 'users'.\n */\n customersSlug?: string\n enableVariants?: boolean\n /**\n * Slug of the products collection, defaults to 'products'.\n */\n productsSlug?: string\n /**\n * Slug of the transactions collection, defaults to 'transactions'.\n */\n transactionsSlug?: string\n /**\n * Slug of the variants collection, defaults to 'variants'.\n */\n variantsSlug?: string\n}\n\nexport const createOrdersCollection: (props: Props) => CollectionConfig = (props) => {\n const {\n access,\n addressFields,\n currenciesConfig,\n customersSlug = 'users',\n enableVariants = false,\n productsSlug = 'products',\n transactionsSlug = 'transactions',\n variantsSlug = 'variants',\n } = props || {}\n\n const fields: Field[] = [\n {\n type: 'tabs',\n tabs: [\n {\n fields: [\n cartItemsField({\n enableVariants,\n overrides: {\n name: 'items',\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:items'),\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:items'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:item'),\n },\n },\n productsSlug,\n variantsSlug,\n }),\n ],\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:orderDetails'),\n },\n {\n fields: [\n ...(addressFields\n ? [\n {\n name: 'shippingAddress',\n type: 'group',\n fields: addressFields,\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:shippingAddress'),\n } as Field,\n ]\n : []),\n ],\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:shipping'),\n },\n ],\n },\n {\n name: 'customer',\n type: 'relationship',\n admin: {\n position: 'sidebar',\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:customer'),\n relationTo: customersSlug,\n },\n {\n name: 'customerEmail',\n type: 'email',\n admin: {\n position: 'sidebar',\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:customerEmail'),\n },\n {\n name: 'transactions',\n type: 'relationship',\n access: {\n create: access.adminOnlyFieldAccess,\n read: access.adminOnlyFieldAccess,\n update: access.adminOnlyFieldAccess,\n },\n admin: {\n position: 'sidebar',\n },\n hasMany: true,\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:transactions'),\n relationTo: transactionsSlug,\n },\n {\n name: 'status',\n type: 'select',\n admin: {\n position: 'sidebar',\n },\n defaultValue: 'processing',\n interfaceName: 'OrderStatus',\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:status'),\n options: [\n {\n // @ts-expect-error - translations are not typed in plugins yet\n label: ({ t }) => t('plugin-ecommerce:processing'),\n value: 'processing',\n },\n {\n // @ts-expect-error - translations are not typed in plugins yet\n label: ({ t }) => t('plugin-ecommerce:completed'),\n value: 'completed',\n },\n {\n // @ts-expect-error - translations are not typed in plugins yet\n label: ({ t }) => t('plugin-ecommerce:cancelled'),\n value: 'cancelled',\n },\n {\n // @ts-expect-error - translations are not typed in plugins yet\n label: ({ t }) => t('plugin-ecommerce:refunded'),\n value: 'refunded',\n },\n ],\n },\n\n ...(currenciesConfig\n ? [\n {\n type: 'row',\n admin: {\n position: 'sidebar',\n },\n fields: [\n amountField({\n currenciesConfig,\n }),\n currencyField({\n currenciesConfig,\n }),\n ],\n } as Field,\n ]\n : []),\n ]\n\n const baseConfig: CollectionConfig = {\n slug: 'orders',\n access: {\n create: access.isAdmin,\n delete: access.isAdmin,\n read: accessOR(access.isAdmin, access.isDocumentOwner),\n update: access.isAdmin,\n },\n admin: {\n description: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:ordersCollectionDescription'),\n group: 'Ecommerce',\n useAsTitle: 'createdAt',\n },\n authorship: false,\n fields,\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:orders'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:order'),\n },\n timestamps: true,\n }\n\n return { ...baseConfig }\n}\n"],"names":["amountField","cartItemsField","currencyField","accessOR","createOrdersCollection","props","access","addressFields","currenciesConfig","customersSlug","enableVariants","productsSlug","transactionsSlug","variantsSlug","fields","type","tabs","overrides","name","label","t","labels","plural","singular","admin","position","relationTo","create","adminOnlyFieldAccess","read","update","hasMany","defaultValue","interfaceName","options","value","baseConfig","slug","isAdmin","delete","isDocumentOwner","description","group","useAsTitle","authorship","timestamps"],"mappings":"AAIA,SAASA,WAAW,QAAQ,8BAA6B;AACzD,SAASC,cAAc,QAAQ,iCAAgC;AAC/D,SAASC,aAAa,QAAQ,gCAA+B;AAC7D,SAASC,QAAQ,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,EAAE,GACjB,+DAA+D;gBAC/DA,EAAE;YACJsB,OAAO;YACPC,YAAY;QACd;QACAC,YAAY;QACZ9B;QACAO,QAAQ;YACNC,QAAQ,CAAC,EAAEF,CAAC,EAAE,GACZ,+DAA+D;gBAC/DA,EAAE;YACJG,UAAU,CAAC,EAAEH,CAAC,EAAE,GACd,+DAA+D;gBAC/DA,EAAE;QACN;QACAyB,YAAY;IACd;IAEA,OAAO;QAAE,GAAGT,UAAU;IAAC;AACzB,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createProductsCollection.d.ts","sourceRoot":"","sources":["../../../src/collections/products/createProductsCollection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE/C,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAA;AAM3F,KAAK,KAAK,GAAG;IACX,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,wBAAwB,GAAG,SAAS,CAAC,CAAA;IAChE,gBAAgB,EAAE,gBAAgB,CAAA;IAClC,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,GAAG,eAAe,CAAA;IACrC;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B,CAAA;AAED,eAAO,MAAM,wBAAwB,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,
|
|
1
|
+
{"version":3,"file":"createProductsCollection.d.ts","sourceRoot":"","sources":["../../../src/collections/products/createProductsCollection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE/C,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAA;AAM3F,KAAK,KAAK,GAAG;IACX,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,wBAAwB,GAAG,SAAS,CAAC,CAAA;IAChE,gBAAgB,EAAE,gBAAgB,CAAA;IAClC,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,GAAG,eAAe,CAAA;IACrC;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B,CAAA;AAED,eAAO,MAAM,wBAAwB,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,gBA4DxD,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/products/createProductsCollection.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\n\nimport type { AccessConfig, CurrenciesConfig, InventoryConfig } from '../../types/index.js'\n\nimport { inventoryField } from '../../fields/inventoryField.js'\nimport { pricesField } from '../../fields/pricesField.js'\nimport { variantsFields } from '../../fields/variantsFields.js'\n\ntype Props = {\n access: Pick<AccessConfig, 'adminOrPublishedStatus' | 'isAdmin'>\n currenciesConfig: CurrenciesConfig\n enableVariants?: boolean\n /**\n * Adds in an inventory field to the product and its variants. This is useful for tracking inventory levels.\n * Defaults to true.\n */\n inventory?: boolean | InventoryConfig\n /**\n * Slug of the variants collection, defaults to 'variants'.\n */\n variantsSlug?: string\n /**\n * Slug of the variant types collection, defaults to 'variantTypes'.\n */\n variantTypesSlug?: string\n}\n\nexport const createProductsCollection: (props: Props) => CollectionConfig = (props) => {\n const {\n access,\n currenciesConfig,\n enableVariants = false,\n inventory = true,\n variantsSlug = 'variants',\n variantTypesSlug = 'variantTypes',\n } = props || {}\n\n const fields = [\n ...(inventory\n ? [\n inventoryField({\n overrides: {\n admin: {\n condition: ({ enableVariants }) => !enableVariants,\n },\n },\n }),\n ]\n : []),\n ...(enableVariants ? variantsFields({ variantsSlug, variantTypesSlug }) : []),\n ...(currenciesConfig ? [...pricesField({ currenciesConfig })] : []),\n ]\n\n const baseConfig: CollectionConfig = {\n slug: 'products',\n access: {\n create: access.isAdmin,\n delete: access.isAdmin,\n read: access.adminOrPublishedStatus,\n update: access.isAdmin,\n },\n admin: {\n defaultColumns: [\n ...(currenciesConfig ? ['prices'] : []),\n ...(enableVariants ? ['variants'] : []),\n ],\n group: 'Ecommerce',\n },\n fields,\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:products'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:product'),\n },\n trash: true,\n versions: {\n drafts: {\n autosave: true,\n },\n },\n }\n\n return baseConfig\n}\n"],"names":["inventoryField","pricesField","variantsFields","createProductsCollection","props","access","currenciesConfig","enableVariants","inventory","variantsSlug","variantTypesSlug","fields","overrides","admin","condition","baseConfig","slug","create","isAdmin","delete","read","adminOrPublishedStatus","update","defaultColumns","group","labels","plural","t","singular","trash","versions","drafts","autosave"],"mappings":"AAIA,SAASA,cAAc,QAAQ,iCAAgC;AAC/D,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,cAAc,QAAQ,iCAAgC;AAqB/D,OAAO,MAAMC,2BAA+D,CAACC;IAC3E,MAAM,EACJC,MAAM,EACNC,gBAAgB,EAChBC,iBAAiB,KAAK,EACtBC,YAAY,IAAI,EAChBC,eAAe,UAAU,EACzBC,mBAAmB,cAAc,EAClC,GAAGN,SAAS,CAAC;IAEd,MAAMO,SAAS;WACTH,YACA;YACER,eAAe;gBACbY,WAAW;oBACTC,OAAO;wBACLC,WAAW,CAAC,EAAEP,cAAc,EAAE,GAAK,CAACA;oBACtC;gBACF;YACF;SACD,GACD,EAAE;WACFA,iBAAiBL,eAAe;YAAEO;YAAcC;QAAiB,KAAK,EAAE;WACxEJ,mBAAmB;eAAIL,YAAY;gBAAEK;YAAiB;SAAG,GAAG,EAAE;KACnE;IAED,MAAMS,aAA+B;QACnCC,MAAM;QACNX,QAAQ;YACNY,QAAQZ,OAAOa,OAAO;YACtBC,QAAQd,OAAOa,OAAO;YACtBE,MAAMf,OAAOgB,sBAAsB;YACnCC,QAAQjB,OAAOa,OAAO;QACxB;QACAL,OAAO;YACLU,gBAAgB;mBACVjB,mBAAmB;oBAAC;iBAAS,GAAG,EAAE;mBAClCC,iBAAiB;oBAAC;iBAAW,GAAG,EAAE;aACvC;YACDiB,OAAO;QACT;
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/products/createProductsCollection.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\n\nimport type { AccessConfig, CurrenciesConfig, InventoryConfig } from '../../types/index.js'\n\nimport { inventoryField } from '../../fields/inventoryField.js'\nimport { pricesField } from '../../fields/pricesField.js'\nimport { variantsFields } from '../../fields/variantsFields.js'\n\ntype Props = {\n access: Pick<AccessConfig, 'adminOrPublishedStatus' | 'isAdmin'>\n currenciesConfig: CurrenciesConfig\n enableVariants?: boolean\n /**\n * Adds in an inventory field to the product and its variants. This is useful for tracking inventory levels.\n * Defaults to true.\n */\n inventory?: boolean | InventoryConfig\n /**\n * Slug of the variants collection, defaults to 'variants'.\n */\n variantsSlug?: string\n /**\n * Slug of the variant types collection, defaults to 'variantTypes'.\n */\n variantTypesSlug?: string\n}\n\nexport const createProductsCollection: (props: Props) => CollectionConfig = (props) => {\n const {\n access,\n currenciesConfig,\n enableVariants = false,\n inventory = true,\n variantsSlug = 'variants',\n variantTypesSlug = 'variantTypes',\n } = props || {}\n\n const fields = [\n ...(inventory\n ? [\n inventoryField({\n overrides: {\n admin: {\n condition: ({ enableVariants }) => !enableVariants,\n },\n },\n }),\n ]\n : []),\n ...(enableVariants ? variantsFields({ variantsSlug, variantTypesSlug }) : []),\n ...(currenciesConfig ? [...pricesField({ currenciesConfig })] : []),\n ]\n\n const baseConfig: CollectionConfig = {\n slug: 'products',\n access: {\n create: access.isAdmin,\n delete: access.isAdmin,\n read: access.adminOrPublishedStatus,\n update: access.isAdmin,\n },\n admin: {\n defaultColumns: [\n ...(currenciesConfig ? ['prices'] : []),\n ...(enableVariants ? ['variants'] : []),\n ],\n group: 'Ecommerce',\n },\n authorship: false,\n fields,\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:products'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:product'),\n },\n trash: true,\n versions: {\n drafts: {\n autosave: true,\n },\n },\n }\n\n return baseConfig\n}\n"],"names":["inventoryField","pricesField","variantsFields","createProductsCollection","props","access","currenciesConfig","enableVariants","inventory","variantsSlug","variantTypesSlug","fields","overrides","admin","condition","baseConfig","slug","create","isAdmin","delete","read","adminOrPublishedStatus","update","defaultColumns","group","authorship","labels","plural","t","singular","trash","versions","drafts","autosave"],"mappings":"AAIA,SAASA,cAAc,QAAQ,iCAAgC;AAC/D,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,cAAc,QAAQ,iCAAgC;AAqB/D,OAAO,MAAMC,2BAA+D,CAACC;IAC3E,MAAM,EACJC,MAAM,EACNC,gBAAgB,EAChBC,iBAAiB,KAAK,EACtBC,YAAY,IAAI,EAChBC,eAAe,UAAU,EACzBC,mBAAmB,cAAc,EAClC,GAAGN,SAAS,CAAC;IAEd,MAAMO,SAAS;WACTH,YACA;YACER,eAAe;gBACbY,WAAW;oBACTC,OAAO;wBACLC,WAAW,CAAC,EAAEP,cAAc,EAAE,GAAK,CAACA;oBACtC;gBACF;YACF;SACD,GACD,EAAE;WACFA,iBAAiBL,eAAe;YAAEO;YAAcC;QAAiB,KAAK,EAAE;WACxEJ,mBAAmB;eAAIL,YAAY;gBAAEK;YAAiB;SAAG,GAAG,EAAE;KACnE;IAED,MAAMS,aAA+B;QACnCC,MAAM;QACNX,QAAQ;YACNY,QAAQZ,OAAOa,OAAO;YACtBC,QAAQd,OAAOa,OAAO;YACtBE,MAAMf,OAAOgB,sBAAsB;YACnCC,QAAQjB,OAAOa,OAAO;QACxB;QACAL,OAAO;YACLU,gBAAgB;mBACVjB,mBAAmB;oBAAC;iBAAS,GAAG,EAAE;mBAClCC,iBAAiB;oBAAC;iBAAW,GAAG,EAAE;aACvC;YACDiB,OAAO;QACT;QACAC,YAAY;QACZd;QACAe,QAAQ;YACNC,QAAQ,CAAC,EAAEC,CAAC,EAAE,GACZ,+DAA+D;gBAC/DA,EAAE;YACJC,UAAU,CAAC,EAAED,CAAC,EAAE,GACd,+DAA+D;gBAC/DA,EAAE;QACN;QACAE,OAAO;QACPC,UAAU;YACRC,QAAQ;gBACNC,UAAU;YACZ;QACF;IACF;IAEA,OAAOlB;AACT,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createTransactionsCollection.d.ts","sourceRoot":"","sources":["../../../src/collections/transactions/createTransactionsCollection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAO1F,KAAK,KAAK,GAAG;IACX,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,SAAS,CAAC,CAAA;IACrC;;OAEG;IACH,aAAa,CAAC,EAAE,KAAK,EAAE,CAAA;IACvB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,gBAAgB,CAAC,EAAE,gBAAgB,CAAA;IACnC;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB;;OAEG;IACH,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,cAAc,CAAC,EAAE,cAAc,EAAE,CAAA;IACjC;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB,CAAA;AAED,eAAO,MAAM,4BAA4B,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,
|
|
1
|
+
{"version":3,"file":"createTransactionsCollection.d.ts","sourceRoot":"","sources":["../../../src/collections/transactions/createTransactionsCollection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAO1F,KAAK,KAAK,GAAG;IACX,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,SAAS,CAAC,CAAA;IACrC;;OAEG;IACH,aAAa,CAAC,EAAE,KAAK,EAAE,CAAA;IACvB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,gBAAgB,CAAC,EAAE,gBAAgB,CAAA;IACnC;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB;;OAEG;IACH,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,cAAc,CAAC,EAAE,cAAc,EAAE,CAAA;IACjC;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB,CAAA;AAED,eAAO,MAAM,4BAA4B,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,gBAgL5D,CAAA"}
|
|
@@ -141,6 +141,7 @@ export const createTransactionsCollection = (props)=>{
|
|
|
141
141
|
t('plugin-ecommerce:transactionsCollectionDescription'),
|
|
142
142
|
group: 'Ecommerce'
|
|
143
143
|
},
|
|
144
|
+
authorship: false,
|
|
144
145
|
fields,
|
|
145
146
|
labels: {
|
|
146
147
|
plural: ({ t })=>// @ts-expect-error - translations are not typed in plugins yet
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/transactions/createTransactionsCollection.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { AccessConfig, CurrenciesConfig, PaymentAdapter } from '../../types/index.js'\n\nimport { amountField } from '../../fields/amountField.js'\nimport { cartItemsField } from '../../fields/cartItemsField.js'\nimport { currencyField } from '../../fields/currencyField.js'\nimport { statusField } from '../../fields/statusField.js'\n\ntype Props = {\n access: Pick<AccessConfig, 'isAdmin'>\n /**\n * Array of fields used for capturing the billing address.\n */\n addressFields?: Field[]\n /**\n * Slug of the carts collection, defaults to 'carts'.\n */\n cartsSlug?: string\n currenciesConfig?: CurrenciesConfig\n /**\n * Slug of the customers collection, defaults to 'users'.\n */\n customersSlug?: string\n /**\n * Enable variants in the transactions collection.\n */\n enableVariants?: boolean\n /**\n * Slug of the orders collection, defaults to 'orders'.\n */\n ordersSlug?: string\n paymentMethods?: PaymentAdapter[]\n /**\n * Slug of the products collection, defaults to 'products'.\n */\n productsSlug?: string\n /**\n * Slug of the variants collection, defaults to 'variants'.\n */\n variantsSlug?: string\n}\n\nexport const createTransactionsCollection: (props: Props) => CollectionConfig = (props) => {\n const {\n access,\n addressFields,\n cartsSlug = 'carts',\n currenciesConfig,\n customersSlug = 'users',\n enableVariants = false,\n ordersSlug = 'orders',\n paymentMethods,\n productsSlug = 'products',\n variantsSlug = 'variants',\n } = props || {}\n\n const fields: Field[] = [\n {\n type: 'tabs',\n tabs: [\n {\n fields: [\n cartItemsField({\n enableVariants,\n overrides: {\n name: 'items',\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:items'),\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:items'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:item'),\n },\n },\n productsSlug,\n variantsSlug,\n }),\n ...(paymentMethods?.length && paymentMethods.length > 0\n ? [\n {\n name: 'paymentMethod',\n type: 'select',\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:paymentMethod'),\n options: paymentMethods.map((method) => ({\n label: method.label ?? method.name,\n value: method.name,\n })),\n } as Field,\n ...(paymentMethods.map((method) => method.group) || []),\n ]\n : []),\n ],\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:transactionDetails'),\n },\n {\n fields: [\n ...(addressFields\n ? [\n {\n name: 'billingAddress',\n type: 'group',\n fields: addressFields,\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:billingAddress'),\n } as Field,\n ]\n : []),\n ],\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:billing'),\n },\n ],\n },\n statusField({\n overrides: {\n admin: {\n position: 'sidebar',\n },\n },\n }),\n {\n name: 'customer',\n type: 'relationship',\n admin: {\n position: 'sidebar',\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:customer'),\n relationTo: customersSlug,\n },\n {\n name: 'customerEmail',\n type: 'email',\n admin: {\n position: 'sidebar',\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:customerEmail'),\n },\n {\n name: 'order',\n type: 'relationship',\n admin: {\n position: 'sidebar',\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:order'),\n relationTo: ordersSlug,\n },\n {\n name: 'cart',\n type: 'relationship',\n admin: {\n position: 'sidebar',\n },\n relationTo: cartsSlug,\n },\n ...(currenciesConfig\n ? [\n {\n type: 'row',\n admin: {\n position: 'sidebar',\n },\n fields: [\n amountField({\n currenciesConfig,\n }),\n currencyField({\n currenciesConfig,\n }),\n ],\n } as Field,\n ]\n : []),\n ]\n\n const baseConfig: CollectionConfig = {\n slug: 'transactions',\n access: {\n create: access.isAdmin,\n delete: access.isAdmin,\n read: access.isAdmin,\n update: access.isAdmin,\n },\n admin: {\n defaultColumns: ['createdAt', 'customer', 'order', 'amount', 'status'],\n description: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:transactionsCollectionDescription'),\n group: 'Ecommerce',\n },\n fields,\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:transactions'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:transaction'),\n },\n }\n\n return { ...baseConfig }\n}\n"],"names":["amountField","cartItemsField","currencyField","statusField","createTransactionsCollection","props","access","addressFields","cartsSlug","currenciesConfig","customersSlug","enableVariants","ordersSlug","paymentMethods","productsSlug","variantsSlug","fields","type","tabs","overrides","name","label","t","labels","plural","singular","length","options","map","method","value","group","admin","position","relationTo","baseConfig","slug","create","isAdmin","delete","read","update","defaultColumns","description"],"mappings":"AAIA,SAASA,WAAW,QAAQ,8BAA6B;AACzD,SAASC,cAAc,QAAQ,iCAAgC;AAC/D,SAASC,aAAa,QAAQ,gCAA+B;AAC7D,SAASC,WAAW,QAAQ,8BAA6B;AAoCzD,OAAO,MAAMC,+BAAmE,CAACC;IAC/E,MAAM,EACJC,MAAM,EACNC,aAAa,EACbC,YAAY,OAAO,EACnBC,gBAAgB,EAChBC,gBAAgB,OAAO,EACvBC,iBAAiB,KAAK,EACtBC,aAAa,QAAQ,EACrBC,cAAc,EACdC,eAAe,UAAU,EACzBC,eAAe,UAAU,EAC1B,GAAGV,SAAS,CAAC;IAEd,MAAMW,SAAkB;QACtB;YACEC,MAAM;YACNC,MAAM;gBACJ;oBACEF,QAAQ;wBACNf,eAAe;4BACbU;4BACAQ,WAAW;gCACTC,MAAM;gCACNC,OAAO,CAAC,EAAEC,CAAC,EAAE,GACX,+DAA+D;oCAC/DA,EAAE;gCACJC,QAAQ;oCACNC,QAAQ,CAAC,EAAEF,CAAC,EAAE,GACZ,+DAA+D;wCAC/DA,EAAE;oCACJG,UAAU,CAAC,EAAEH,CAAC,EAAE,GACd,+DAA+D;wC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,EAAE;YACJY,YAAYtB;QACd;QACA;YACEQ,MAAM;YACNH,MAAM;YACNe,OAAO;gBACLC,UAAU;YACZ;YACAC,YAAY1B;QACd;WACIC,mBACA;YACE;gBACEQ,MAAM;gBACNe,OAAO;oBACLC,UAAU;gBACZ;gBACAjB,QAAQ;oBACNhB,YAAY;wBACVS;oBACF;oBACAP,cAAc;wBACZO;oBACF;iBACD;YACH;SACD,GACD,EAAE;KACP;IAED,MAAM0B,aAA+B;QACnCC,MAAM;QACN9B,QAAQ;YACN+B,QAAQ/B,OAAOgC,OAAO;YACtBC,QAAQjC,OAAOgC,OAAO;YACtBE,MAAMlC,OAAOgC,OAAO;YACpBG,QAAQnC,OAAOgC,OAAO;QACxB;QACAN,OAAO;YACLU,gBAAgB;gBAAC;gBAAa;gBAAY;gBAAS;gBAAU;aAAS;YACtEC,aAAa,CAAC,EAAErB,CAAC,EAAE,GACjB,+DAA+D;gBAC/DA,EAAE;YACJS,OAAO;QACT;
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/transactions/createTransactionsCollection.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { AccessConfig, CurrenciesConfig, PaymentAdapter } from '../../types/index.js'\n\nimport { amountField } from '../../fields/amountField.js'\nimport { cartItemsField } from '../../fields/cartItemsField.js'\nimport { currencyField } from '../../fields/currencyField.js'\nimport { statusField } from '../../fields/statusField.js'\n\ntype Props = {\n access: Pick<AccessConfig, 'isAdmin'>\n /**\n * Array of fields used for capturing the billing address.\n */\n addressFields?: Field[]\n /**\n * Slug of the carts collection, defaults to 'carts'.\n */\n cartsSlug?: string\n currenciesConfig?: CurrenciesConfig\n /**\n * Slug of the customers collection, defaults to 'users'.\n */\n customersSlug?: string\n /**\n * Enable variants in the transactions collection.\n */\n enableVariants?: boolean\n /**\n * Slug of the orders collection, defaults to 'orders'.\n */\n ordersSlug?: string\n paymentMethods?: PaymentAdapter[]\n /**\n * Slug of the products collection, defaults to 'products'.\n */\n productsSlug?: string\n /**\n * Slug of the variants collection, defaults to 'variants'.\n */\n variantsSlug?: string\n}\n\nexport const createTransactionsCollection: (props: Props) => CollectionConfig = (props) => {\n const {\n access,\n addressFields,\n cartsSlug = 'carts',\n currenciesConfig,\n customersSlug = 'users',\n enableVariants = false,\n ordersSlug = 'orders',\n paymentMethods,\n productsSlug = 'products',\n variantsSlug = 'variants',\n } = props || {}\n\n const fields: Field[] = [\n {\n type: 'tabs',\n tabs: [\n {\n fields: [\n cartItemsField({\n enableVariants,\n overrides: {\n name: 'items',\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:items'),\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:items'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:item'),\n },\n },\n productsSlug,\n variantsSlug,\n }),\n ...(paymentMethods?.length && paymentMethods.length > 0\n ? [\n {\n name: 'paymentMethod',\n type: 'select',\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:paymentMethod'),\n options: paymentMethods.map((method) => ({\n label: method.label ?? method.name,\n value: method.name,\n })),\n } as Field,\n ...(paymentMethods.map((method) => method.group) || []),\n ]\n : []),\n ],\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:transactionDetails'),\n },\n {\n fields: [\n ...(addressFields\n ? [\n {\n name: 'billingAddress',\n type: 'group',\n fields: addressFields,\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:billingAddress'),\n } as Field,\n ]\n : []),\n ],\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:billing'),\n },\n ],\n },\n statusField({\n overrides: {\n admin: {\n position: 'sidebar',\n },\n },\n }),\n {\n name: 'customer',\n type: 'relationship',\n admin: {\n position: 'sidebar',\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:customer'),\n relationTo: customersSlug,\n },\n {\n name: 'customerEmail',\n type: 'email',\n admin: {\n position: 'sidebar',\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:customerEmail'),\n },\n {\n name: 'order',\n type: 'relationship',\n admin: {\n position: 'sidebar',\n },\n label: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:order'),\n relationTo: ordersSlug,\n },\n {\n name: 'cart',\n type: 'relationship',\n admin: {\n position: 'sidebar',\n },\n relationTo: cartsSlug,\n },\n ...(currenciesConfig\n ? [\n {\n type: 'row',\n admin: {\n position: 'sidebar',\n },\n fields: [\n amountField({\n currenciesConfig,\n }),\n currencyField({\n currenciesConfig,\n }),\n ],\n } as Field,\n ]\n : []),\n ]\n\n const baseConfig: CollectionConfig = {\n slug: 'transactions',\n access: {\n create: access.isAdmin,\n delete: access.isAdmin,\n read: access.isAdmin,\n update: access.isAdmin,\n },\n admin: {\n defaultColumns: ['createdAt', 'customer', 'order', 'amount', 'status'],\n description: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:transactionsCollectionDescription'),\n group: 'Ecommerce',\n },\n authorship: false,\n fields,\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:transactions'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:transaction'),\n },\n }\n\n return { ...baseConfig }\n}\n"],"names":["amountField","cartItemsField","currencyField","statusField","createTransactionsCollection","props","access","addressFields","cartsSlug","currenciesConfig","customersSlug","enableVariants","ordersSlug","paymentMethods","productsSlug","variantsSlug","fields","type","tabs","overrides","name","label","t","labels","plural","singular","length","options","map","method","value","group","admin","position","relationTo","baseConfig","slug","create","isAdmin","delete","read","update","defaultColumns","description","authorship"],"mappings":"AAIA,SAASA,WAAW,QAAQ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CAAC,EAAE,GACjB,+DAA+D;gBAC/DA,EAAE;YACJS,OAAO;QACT;QACAa,YAAY;QACZ5B;QACAO,QAAQ;YACNC,QAAQ,CAAC,EAAEF,CAAC,EAAE,GACZ,+DAA+D;gBAC/DA,EAAE;YACJG,UAAU,CAAC,EAAEH,CAAC,EAAE,GACd,+DAA+D;gBAC/DA,EAAE;QACN;IACF;IAEA,OAAO;QAAE,GAAGa,UAAU;IAAC;AACzB,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createVariantOptionsCollection.d.ts","sourceRoot":"","sources":["../../../src/collections/variants/createVariantOptionsCollection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAS,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AAExD,KAAK,KAAK,GAAG;IACX,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,SAAS,GAAG,cAAc,CAAC,CAAA;IACtD;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B,CAAA;AAED,eAAO,MAAM,8BAA8B,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,
|
|
1
|
+
{"version":3,"file":"createVariantOptionsCollection.d.ts","sourceRoot":"","sources":["../../../src/collections/variants/createVariantOptionsCollection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAS,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AAExD,KAAK,KAAK,GAAG;IACX,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,SAAS,GAAG,cAAc,CAAC,CAAA;IACtD;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B,CAAA;AAED,eAAO,MAAM,8BAA8B,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,gBAsD9D,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/variants/createVariantOptionsCollection.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { AccessConfig } from '../../types/index.js'\n\ntype Props = {\n access: Pick<AccessConfig, 'isAdmin' | 'publicAccess'>\n /**\n * Slug of the variant types collection, defaults to 'variantTypes'.\n */\n variantTypesSlug?: string\n}\n\nexport const createVariantOptionsCollection: (props: Props) => CollectionConfig = (props) => {\n const { access, variantTypesSlug = 'variantTypes' } = props || {}\n\n const fields: Field[] = [\n {\n name: 'variantType',\n type: 'relationship',\n admin: {\n readOnly: true,\n },\n relationTo: variantTypesSlug,\n required: true,\n },\n {\n name: 'label',\n type: 'text',\n required: true,\n },\n {\n name: 'value',\n type: 'text',\n admin: {\n description: 'should be defaulted or dynamic based on label',\n },\n required: true,\n },\n ]\n\n const baseConfig: CollectionConfig = {\n slug: 'variantOptions',\n access: {\n create: access.isAdmin,\n delete: access.isAdmin,\n read: access.publicAccess,\n update: access.isAdmin,\n },\n admin: {\n group: false,\n useAsTitle: 'label',\n },\n fields,\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:variantOptions'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:variantOption'),\n },\n trash: true,\n }\n\n return { ...baseConfig }\n}\n"],"names":["createVariantOptionsCollection","props","access","variantTypesSlug","fields","name","type","admin","readOnly","relationTo","required","description","baseConfig","slug","create","isAdmin","delete","read","publicAccess","update","group","useAsTitle","labels","plural","t","singular","trash"],"mappings":"AAYA,OAAO,MAAMA,iCAAqE,CAACC;IACjF,MAAM,EAAEC,MAAM,EAAEC,mBAAmB,cAAc,EAAE,GAAGF,SAAS,CAAC;IAEhE,MAAMG,SAAkB;QACtB;YACEC,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLC,UAAU;YACZ;YACAC,YAAYN;YACZO,UAAU;QACZ;QACA;YACEL,MAAM;YACNC,MAAM;YACNI,UAAU;QACZ;QACA;YACEL,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLI,aAAa;YACf;YACAD,UAAU;QACZ;KACD;IAED,MAAME,aAA+B;QACnCC,MAAM;QACNX,QAAQ;YACNY,QAAQZ,OAAOa,OAAO;YACtBC,QAAQd,OAAOa,OAAO;YACtBE,MAAMf,OAAOgB,YAAY;YACzBC,QAAQjB,OAAOa,OAAO;QACxB;QACAR,OAAO;YACLa,OAAO;YACPC,YAAY;QACd;
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/variants/createVariantOptionsCollection.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { AccessConfig } from '../../types/index.js'\n\ntype Props = {\n access: Pick<AccessConfig, 'isAdmin' | 'publicAccess'>\n /**\n * Slug of the variant types collection, defaults to 'variantTypes'.\n */\n variantTypesSlug?: string\n}\n\nexport const createVariantOptionsCollection: (props: Props) => CollectionConfig = (props) => {\n const { access, variantTypesSlug = 'variantTypes' } = props || {}\n\n const fields: Field[] = [\n {\n name: 'variantType',\n type: 'relationship',\n admin: {\n readOnly: true,\n },\n relationTo: variantTypesSlug,\n required: true,\n },\n {\n name: 'label',\n type: 'text',\n required: true,\n },\n {\n name: 'value',\n type: 'text',\n admin: {\n description: 'should be defaulted or dynamic based on label',\n },\n required: true,\n },\n ]\n\n const baseConfig: CollectionConfig = {\n slug: 'variantOptions',\n access: {\n create: access.isAdmin,\n delete: access.isAdmin,\n read: access.publicAccess,\n update: access.isAdmin,\n },\n admin: {\n group: false,\n useAsTitle: 'label',\n },\n authorship: false,\n fields,\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:variantOptions'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:variantOption'),\n },\n trash: true,\n }\n\n return { ...baseConfig }\n}\n"],"names":["createVariantOptionsCollection","props","access","variantTypesSlug","fields","name","type","admin","readOnly","relationTo","required","description","baseConfig","slug","create","isAdmin","delete","read","publicAccess","update","group","useAsTitle","authorship","labels","plural","t","singular","trash"],"mappings":"AAYA,OAAO,MAAMA,iCAAqE,CAACC;IACjF,MAAM,EAAEC,MAAM,EAAEC,mBAAmB,cAAc,EAAE,GAAGF,SAAS,CAAC;IAEhE,MAAMG,SAAkB;QACtB;YACEC,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLC,UAAU;YACZ;YACAC,YAAYN;YACZO,UAAU;QACZ;QACA;YACEL,MAAM;YACNC,MAAM;YACNI,UAAU;QACZ;QACA;YACEL,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLI,aAAa;YACf;YACAD,UAAU;QACZ;KACD;IAED,MAAME,aAA+B;QACnCC,MAAM;QACNX,QAAQ;YACNY,QAAQZ,OAAOa,OAAO;YACtBC,QAAQd,OAAOa,OAAO;YACtBE,MAAMf,OAAOgB,YAAY;YACzBC,QAAQjB,OAAOa,OAAO;QACxB;QACAR,OAAO;YACLa,OAAO;YACPC,YAAY;QACd;QACAC,YAAY;QACZlB;QACAmB,QAAQ;YACNC,QAAQ,CAAC,EAAEC,CAAC,EAAE,GACZ,+DAA+D;gBAC/DA,EAAE;YACJC,UAAU,CAAC,EAAED,CAAC,EAAE,GACd,+DAA+D;gBAC/DA,EAAE;QACN;QACAE,OAAO;IACT;IAEA,OAAO;QAAE,GAAGf,UAAU;IAAC;AACzB,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createVariantTypesCollection.d.ts","sourceRoot":"","sources":["../../../src/collections/variants/createVariantTypesCollection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAS,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AAExD,KAAK,KAAK,GAAG;IACX,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,SAAS,GAAG,cAAc,CAAC,CAAA;IACtD;;OAEG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAA;CAC5B,CAAA;AAED,eAAO,MAAM,4BAA4B,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,
|
|
1
|
+
{"version":3,"file":"createVariantTypesCollection.d.ts","sourceRoot":"","sources":["../../../src/collections/variants/createVariantTypesCollection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAS,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AAExD,KAAK,KAAK,GAAG;IACX,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,SAAS,GAAG,cAAc,CAAC,CAAA;IACtD;;OAEG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAA;CAC5B,CAAA;AAED,eAAO,MAAM,4BAA4B,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,gBAkD5D,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/variants/createVariantTypesCollection.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { AccessConfig } from '../../types/index.js'\n\ntype Props = {\n access: Pick<AccessConfig, 'isAdmin' | 'publicAccess'>\n /**\n * Slug of the variant options collection, defaults to 'variantOptions'.\n */\n variantOptionsSlug?: string\n}\n\nexport const createVariantTypesCollection: (props: Props) => CollectionConfig = (props) => {\n const { access, variantOptionsSlug = 'variantOptions' } = props || {}\n\n const fields: Field[] = [\n {\n name: 'label',\n type: 'text',\n required: true,\n },\n {\n name: 'name',\n type: 'text',\n required: true,\n },\n {\n name: 'options',\n type: 'join',\n collection: variantOptionsSlug,\n maxDepth: 2,\n on: 'variantType',\n orderable: true,\n },\n ]\n\n const baseConfig: CollectionConfig = {\n slug: 'variantTypes',\n access: {\n create: access.isAdmin,\n delete: access.isAdmin,\n read: access.publicAccess,\n update: access.isAdmin,\n },\n admin: {\n group: false,\n useAsTitle: 'label',\n },\n fields,\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:variantTypes'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:variantType'),\n },\n trash: true,\n }\n\n return { ...baseConfig }\n}\n"],"names":["createVariantTypesCollection","props","access","variantOptionsSlug","fields","name","type","required","collection","maxDepth","on","orderable","baseConfig","slug","create","isAdmin","delete","read","publicAccess","update","admin","group","useAsTitle","labels","plural","t","singular","trash"],"mappings":"AAYA,OAAO,MAAMA,+BAAmE,CAACC;IAC/E,MAAM,EAAEC,MAAM,EAAEC,qBAAqB,gBAAgB,EAAE,GAAGF,SAAS,CAAC;IAEpE,MAAMG,SAAkB;QACtB;YACEC,MAAM;YACNC,MAAM;YACNC,UAAU;QACZ;QACA;YACEF,MAAM;YACNC,MAAM;YACNC,UAAU;QACZ;QACA;YACEF,MAAM;YACNC,MAAM;YACNE,YAAYL;YACZM,UAAU;YACVC,IAAI;YACJC,WAAW;QACb;KACD;IAED,MAAMC,aAA+B;QACnCC,MAAM;QACNX,QAAQ;YACNY,QAAQZ,OAAOa,OAAO;YACtBC,QAAQd,OAAOa,OAAO;YACtBE,MAAMf,OAAOgB,YAAY;YACzBC,QAAQjB,OAAOa,OAAO;QACxB;QACAK,OAAO;YACLC,OAAO;YACPC,YAAY;QACd;
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/variants/createVariantTypesCollection.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { AccessConfig } from '../../types/index.js'\n\ntype Props = {\n access: Pick<AccessConfig, 'isAdmin' | 'publicAccess'>\n /**\n * Slug of the variant options collection, defaults to 'variantOptions'.\n */\n variantOptionsSlug?: string\n}\n\nexport const createVariantTypesCollection: (props: Props) => CollectionConfig = (props) => {\n const { access, variantOptionsSlug = 'variantOptions' } = props || {}\n\n const fields: Field[] = [\n {\n name: 'label',\n type: 'text',\n required: true,\n },\n {\n name: 'name',\n type: 'text',\n required: true,\n },\n {\n name: 'options',\n type: 'join',\n collection: variantOptionsSlug,\n maxDepth: 2,\n on: 'variantType',\n orderable: true,\n },\n ]\n\n const baseConfig: CollectionConfig = {\n slug: 'variantTypes',\n access: {\n create: access.isAdmin,\n delete: access.isAdmin,\n read: access.publicAccess,\n update: access.isAdmin,\n },\n admin: {\n group: false,\n useAsTitle: 'label',\n },\n authorship: false,\n fields,\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:variantTypes'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:variantType'),\n },\n trash: true,\n }\n\n return { ...baseConfig }\n}\n"],"names":["createVariantTypesCollection","props","access","variantOptionsSlug","fields","name","type","required","collection","maxDepth","on","orderable","baseConfig","slug","create","isAdmin","delete","read","publicAccess","update","admin","group","useAsTitle","authorship","labels","plural","t","singular","trash"],"mappings":"AAYA,OAAO,MAAMA,+BAAmE,CAACC;IAC/E,MAAM,EAAEC,MAAM,EAAEC,qBAAqB,gBAAgB,EAAE,GAAGF,SAAS,CAAC;IAEpE,MAAMG,SAAkB;QACtB;YACEC,MAAM;YACNC,MAAM;YACNC,UAAU;QACZ;QACA;YACEF,MAAM;YACNC,MAAM;YACNC,UAAU;QACZ;QACA;YACEF,MAAM;YACNC,MAAM;YACNE,YAAYL;YACZM,UAAU;YACVC,IAAI;YACJC,WAAW;QACb;KACD;IAED,MAAMC,aAA+B;QACnCC,MAAM;QACNX,QAAQ;YACNY,QAAQZ,OAAOa,OAAO;YACtBC,QAAQd,OAAOa,OAAO;YACtBE,MAAMf,OAAOgB,YAAY;YACzBC,QAAQjB,OAAOa,OAAO;QACxB;QACAK,OAAO;YACLC,OAAO;YACPC,YAAY;QACd;QACAC,YAAY;QACZnB;QACAoB,QAAQ;YACNC,QAAQ,CAAC,EAAEC,CAAC,EAAE,GACZ,+DAA+D;gBAC/DA,EAAE;YACJC,UAAU,CAAC,EAAED,CAAC,EAAE,GACd,+DAA+D;gBAC/DA,EAAE;QACN;QACAE,OAAO;IACT;IAEA,OAAO;QAAE,GAAGhB,UAAU;IAAC;AACzB,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"beforeChange.d.ts","sourceRoot":"","sources":["../../../../../src/collections/variants/createVariantsCollection/hooks/beforeChange.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,SAAS,CAAA;AAEzD,KAAK,KAAK,GAAG;IACX,YAAY,EAAE,MAAM,CAAA;IACpB,kBAAkB,EAAE,MAAM,CAAA;CAC3B,CAAA;AAED,eAAO,MAAM,8BAA8B,EAAE,CAAC,IAAI,EAAE,KAAK,KAAK,
|
|
1
|
+
{"version":3,"file":"beforeChange.d.ts","sourceRoot":"","sources":["../../../../../src/collections/variants/createVariantsCollection/hooks/beforeChange.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,SAAS,CAAA;AAEzD,KAAK,KAAK,GAAG;IACX,YAAY,EAAE,MAAM,CAAA;IACpB,kBAAkB,EAAE,MAAM,CAAA;CAC3B,CAAA;AAED,eAAO,MAAM,8BAA8B,EAAE,CAAC,IAAI,EAAE,KAAK,KAAK,0BA6C3D,CAAA"}
|
|
@@ -6,6 +6,7 @@ export const variantsCollectionBeforeChange = ({ productsSlug, variantOptionsSlu
|
|
|
6
6
|
id: productID,
|
|
7
7
|
collection: productsSlug,
|
|
8
8
|
depth: 0,
|
|
9
|
+
overrideAccess: true,
|
|
9
10
|
select: {
|
|
10
11
|
title: true,
|
|
11
12
|
variantTypes: true
|
|
@@ -19,6 +20,7 @@ export const variantsCollectionBeforeChange = ({ productsSlug, variantOptionsSlu
|
|
|
19
20
|
id: option,
|
|
20
21
|
collection: variantOptionsSlug,
|
|
21
22
|
depth: 0,
|
|
23
|
+
overrideAccess: true,
|
|
22
24
|
select: {
|
|
23
25
|
label: true
|
|
24
26
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/collections/variants/createVariantsCollection/hooks/beforeChange.ts"],"sourcesContent":["import type { CollectionBeforeChangeHook } from 'payload'\n\ntype Props = {\n productsSlug: string\n variantOptionsSlug: string\n}\n\nexport const variantsCollectionBeforeChange: (args: Props) => CollectionBeforeChangeHook =\n ({ productsSlug, variantOptionsSlug }) =>\n async ({ data, req }) => {\n if (data?.options?.length && data.options.length > 0) {\n const titleArray: string[] = []\n const productID = data.product\n const product = await req.payload.findByID({\n id: productID,\n collection: productsSlug,\n depth: 0,\n select: {\n title: true,\n variantTypes: true,\n },\n })\n\n if (product.title && typeof product.title === 'string') {\n titleArray.push(product.title)\n }\n\n for (const option of data.options) {\n const variantOption = await req.payload.findByID({\n id: option,\n collection: variantOptionsSlug,\n depth: 0,\n select: {\n label: true,\n },\n })\n\n if (!variantOption) {\n continue\n }\n\n if (variantOption.label && typeof variantOption.label === 'string') {\n titleArray.push(variantOption.label)\n }\n }\n\n data.title = titleArray.join(' — ')\n }\n\n return data\n }\n"],"names":["variantsCollectionBeforeChange","productsSlug","variantOptionsSlug","data","req","options","length","titleArray","productID","product","payload","findByID","id","collection","depth","select","title","variantTypes","push","option","variantOption","label","join"],"mappings":"AAOA,OAAO,MAAMA,iCACX,CAAC,EAAEC,YAAY,EAAEC,kBAAkB,EAAE,GACrC,OAAO,EAAEC,IAAI,EAAEC,GAAG,EAAE;QAClB,IAAID,MAAME,SAASC,UAAUH,KAAKE,OAAO,CAACC,MAAM,GAAG,GAAG;YACpD,MAAMC,aAAuB,EAAE;YAC/B,MAAMC,YAAYL,KAAKM,OAAO;YAC9B,MAAMA,UAAU,MAAML,IAAIM,OAAO,CAACC,QAAQ,CAAC;gBACzCC,IAAIJ;gBACJK,YAAYZ;gBACZa,OAAO;gBACPC,QAAQ;oBACNC,OAAO;oBACPC,cAAc;gBAChB;YACF;YAEA,
|
|
1
|
+
{"version":3,"sources":["../../../../../src/collections/variants/createVariantsCollection/hooks/beforeChange.ts"],"sourcesContent":["import type { CollectionBeforeChangeHook } from 'payload'\n\ntype Props = {\n productsSlug: string\n variantOptionsSlug: string\n}\n\nexport const variantsCollectionBeforeChange: (args: Props) => CollectionBeforeChangeHook =\n ({ productsSlug, variantOptionsSlug }) =>\n async ({ data, req }) => {\n if (data?.options?.length && data.options.length > 0) {\n const titleArray: string[] = []\n const productID = data.product\n const product = await req.payload.findByID({\n id: productID,\n collection: productsSlug,\n depth: 0,\n overrideAccess: true,\n select: {\n title: true,\n variantTypes: true,\n },\n })\n\n if (product.title && typeof product.title === 'string') {\n titleArray.push(product.title)\n }\n\n for (const option of data.options) {\n const variantOption = await req.payload.findByID({\n id: option,\n collection: variantOptionsSlug,\n depth: 0,\n overrideAccess: true,\n select: {\n label: true,\n },\n })\n\n if (!variantOption) {\n continue\n }\n\n if (variantOption.label && typeof variantOption.label === 'string') {\n titleArray.push(variantOption.label)\n }\n }\n\n data.title = titleArray.join(' — ')\n }\n\n return data\n }\n"],"names":["variantsCollectionBeforeChange","productsSlug","variantOptionsSlug","data","req","options","length","titleArray","productID","product","payload","findByID","id","collection","depth","overrideAccess","select","title","variantTypes","push","option","variantOption","label","join"],"mappings":"AAOA,OAAO,MAAMA,iCACX,CAAC,EAAEC,YAAY,EAAEC,kBAAkB,EAAE,GACrC,OAAO,EAAEC,IAAI,EAAEC,GAAG,EAAE;QAClB,IAAID,MAAME,SAASC,UAAUH,KAAKE,OAAO,CAACC,MAAM,GAAG,GAAG;YACpD,MAAMC,aAAuB,EAAE;YAC/B,MAAMC,YAAYL,KAAKM,OAAO;YAC9B,MAAMA,UAAU,MAAML,IAAIM,OAAO,CAACC,QAAQ,CAAC;gBACzCC,IAAIJ;gBACJK,YAAYZ;gBACZa,OAAO;gBACPC,gBAAgB;gBAChBC,QAAQ;oBACNC,OAAO;oBACPC,cAAc;gBAChB;YACF;YAEA,IAAIT,QAAQQ,KAAK,IAAI,OAAOR,QAAQQ,KAAK,KAAK,UAAU;gBACtDV,WAAWY,IAAI,CAACV,QAAQQ,KAAK;YAC/B;YAEA,KAAK,MAAMG,UAAUjB,KAAKE,OAAO,CAAE;gBACjC,MAAMgB,gBAAgB,MAAMjB,IAAIM,OAAO,CAACC,QAAQ,CAAC;oBAC/CC,IAAIQ;oBACJP,YAAYX;oBACZY,OAAO;oBACPC,gBAAgB;oBAChBC,QAAQ;wBACNM,OAAO;oBACT;gBACF;gBAEA,IAAI,CAACD,eAAe;oBAClB;gBACF;gBAEA,IAAIA,cAAcC,KAAK,IAAI,OAAOD,cAAcC,KAAK,KAAK,UAAU;oBAClEf,WAAWY,IAAI,CAACE,cAAcC,KAAK;gBACrC;YACF;YAEAnB,KAAKc,KAAK,GAAGV,WAAWgB,IAAI,CAAC;QAC/B;QAEA,OAAOpB;IACT,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validateOptions.d.ts","sourceRoot":"","sources":["../../../../../src/collections/variants/createVariantsCollection/hooks/validateOptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAEvC,KAAK,KAAK,GAAG;IACX,sBAAsB,CAAC,EAAE,MAAM,CAAA;CAChC,CAAA;AAED,eAAO,MAAM,eAAe,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,KAAK,
|
|
1
|
+
{"version":3,"file":"validateOptions.d.ts","sourceRoot":"","sources":["../../../../../src/collections/variants/createVariantsCollection/hooks/validateOptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAEvC,KAAK,KAAK,GAAG;IACX,sBAAsB,CAAC,EAAE,MAAM,CAAA;CAChC,CAAA;AAED,eAAO,MAAM,eAAe,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,KAAK,QAqE9C,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/collections/variants/createVariantsCollection/hooks/validateOptions.ts"],"sourcesContent":["import type { Validate } from 'payload'\n\ntype Props = {\n productsCollectionSlug?: string\n}\n\nexport const validateOptions: (props?: Props) => Validate =\n (props) =>\n async (values, { data, req }) => {\n const { productsCollectionSlug = 'products' } = props || {}\n const { t } = req\n\n if (!values || values.length === 0) {\n // @ts-expect-error - TODO: Fix types\n return t('ecommerce:variantOptionsRequired')\n }\n\n const productID = data.product\n\n if (!productID) {\n // @ts-expect-error - TODO: Fix types\n return t('ecommerce:productRequired')\n }\n\n const product = await req.payload.findByID({\n id: productID,\n collection: productsCollectionSlug,\n depth: 1,\n joins: {\n variants: {\n where: {\n deletedAt: { exists: false },\n ...(data.id && {\n id: {\n not_equals: data.id, // exclude the current variant from the search\n },\n }),\n },\n },\n },\n select: {\n variants: true,\n variantTypes: true,\n },\n user: req.user,\n })\n\n // @ts-expect-error - TODO: Fix types\n const variants = product.variants?.docs ?? []\n\n // @ts-expect-error - TODO: Fix types\n if (values.length < product?.variantTypes?.length) {\n // @ts-expect-error - TODO: Fix types\n return t('ecommerce:variantOptionsRequiredAll')\n }\n\n if (variants.length > 0) {\n const existingOptions: (number | string)[][] = []\n\n variants.forEach((variant: any) => {\n existingOptions.push(variant.options)\n })\n\n const exists = existingOptions.some(\n (combo) => combo.length === values.length && combo.every((val) => values.includes(val)),\n )\n\n if (exists) {\n // @ts-expect-error - TODO: Fix types\n return t('ecommerce:variantOptionsAlreadyExists')\n }\n }\n\n return true\n }\n"],"names":["validateOptions","props","values","data","req","productsCollectionSlug","t","length","productID","product","payload","findByID","id","collection","depth","joins","variants","where","deletedAt","exists","not_equals","select","variantTypes","user","docs","existingOptions","forEach","variant","push","options","some","combo","every","val","includes"],"mappings":"AAMA,OAAO,MAAMA,kBACX,CAACC,QACD,OAAOC,QAAQ,EAAEC,IAAI,EAAEC,GAAG,EAAE;QAC1B,MAAM,EAAEC,yBAAyB,UAAU,EAAE,GAAGJ,SAAS,CAAC;QAC1D,MAAM,EAAEK,CAAC,EAAE,GAAGF;QAEd,IAAI,CAACF,UAAUA,OAAOK,MAAM,KAAK,GAAG;YAClC,qCAAqC;YACrC,OAAOD,EAAE;QACX;QAEA,MAAME,YAAYL,KAAKM,OAAO;QAE9B,IAAI,CAACD,WAAW;YACd,qCAAqC;YACrC,OAAOF,EAAE;QACX;QAEA,MAAMG,UAAU,MAAML,IAAIM,OAAO,CAACC,QAAQ,CAAC;YACzCC,IAAIJ;YACJK,YAAYR;YACZS,OAAO;YACPC,OAAO;gBACLC,UAAU;oBACRC,OAAO;wBACLC,WAAW;4BAAEC,QAAQ;wBAAM;wBAC3B,GAAIhB,KAAKS,EAAE,IAAI;4BACbA,IAAI;gCACFQ,YAAYjB,KAAKS,EAAE;4BACrB;wBACF,CAAC;oBACH;gBACF;YACF;YACAS,QAAQ;
|
|
1
|
+
{"version":3,"sources":["../../../../../src/collections/variants/createVariantsCollection/hooks/validateOptions.ts"],"sourcesContent":["import type { Validate } from 'payload'\n\ntype Props = {\n productsCollectionSlug?: string\n}\n\nexport const validateOptions: (props?: Props) => Validate =\n (props) =>\n async (values, { data, req }) => {\n const { productsCollectionSlug = 'products' } = props || {}\n const { t } = req\n\n if (!values || values.length === 0) {\n // @ts-expect-error - TODO: Fix types\n return t('ecommerce:variantOptionsRequired')\n }\n\n const productID = data.product\n\n if (!productID) {\n // @ts-expect-error - TODO: Fix types\n return t('ecommerce:productRequired')\n }\n\n const product = await req.payload.findByID({\n id: productID,\n collection: productsCollectionSlug,\n depth: 1,\n joins: {\n variants: {\n where: {\n deletedAt: { exists: false },\n ...(data.id && {\n id: {\n not_equals: data.id, // exclude the current variant from the search\n },\n }),\n },\n },\n },\n overrideAccess: true,\n select: {\n variants: true,\n variantTypes: true,\n },\n user: req.user,\n })\n\n // @ts-expect-error - TODO: Fix types\n const variants = product.variants?.docs ?? []\n\n // @ts-expect-error - TODO: Fix types\n if (values.length < product?.variantTypes?.length) {\n // @ts-expect-error - TODO: Fix types\n return t('ecommerce:variantOptionsRequiredAll')\n }\n\n if (variants.length > 0) {\n const existingOptions: (number | string)[][] = []\n\n variants.forEach((variant: any) => {\n existingOptions.push(variant.options)\n })\n\n const exists = existingOptions.some(\n (combo) => combo.length === values.length && combo.every((val) => values.includes(val)),\n )\n\n if (exists) {\n // @ts-expect-error - TODO: Fix types\n return t('ecommerce:variantOptionsAlreadyExists')\n }\n }\n\n return true\n }\n"],"names":["validateOptions","props","values","data","req","productsCollectionSlug","t","length","productID","product","payload","findByID","id","collection","depth","joins","variants","where","deletedAt","exists","not_equals","overrideAccess","select","variantTypes","user","docs","existingOptions","forEach","variant","push","options","some","combo","every","val","includes"],"mappings":"AAMA,OAAO,MAAMA,kBACX,CAACC,QACD,OAAOC,QAAQ,EAAEC,IAAI,EAAEC,GAAG,EAAE;QAC1B,MAAM,EAAEC,yBAAyB,UAAU,EAAE,GAAGJ,SAAS,CAAC;QAC1D,MAAM,EAAEK,CAAC,EAAE,GAAGF;QAEd,IAAI,CAACF,UAAUA,OAAOK,MAAM,KAAK,GAAG;YAClC,qCAAqC;YACrC,OAAOD,EAAE;QACX;QAEA,MAAME,YAAYL,KAAKM,OAAO;QAE9B,IAAI,CAACD,WAAW;YACd,qCAAqC;YACrC,OAAOF,EAAE;QACX;QAEA,MAAMG,UAAU,MAAML,IAAIM,OAAO,CAACC,QAAQ,CAAC;YACzCC,IAAIJ;YACJK,YAAYR;YACZS,OAAO;YACPC,OAAO;gBACLC,UAAU;oBACRC,OAAO;wBACLC,WAAW;4BAAEC,QAAQ;wBAAM;wBAC3B,GAAIhB,KAAKS,EAAE,IAAI;4BACbA,IAAI;gCACFQ,YAAYjB,KAAKS,EAAE;4BACrB;wBACF,CAAC;oBACH;gBACF;YACF;YACAS,gBAAgB;YAChBC,QAAQ;gBACNN,UAAU;gBACVO,cAAc;YAChB;YACAC,MAAMpB,IAAIoB,IAAI;QAChB;QAEA,qCAAqC;QACrC,MAAMR,WAAWP,QAAQO,QAAQ,EAAES,QAAQ,EAAE;QAE7C,qCAAqC;QACrC,IAAIvB,OAAOK,MAAM,GAAGE,SAASc,cAAchB,QAAQ;YACjD,qCAAqC;YACrC,OAAOD,EAAE;QACX;QAEA,IAAIU,SAAST,MAAM,GAAG,GAAG;YACvB,MAAMmB,kBAAyC,EAAE;YAEjDV,SAASW,OAAO,CAAC,CAACC;gBAChBF,gBAAgBG,IAAI,CAACD,QAAQE,OAAO;YACtC;YAEA,MAAMX,SAASO,gBAAgBK,IAAI,CACjC,CAACC,QAAUA,MAAMzB,MAAM,KAAKL,OAAOK,MAAM,IAAIyB,MAAMC,KAAK,CAAC,CAACC,MAAQhC,OAAOiC,QAAQ,CAACD;YAGpF,IAAIf,QAAQ;gBACV,qCAAqC;gBACrC,OAAOb,EAAE;YACX;QACF;QAEA,OAAO;IACT,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/collections/variants/createVariantsCollection/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAS,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAO9F,KAAK,KAAK,GAAG;IACX,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,wBAAwB,GAAG,SAAS,CAAC,CAAA;IAChE,gBAAgB,CAAC,EAAE,gBAAgB,CAAA;IACnC;;OAEG;IACH,SAAS,CAAC,EAAE,OAAO,GAAG,eAAe,CAAA;IACrC;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;OAEG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B,CAAA;AAED,eAAO,MAAM,wBAAwB,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/collections/variants/createVariantsCollection/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAS,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAO9F,KAAK,KAAK,GAAG;IACX,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,wBAAwB,GAAG,SAAS,CAAC,CAAA;IAChE,gBAAgB,CAAC,EAAE,gBAAgB,CAAA;IACnC;;OAEG;IACH,SAAS,CAAC,EAAE,OAAO,GAAG,eAAe,CAAA;IACrC;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;OAEG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B,CAAA;AAED,eAAO,MAAM,wBAAwB,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,gBA2GxD,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/collections/variants/createVariantsCollection/index.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { AccessConfig, CurrenciesConfig, InventoryConfig } from '../../../types/index.js'\n\nimport { inventoryField } from '../../../fields/inventoryField.js'\nimport { pricesField } from '../../../fields/pricesField.js'\nimport { variantsCollectionBeforeChange as beforeChange } from './hooks/beforeChange.js'\nimport { validateOptions } from './hooks/validateOptions.js'\n\ntype Props = {\n access: Pick<AccessConfig, 'adminOrPublishedStatus' | 'isAdmin'>\n currenciesConfig?: CurrenciesConfig\n /**\n * Enables inventory tracking for variants. Defaults to true.\n */\n inventory?: boolean | InventoryConfig\n /**\n * Slug of the products collection, defaults to 'products'.\n */\n productsSlug?: string\n /**\n * Slug of the variant options collection, defaults to 'variantOptions'.\n */\n variantOptionsSlug?: string\n /**\n * Slug of the variant types collection, defaults to 'variantTypes'.\n */\n variantTypesSlug?: string\n}\n\nexport const createVariantsCollection: (props: Props) => CollectionConfig = (props) => {\n const {\n access,\n currenciesConfig,\n inventory = true,\n productsSlug = 'products',\n variantOptionsSlug = 'variantOptions',\n variantTypesSlug = 'variantTypes',\n } = props || {}\n const { supportedCurrencies } = currenciesConfig || {}\n\n const fields: Field[] = [\n {\n name: 'title',\n type: 'text',\n admin: {\n description:\n 'Used for administrative purposes, not shown to customers. This is populated by default.',\n },\n },\n {\n name: 'product',\n type: 'relationship',\n admin: {\n position: 'sidebar',\n readOnly: true,\n },\n relationTo: productsSlug,\n required: true,\n },\n {\n // This might need to be a custom component, to show a selector for each variant that is\n // enabled on the parent product\n // - separate select inputs, each showing only a specific variant (w/ options)\n // - it will save data to the DB as IDs in this relationship field\n // and needs a validate function as well which enforces that the options are fully specified, and accurate\n name: 'options',\n type: 'relationship',\n admin: {\n components: {\n Field: {\n path: '@payloadcms/plugin-ecommerce/rsc#VariantOptionsSelector',\n },\n },\n },\n custom: {\n productsSlug,\n variantTypesSlug,\n },\n hasMany: true,\n label: 'Variant options',\n relationTo: variantOptionsSlug,\n required: true,\n validate: validateOptions({ productsCollectionSlug: productsSlug }),\n },\n ...(inventory ? [inventoryField()] : []),\n ]\n\n if (supportedCurrencies?.length && supportedCurrencies.length > 0) {\n const currencyOptions: string[] = []\n\n supportedCurrencies.forEach((currency) => {\n currencyOptions.push(currency.code)\n })\n\n if (currenciesConfig) {\n fields.push(...pricesField({ currenciesConfig }))\n }\n }\n\n const baseConfig: CollectionConfig = {\n slug: 'variants',\n access: {\n create: access.isAdmin,\n delete: access.isAdmin,\n read: access.adminOrPublishedStatus,\n update: access.isAdmin,\n },\n admin: {\n description: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:variantsCollectionDescription'),\n group: false,\n useAsTitle: 'title',\n },\n fields,\n hooks: {\n beforeChange: [beforeChange({ productsSlug, variantOptionsSlug })],\n },\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:variants'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:variant'),\n },\n trash: true,\n versions: {\n drafts: {\n autosave: true,\n },\n },\n }\n\n return baseConfig\n}\n"],"names":["inventoryField","pricesField","variantsCollectionBeforeChange","beforeChange","validateOptions","createVariantsCollection","props","access","currenciesConfig","inventory","productsSlug","variantOptionsSlug","variantTypesSlug","supportedCurrencies","fields","name","type","admin","description","position","readOnly","relationTo","required","components","Field","path","custom","hasMany","label","validate","productsCollectionSlug","length","currencyOptions","forEach","currency","push","code","baseConfig","slug","create","isAdmin","delete","read","adminOrPublishedStatus","update","t","group","useAsTitle","hooks","labels","plural","singular","trash","versions","drafts","autosave"],"mappings":"AAIA,SAASA,cAAc,QAAQ,oCAAmC;AAClE,SAASC,WAAW,QAAQ,iCAAgC;AAC5D,SAASC,kCAAkCC,YAAY,QAAQ,0BAAyB;AACxF,SAASC,eAAe,QAAQ,6BAA4B;AAuB5D,OAAO,MAAMC,2BAA+D,CAACC;IAC3E,MAAM,EACJC,MAAM,EACNC,gBAAgB,EAChBC,YAAY,IAAI,EAChBC,eAAe,UAAU,EACzBC,qBAAqB,gBAAgB,EACrCC,mBAAmB,cAAc,EAClC,GAAGN,SAAS,CAAC;IACd,MAAM,EAAEO,mBAAmB,EAAE,GAAGL,oBAAoB,CAAC;IAErD,MAAMM,SAAkB;QACtB;YACEC,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLC,aACE;YACJ;QACF;QACA;YACEH,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLE,UAAU;gBACVC,UAAU;YACZ;YACAC,YAAYX;YACZY,UAAU;QACZ;QACA;YACE,wFAAwF;YACxF,gCAAgC;YAChC,8EAA8E;YAC9E,kEAAkE;YAClE,0GAA0G;YAC1GP,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLM,YAAY;oBACVC,OAAO;wBACLC,MAAM;oBACR;gBACF;YACF;YACAC,QAAQ;gBACNhB;gBACAE;YACF;YACAe,SAAS;YACTC,OAAO;YACPP,YAAYV;YACZW,UAAU;YACVO,UAAUzB,gBAAgB;gBAAE0B,wBAAwBpB;YAAa;QACnE;WACID,YAAY;YAACT;SAAiB,GAAG,EAAE;KACxC;IAED,IAAIa,qBAAqBkB,UAAUlB,oBAAoBkB,MAAM,GAAG,GAAG;QACjE,MAAMC,kBAA4B,EAAE;QAEpCnB,oBAAoBoB,OAAO,CAAC,CAACC;YAC3BF,gBAAgBG,IAAI,CAACD,SAASE,IAAI;QACpC;QAEA,IAAI5B,kBAAkB;YACpBM,OAAOqB,IAAI,IAAIlC,YAAY;gBAAEO;YAAiB;QAChD;IACF;IAEA,MAAM6B,aAA+B;QACnCC,MAAM;QACN/B,QAAQ;YACNgC,QAAQhC,OAAOiC,OAAO;YACtBC,QAAQlC,OAAOiC,OAAO;YACtBE,MAAMnC,OAAOoC,sBAAsB;YACnCC,QAAQrC,OAAOiC,OAAO;QACxB;QACAvB,OAAO;YACLC,aAAa,CAAC,EAAE2B,CAAC,EAAE,GACjB,+DAA+D;gBAC/DA,EAAE;YACJC,OAAO;YACPC,YAAY;QACd;
|
|
1
|
+
{"version":3,"sources":["../../../../src/collections/variants/createVariantsCollection/index.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { AccessConfig, CurrenciesConfig, InventoryConfig } from '../../../types/index.js'\n\nimport { inventoryField } from '../../../fields/inventoryField.js'\nimport { pricesField } from '../../../fields/pricesField.js'\nimport { variantsCollectionBeforeChange as beforeChange } from './hooks/beforeChange.js'\nimport { validateOptions } from './hooks/validateOptions.js'\n\ntype Props = {\n access: Pick<AccessConfig, 'adminOrPublishedStatus' | 'isAdmin'>\n currenciesConfig?: CurrenciesConfig\n /**\n * Enables inventory tracking for variants. Defaults to true.\n */\n inventory?: boolean | InventoryConfig\n /**\n * Slug of the products collection, defaults to 'products'.\n */\n productsSlug?: string\n /**\n * Slug of the variant options collection, defaults to 'variantOptions'.\n */\n variantOptionsSlug?: string\n /**\n * Slug of the variant types collection, defaults to 'variantTypes'.\n */\n variantTypesSlug?: string\n}\n\nexport const createVariantsCollection: (props: Props) => CollectionConfig = (props) => {\n const {\n access,\n currenciesConfig,\n inventory = true,\n productsSlug = 'products',\n variantOptionsSlug = 'variantOptions',\n variantTypesSlug = 'variantTypes',\n } = props || {}\n const { supportedCurrencies } = currenciesConfig || {}\n\n const fields: Field[] = [\n {\n name: 'title',\n type: 'text',\n admin: {\n description:\n 'Used for administrative purposes, not shown to customers. This is populated by default.',\n },\n },\n {\n name: 'product',\n type: 'relationship',\n admin: {\n position: 'sidebar',\n readOnly: true,\n },\n relationTo: productsSlug,\n required: true,\n },\n {\n // This might need to be a custom component, to show a selector for each variant that is\n // enabled on the parent product\n // - separate select inputs, each showing only a specific variant (w/ options)\n // - it will save data to the DB as IDs in this relationship field\n // and needs a validate function as well which enforces that the options are fully specified, and accurate\n name: 'options',\n type: 'relationship',\n admin: {\n components: {\n Field: {\n path: '@payloadcms/plugin-ecommerce/rsc#VariantOptionsSelector',\n },\n },\n },\n custom: {\n productsSlug,\n variantTypesSlug,\n },\n hasMany: true,\n label: 'Variant options',\n relationTo: variantOptionsSlug,\n required: true,\n validate: validateOptions({ productsCollectionSlug: productsSlug }),\n },\n ...(inventory ? [inventoryField()] : []),\n ]\n\n if (supportedCurrencies?.length && supportedCurrencies.length > 0) {\n const currencyOptions: string[] = []\n\n supportedCurrencies.forEach((currency) => {\n currencyOptions.push(currency.code)\n })\n\n if (currenciesConfig) {\n fields.push(...pricesField({ currenciesConfig }))\n }\n }\n\n const baseConfig: CollectionConfig = {\n slug: 'variants',\n access: {\n create: access.isAdmin,\n delete: access.isAdmin,\n read: access.adminOrPublishedStatus,\n update: access.isAdmin,\n },\n admin: {\n description: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:variantsCollectionDescription'),\n group: false,\n useAsTitle: 'title',\n },\n authorship: false,\n fields,\n hooks: {\n beforeChange: [beforeChange({ productsSlug, variantOptionsSlug })],\n },\n labels: {\n plural: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:variants'),\n singular: ({ t }) =>\n // @ts-expect-error - translations are not typed in plugins yet\n t('plugin-ecommerce:variant'),\n },\n trash: true,\n versions: {\n drafts: {\n autosave: true,\n },\n },\n }\n\n return baseConfig\n}\n"],"names":["inventoryField","pricesField","variantsCollectionBeforeChange","beforeChange","validateOptions","createVariantsCollection","props","access","currenciesConfig","inventory","productsSlug","variantOptionsSlug","variantTypesSlug","supportedCurrencies","fields","name","type","admin","description","position","readOnly","relationTo","required","components","Field","path","custom","hasMany","label","validate","productsCollectionSlug","length","currencyOptions","forEach","currency","push","code","baseConfig","slug","create","isAdmin","delete","read","adminOrPublishedStatus","update","t","group","useAsTitle","authorship","hooks","labels","plural","singular","trash","versions","drafts","autosave"],"mappings":"AAIA,SAASA,cAAc,QAAQ,oCAAmC;AAClE,SAASC,WAAW,QAAQ,iCAAgC;AAC5D,SAASC,kCAAkCC,YAAY,QAAQ,0BAAyB;AACxF,SAASC,eAAe,QAAQ,6BAA4B;AAuB5D,OAAO,MAAMC,2BAA+D,CAACC;IAC3E,MAAM,EACJC,MAAM,EACNC,gBAAgB,EAChBC,YAAY,IAAI,EAChBC,eAAe,UAAU,EACzBC,qBAAqB,gBAAgB,EACrCC,mBAAmB,cAAc,EAClC,GAAGN,SAAS,CAAC;IACd,MAAM,EAAEO,mBAAmB,EAAE,GAAGL,oBAAoB,CAAC;IAErD,MAAMM,SAAkB;QACtB;YACEC,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLC,aACE;YACJ;QACF;QACA;YACEH,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLE,UAAU;gBACVC,UAAU;YACZ;YACAC,YAAYX;YACZY,UAAU;QACZ;QACA;YACE,wFAAwF;YACxF,gCAAgC;YAChC,8EAA8E;YAC9E,kEAAkE;YAClE,0GAA0G;YAC1GP,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLM,YAAY;oBACVC,OAAO;wBACLC,MAAM;oBACR;gBACF;YACF;YACAC,QAAQ;gBACNhB;gBACAE;YACF;YACAe,SAAS;YACTC,OAAO;YACPP,YAAYV;YACZW,UAAU;YACVO,UAAUzB,gBAAgB;gBAAE0B,wBAAwBpB;YAAa;QACnE;WACID,YAAY;YAACT;SAAiB,GAAG,EAAE;KACxC;IAED,IAAIa,qBAAqBkB,UAAUlB,oBAAoBkB,MAAM,GAAG,GAAG;QACjE,MAAMC,kBAA4B,EAAE;QAEpCnB,oBAAoBoB,OAAO,CAAC,CAACC;YAC3BF,gBAAgBG,IAAI,CAACD,SAASE,IAAI;QACpC;QAEA,IAAI5B,kBAAkB;YACpBM,OAAOqB,IAAI,IAAIlC,YAAY;gBAAEO;YAAiB;QAChD;IACF;IAEA,MAAM6B,aAA+B;QACnCC,MAAM;QACN/B,QAAQ;YACNgC,QAAQhC,OAAOiC,OAAO;YACtBC,QAAQlC,OAAOiC,OAAO;YACtBE,MAAMnC,OAAOoC,sBAAsB;YACnCC,QAAQrC,OAAOiC,OAAO;QACxB;QACAvB,OAAO;YACLC,aAAa,CAAC,EAAE2B,CAAC,EAAE,GACjB,+DAA+D;gBAC/DA,EAAE;YACJC,OAAO;YACPC,YAAY;QACd;QACAC,YAAY;QACZlC;QACAmC,OAAO;YACL9C,cAAc;gBAACA,aAAa;oBAAEO;oBAAcC;gBAAmB;aAAG;QACpE;QACAuC,QAAQ;YACNC,QAAQ,CAAC,EAAEN,CAAC,EAAE,GACZ,+DAA+D;gBAC/DA,EAAE;YACJO,UAAU,CAAC,EAAEP,CAAC,EAAE,GACd,+DAA+D;gBAC/DA,EAAE;QACN;QACAQ,OAAO;QACPC,UAAU;YACRC,QAAQ;gBACNC,UAAU;YACZ;QACF;IACF;IAEA,OAAOnB;AACT,EAAC"}
|
|
@@ -244,6 +244,7 @@ const finalizeTransactionOrder = async ({ cartID, cartsSlug, orderData, ordersSl
|
|
|
244
244
|
id: transactionID,
|
|
245
245
|
collection: transactionsSlug,
|
|
246
246
|
depth: 0,
|
|
247
|
+
overrideAccess: true,
|
|
247
248
|
req
|
|
248
249
|
});
|
|
249
250
|
if (!transaction || getRelationshipID(transaction.id) !== getRelationshipID(transactionID) || transaction.status !== 'processing') {
|
|
@@ -253,6 +254,7 @@ const finalizeTransactionOrder = async ({ cartID, cartsSlug, orderData, ordersSl
|
|
|
253
254
|
collection: ordersSlug,
|
|
254
255
|
depth: 0,
|
|
255
256
|
limit: 1,
|
|
257
|
+
overrideAccess: true,
|
|
256
258
|
pagination: false,
|
|
257
259
|
req,
|
|
258
260
|
where: {
|
|
@@ -272,6 +274,7 @@ const finalizeTransactionOrder = async ({ cartID, cartsSlug, orderData, ordersSl
|
|
|
272
274
|
transactionID
|
|
273
275
|
]
|
|
274
276
|
},
|
|
277
|
+
overrideAccess: true,
|
|
275
278
|
req
|
|
276
279
|
});
|
|
277
280
|
const orderID = requireDocumentID({
|
|
@@ -284,6 +287,7 @@ const finalizeTransactionOrder = async ({ cartID, cartsSlug, orderData, ordersSl
|
|
|
284
287
|
data: {
|
|
285
288
|
purchasedAt: new Date().toISOString()
|
|
286
289
|
},
|
|
290
|
+
overrideAccess: true,
|
|
287
291
|
req
|
|
288
292
|
});
|
|
289
293
|
await decrementInventory({
|
|
@@ -299,6 +303,7 @@ const finalizeTransactionOrder = async ({ cartID, cartsSlug, orderData, ordersSl
|
|
|
299
303
|
order: orderID,
|
|
300
304
|
status: 'succeeded'
|
|
301
305
|
},
|
|
306
|
+
overrideAccess: true,
|
|
302
307
|
req
|
|
303
308
|
});
|
|
304
309
|
return order;
|
|
@@ -338,6 +343,7 @@ const waitForCanonicalOrder = async ({ ordersSlug, req, transactionID, transacti
|
|
|
338
343
|
id: transactionID,
|
|
339
344
|
collection: transactionsSlug,
|
|
340
345
|
depth: 0,
|
|
346
|
+
overrideAccess: true,
|
|
341
347
|
req
|
|
342
348
|
});
|
|
343
349
|
if (!transaction) {
|
|
@@ -370,6 +376,7 @@ const findExactlyLinkedOrder = async ({ orderID, ordersSlug, req, transactionID
|
|
|
370
376
|
collection: ordersSlug,
|
|
371
377
|
depth: 0,
|
|
372
378
|
limit: 2,
|
|
379
|
+
overrideAccess: true,
|
|
373
380
|
pagination: false,
|
|
374
381
|
req,
|
|
375
382
|
where: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/endpoints/confirmOrder.ts"],"sourcesContent":["import {\n addDataAndFileToRequest,\n commitTransaction,\n type DefaultDocumentIDType,\n type Endpoint,\n initTransaction,\n killTransaction,\n} from 'payload'\n\nimport type {\n CurrenciesConfig,\n PaymentAdapter,\n ProductsValidation,\n UserWithCart,\n} from '../types/index.js'\n\ntype ConfirmOrderArgs = Parameters<PaymentAdapter['confirmOrder']>[0]\ntype FinalizeOrder = ConfirmOrderArgs['finalizeOrder']\ntype RecordValue = Record<string, unknown>\n\nconst SETTLEMENT_POLL_INTERVAL_MS = 25\nconst SETTLEMENT_WAIT_TIMEOUT_MS = 500\n\ntype Args = {\n /**\n * The slug of the carts collection, defaults to 'carts'.\n */\n cartsSlug?: string\n currenciesConfig: CurrenciesConfig\n /**\n * The slug of the customers collection, defaults to 'users'.\n */\n customersSlug?: string\n /**\n * The slug of the orders collection, defaults to 'orders'.\n */\n ordersSlug?: string\n paymentMethod: PaymentAdapter\n /**\n * The slug of the products collection, defaults to 'products'.\n */\n productsSlug?: string\n /**\n * Customise the validation used for checking products or variants before a transaction is created.\n */\n productsValidation?: ProductsValidation\n /**\n * The slug of the transactions collection, defaults to 'transactions'.\n */\n transactionsSlug?: string\n /**\n * The slug of the variants collection, defaults to 'variants'.\n */\n variantsSlug?: string\n}\n\ntype ConfirmOrderHandler = (args: Args) => Endpoint['handler']\n\n/**\n * Handles the endpoint for initiating payments. We will handle checking the amount and product and variant prices here before it is sent to the payment provider.\n * This is the first step in the payment process.\n */\nexport const confirmOrderHandler: ConfirmOrderHandler =\n ({\n cartsSlug = 'carts',\n currenciesConfig,\n customersSlug = 'users',\n ordersSlug = 'orders',\n paymentMethod,\n productsSlug = 'products',\n productsValidation,\n transactionsSlug = 'transactions',\n variantsSlug = 'variants',\n }) =>\n async (req) => {\n await addDataAndFileToRequest(req)\n\n const data = req.data\n const payload = req.payload\n const user = req.user as null | UserWithCart\n\n let currency: string = currenciesConfig.defaultCurrency\n let cartID: DefaultDocumentIDType = data?.cartID\n let cart = undefined\n let customerEmail: string = user?.email ?? ''\n const cartSecret = data?.secret\n\n if (user) {\n if (user.cart?.docs && Array.isArray(user.cart.docs) && user.cart.docs.length > 0) {\n if (!cartID && user.cart.docs[0]) {\n // Use the user's cart instead\n if (typeof user.cart.docs[0] === 'object') {\n cartID = user.cart.docs[0].id\n cart = user.cart.docs[0]\n } else {\n cartID = user.cart.docs[0]\n }\n }\n }\n } else {\n // Get the email from the data if user is not available\n if (\n typeof data?.customerEmail === 'string' &&\n normalizeEmail(data.customerEmail).length > 0\n ) {\n customerEmail = data.customerEmail\n } else {\n return Response.json(\n {\n message: 'A customer email is required to make a purchase.',\n },\n {\n status: 400,\n },\n )\n }\n }\n\n if (!cart) {\n if (cartID) {\n // Add cart secret to query for guest cart access control\n if (cartSecret && typeof cartSecret === 'string') {\n req.query = req.query || {}\n req.query.secret = cartSecret\n }\n\n cart = await payload.findByID({\n id: cartID,\n collection: cartsSlug,\n depth: 2,\n overrideAccess: false,\n req,\n select: {\n id: true,\n currency: true,\n customerEmail: true,\n items: true,\n subtotal: true,\n },\n })\n\n if (!cart) {\n return Response.json(\n {\n message: `Cart with ID ${cartID} not found.`,\n },\n {\n status: 404,\n },\n )\n }\n } else {\n return Response.json(\n {\n message: 'Cart ID is required.',\n },\n {\n status: 400,\n },\n )\n }\n }\n\n if (cart.currency && typeof cart.currency === 'string') {\n currency = cart.currency\n }\n\n // Ensure the currency is provided or inferred in some way\n if (!currency) {\n return Response.json(\n {\n message: 'Currency is required.',\n },\n {\n status: 400,\n },\n )\n }\n\n let shouldCommit = false\n\n try {\n const canonicalCartID = cart.id\n if (\n canonicalCartID === null ||\n canonicalCartID === undefined ||\n (typeof canonicalCartID === 'string' && canonicalCartID.trim() === '')\n ) {\n throw new Error('Canonical cart ID is required.')\n }\n\n const cartCustomerEmail = 'customerEmail' in cart ? cart.customerEmail : undefined\n const normalizedCartCustomerEmail = normalizeEmail(cartCustomerEmail)\n const normalizedSubmittedCustomerEmail = normalizeEmail(customerEmail)\n const canonicalEmail = user\n ? normalizeEmail(user.email)\n : normalizedCartCustomerEmail || normalizedSubmittedCustomerEmail\n\n if (\n !user &&\n normalizedCartCustomerEmail &&\n normalizedSubmittedCustomerEmail !== normalizedCartCustomerEmail\n ) {\n throw new Error('Customer email does not match the cart.')\n }\n\n shouldCommit = await initTransaction(req)\n const hadActiveTransaction = Boolean(await req.transactionID)\n let didCallFinalizeOrder = false\n let didFinalizeOrder = false\n let didRecoverTransientConflict = false\n let finalizedTransactionID: DefaultDocumentIDType | undefined\n\n const finalizeOrder: FinalizeOrder = async ({ orderData, transactionID }) => {\n if (didCallFinalizeOrder) {\n throw new Error('Order settlement was already finalized for this request.')\n }\n\n didCallFinalizeOrder = true\n finalizedTransactionID = transactionID\n\n let order: RecordValue\n\n try {\n order = await finalizeTransactionOrder({\n cartID: canonicalCartID,\n cartsSlug,\n orderData,\n ordersSlug,\n productsSlug,\n req,\n transactionID,\n transactionsSlug,\n variantsSlug,\n })\n } catch (error) {\n if (!shouldCommit || !isTransientTransactionConflict(error)) {\n throw error\n }\n\n // MongoDB reports a losing transactional claim as a transient write conflict rather\n // than a null compare-and-set result. Leave the aborted snapshot before polling.\n await killTransaction(req)\n shouldCommit = false\n order = await waitForCanonicalOrder({\n ordersSlug,\n req,\n transactionID,\n transactionsSlug,\n })\n didRecoverTransientConflict = true\n }\n\n didFinalizeOrder = true\n\n return order\n }\n\n const paymentResponse = await paymentMethod.confirmOrder({\n cartsSlug,\n customersSlug,\n data: {\n ...data,\n cartID: canonicalCartID,\n customerEmail: canonicalEmail,\n },\n finalizeOrder,\n ordersSlug,\n req,\n transactionsSlug,\n })\n const hasActiveTransaction = Boolean(await req.transactionID)\n const transactionID = paymentResponse.transactionID\n\n if (!isValidDocumentID(transactionID)) {\n throw new Error('Transaction ID is missing or invalid.')\n }\n\n if (!didCallFinalizeOrder) {\n throw new Error('Payment adapter did not finalize the order.')\n }\n\n if (!didFinalizeOrder) {\n throw new Error('Order settlement did not complete successfully.')\n }\n\n if (\n didFinalizeOrder &&\n getRelationshipID(transactionID) !== getRelationshipID(finalizedTransactionID)\n ) {\n throw new Error('Confirmation response transaction does not match the settlement.')\n }\n\n if (hadActiveTransaction && !hasActiveTransaction && !didRecoverTransientConflict) {\n throw new Error('Order confirmation lost its active transaction.')\n }\n\n if (shouldCommit && hasActiveTransaction) {\n await commitTransaction(req)\n }\n\n return Response.json(paymentResponse)\n } catch (err) {\n if (shouldCommit) {\n await killTransaction(req)\n }\n\n payload.logger.error({ err, msg: 'Error confirming order.' })\n\n return Response.json(\n {\n message: 'Error confirming order.',\n },\n {\n status: 500,\n },\n )\n }\n }\n\nconst normalizeEmail = (email: unknown): string =>\n typeof email === 'string' ? email.trim().toLowerCase() : ''\n\nconst isValidDocumentID = (id: unknown): id is DefaultDocumentIDType =>\n (typeof id === 'number' && Number.isFinite(id)) ||\n (typeof id === 'string' && id.trim().length > 0)\n\nconst finalizeTransactionOrder = async ({\n cartID,\n cartsSlug,\n orderData,\n ordersSlug,\n productsSlug,\n req,\n transactionID,\n transactionsSlug,\n variantsSlug,\n}: {\n cartID: DefaultDocumentIDType\n cartsSlug: string\n orderData: Record<string, unknown>\n ordersSlug: string\n productsSlug: string\n req: ConfirmOrderArgs['req']\n transactionID: DefaultDocumentIDType\n transactionsSlug: string\n variantsSlug: string\n}): Promise<RecordValue> => {\n if (!isValidDocumentID(transactionID)) {\n throw new Error('Transaction ID is missing or invalid.')\n }\n\n if (!isRecord(orderData)) {\n throw new Error('Order data is missing or invalid.')\n }\n\n const claimedTransaction = await req.payload.db.updateOne({\n collection: transactionsSlug,\n data: { status: 'processing' },\n options: { atomic: true },\n req,\n where: {\n and: [\n { id: { equals: transactionID } },\n { status: { equals: 'pending' } },\n { order: { exists: false } },\n ],\n },\n })\n\n if (!claimedTransaction) {\n return waitForCanonicalOrder({ ordersSlug, req, transactionID, transactionsSlug })\n }\n\n if (getRelationshipID(claimedTransaction.id) !== getRelationshipID(transactionID)) {\n throw new Error('Claimed transaction does not match the requested transaction.')\n }\n\n const transaction = await req.payload.findByID({\n id: transactionID,\n collection: transactionsSlug,\n depth: 0,\n req,\n })\n\n if (\n !transaction ||\n getRelationshipID(transaction.id) !== getRelationshipID(transactionID) ||\n transaction.status !== 'processing'\n ) {\n throw new Error('Claimed transaction could not be loaded for settlement.')\n }\n\n const referencedOrders = await req.payload.find({\n collection: ordersSlug,\n depth: 0,\n limit: 1,\n pagination: false,\n req,\n where: { transactions: { equals: transactionID } },\n })\n\n if (referencedOrders.totalDocs !== 0 || referencedOrders.docs.length !== 0) {\n throw new Error('An order already references the claimed transaction.')\n }\n\n const order = (await req.payload.create({\n collection: ordersSlug,\n data: {\n ...orderData,\n transactions: [transactionID],\n },\n req,\n })) as RecordValue\n const orderID = requireDocumentID({ fieldName: 'order ID', value: order.id })\n\n await req.payload.update({\n id: cartID,\n collection: cartsSlug,\n data: { purchasedAt: new Date().toISOString() },\n req,\n })\n\n await decrementInventory({\n items: transaction.items,\n productsSlug,\n req,\n variantsSlug,\n })\n\n await req.payload.update({\n id: transactionID,\n collection: transactionsSlug,\n data: { order: orderID, status: 'succeeded' },\n req,\n })\n\n return order\n}\n\nconst decrementInventory = async ({\n items,\n productsSlug,\n req,\n variantsSlug,\n}: {\n items: unknown\n productsSlug: string\n req: ConfirmOrderArgs['req']\n variantsSlug: string\n}): Promise<void> => {\n if (!Array.isArray(items) || items.length === 0) {\n throw new Error('Inventory transaction items are missing or invalid.')\n }\n\n for (const item of items) {\n if (\n !isRecord(item) ||\n typeof item.quantity !== 'number' ||\n !Number.isFinite(item.quantity) ||\n item.quantity <= 0\n ) {\n throw new Error('Inventory item quantity is missing or invalid.')\n }\n\n const hasVariant = item.variant !== null && item.variant !== undefined\n const id = hasVariant ? item.variant : item.product\n\n if (!isValidDocumentID(id)) {\n throw new Error('Inventory item target is missing or invalid.')\n }\n\n const updatedInventory = await req.payload.db.updateOne({\n id,\n collection: hasVariant ? variantsSlug : productsSlug,\n data: { inventory: { $inc: item.quantity * -1 } },\n req,\n })\n\n if (!updatedInventory) {\n throw new Error('Inventory item could not be updated.')\n }\n }\n}\n\nconst waitForCanonicalOrder = async ({\n ordersSlug,\n req,\n transactionID,\n transactionsSlug,\n}: {\n ordersSlug: string\n req: ConfirmOrderArgs['req']\n transactionID: DefaultDocumentIDType\n transactionsSlug: string\n}): Promise<RecordValue> => {\n const deadline = Date.now() + SETTLEMENT_WAIT_TIMEOUT_MS\n\n do {\n const transaction = await req.payload.findByID({\n id: transactionID,\n collection: transactionsSlug,\n depth: 0,\n req,\n })\n\n if (!transaction) {\n throw new Error('Canonical transaction was not found.')\n }\n\n if (transaction.status === 'succeeded') {\n return findExactlyLinkedOrder({\n orderID: transaction.order,\n ordersSlug,\n req,\n transactionID,\n })\n }\n\n if (transaction.status !== 'pending' && transaction.status !== 'processing') {\n throw new Error('Transaction is not available for settlement.')\n }\n\n if (Date.now() >= deadline) {\n break\n }\n\n await new Promise<void>((resolve) =>\n setTimeout(resolve, Math.min(SETTLEMENT_POLL_INTERVAL_MS, deadline - Date.now())),\n )\n } while (Date.now() <= deadline)\n\n throw new Error('Transaction settlement did not complete in time.')\n}\n\nconst findExactlyLinkedOrder = async ({\n orderID,\n ordersSlug,\n req,\n transactionID,\n}: {\n orderID: unknown\n ordersSlug: string\n req: ConfirmOrderArgs['req']\n transactionID: DefaultDocumentIDType\n}): Promise<RecordValue> => {\n const canonicalOrderID = requireDocumentID({ fieldName: 'order ID', value: orderID })\n const result = await req.payload.find({\n collection: ordersSlug,\n depth: 0,\n limit: 2,\n pagination: false,\n req,\n where: { transactions: { equals: transactionID } },\n })\n\n if (\n result.totalDocs !== 1 ||\n result.docs.length !== 1 ||\n getRelationshipID(result.docs[0]?.id) !== getRelationshipID(canonicalOrderID)\n ) {\n throw new Error('Transaction does not have exactly one canonical linked order.')\n }\n\n return result.docs[0] as RecordValue\n}\n\nconst getRelationshipID = (value: unknown): string | undefined => {\n const id = isRecord(value) ? value.id : value\n\n return isValidDocumentID(id) ? String(id) : undefined\n}\n\nconst requireDocumentID = ({\n fieldName,\n value,\n}: {\n fieldName: string\n value: unknown\n}): DefaultDocumentIDType => {\n const id = isRecord(value) ? value.id : value\n\n if (!isValidDocumentID(id)) {\n throw new Error(`${fieldName} is missing or invalid.`)\n }\n\n return id\n}\n\nconst isRecord = (value: unknown): value is RecordValue =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst isTransientTransactionConflict = (error: unknown): boolean => {\n if (!isRecord(error)) {\n return false\n }\n\n return (\n error.code === 112 ||\n error.codeName === 'WriteConflict' ||\n (Array.isArray(error.errorLabels) && error.errorLabels.includes('TransientTransactionError'))\n )\n}\n"],"names":["addDataAndFileToRequest","commitTransaction","initTransaction","killTransaction","SETTLEMENT_POLL_INTERVAL_MS","SETTLEMENT_WAIT_TIMEOUT_MS","confirmOrderHandler","cartsSlug","currenciesConfig","customersSlug","ordersSlug","paymentMethod","productsSlug","productsValidation","transactionsSlug","variantsSlug","req","data","payload","user","currency","defaultCurrency","cartID","cart","undefined","customerEmail","email","cartSecret","secret","docs","Array","isArray","length","id","normalizeEmail","Response","json","message","status","query","findByID","collection","depth","overrideAccess","select","items","subtotal","shouldCommit","canonicalCartID","trim","Error","cartCustomerEmail","normalizedCartCustomerEmail","normalizedSubmittedCustomerEmail","canonicalEmail","hadActiveTransaction","Boolean","transactionID","didCallFinalizeOrder","didFinalizeOrder","didRecoverTransientConflict","finalizedTransactionID","finalizeOrder","orderData","order","finalizeTransactionOrder","error","isTransientTransactionConflict","waitForCanonicalOrder","paymentResponse","confirmOrder","hasActiveTransaction","isValidDocumentID","getRelationshipID","err","logger","msg","toLowerCase","Number","isFinite","isRecord","claimedTransaction","db","updateOne","options","atomic","where","and","equals","exists","transaction","referencedOrders","find","limit","pagination","transactions","totalDocs","create","orderID","requireDocumentID","fieldName","value","update","purchasedAt","Date","toISOString","decrementInventory","item","quantity","hasVariant","variant","product","updatedInventory","inventory","$inc","deadline","now","findExactlyLinkedOrder","Promise","resolve","setTimeout","Math","min","canonicalOrderID","result","String","code","codeName","errorLabels","includes"],"mappings":"AAAA,SACEA,uBAAuB,EACvBC,iBAAiB,EAGjBC,eAAe,EACfC,eAAe,QACV,UAAS;AAahB,MAAMC,8BAA8B;AACpC,MAAMC,6BAA6B;AAqCnC;;;CAGC,GACD,OAAO,MAAMC,sBACX,CAAC,EACCC,YAAY,OAAO,EACnBC,gBAAgB,EAChBC,gBAAgB,OAAO,EACvBC,aAAa,QAAQ,EACrBC,aAAa,EACbC,eAAe,UAAU,EACzBC,kBAAkB,EAClBC,mBAAmB,cAAc,EACjCC,eAAe,UAAU,EAC1B,GACD,OAAOC;QACL,MAAMhB,wBAAwBgB;QAE9B,MAAMC,OAAOD,IAAIC,IAAI;QACrB,MAAMC,UAAUF,IAAIE,OAAO;QAC3B,MAAMC,OAAOH,IAAIG,IAAI;QAErB,IAAIC,WAAmBZ,iBAAiBa,eAAe;QACvD,IAAIC,SAAgCL,MAAMK;QAC1C,IAAIC,OAAOC;QACX,IAAIC,gBAAwBN,MAAMO,SAAS;QAC3C,MAAMC,aAAaV,MAAMW;QAEzB,IAAIT,MAAM;YACR,IAAIA,KAAKI,IAAI,EAAEM,QAAQC,MAAMC,OAAO,CAACZ,KAAKI,IAAI,CAACM,IAAI,KAAKV,KAAKI,IAAI,CAACM,IAAI,CAACG,MAAM,GAAG,GAAG;gBACjF,IAAI,CAACV,UAAUH,KAAKI,IAAI,CAACM,IAAI,CAAC,EAAE,EAAE;oBAChC,8BAA8B;oBAC9B,IAAI,OAAOV,KAAKI,IAAI,CAACM,IAAI,CAAC,EAAE,KA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D;IACtC,IAAI,CAACc,SAASd,QAAQ;QACpB,OAAO;IACT;IAEA,OACEA,MAAM4D,IAAI,KAAK,OACf5D,MAAM6D,QAAQ,KAAK,mBAClBjG,MAAMC,OAAO,CAACmC,MAAM8D,WAAW,KAAK9D,MAAM8D,WAAW,CAACC,QAAQ,CAAC;AAEpE"}
|
|
1
|
+
{"version":3,"sources":["../../src/endpoints/confirmOrder.ts"],"sourcesContent":["import {\n addDataAndFileToRequest,\n commitTransaction,\n type DefaultDocumentIDType,\n type Endpoint,\n initTransaction,\n killTransaction,\n} from 'payload'\n\nimport type {\n CurrenciesConfig,\n PaymentAdapter,\n ProductsValidation,\n UserWithCart,\n} from '../types/index.js'\n\ntype ConfirmOrderArgs = Parameters<PaymentAdapter['confirmOrder']>[0]\ntype FinalizeOrder = ConfirmOrderArgs['finalizeOrder']\ntype RecordValue = Record<string, unknown>\n\nconst SETTLEMENT_POLL_INTERVAL_MS = 25\nconst SETTLEMENT_WAIT_TIMEOUT_MS = 500\n\ntype Args = {\n /**\n * The slug of the carts collection, defaults to 'carts'.\n */\n cartsSlug?: string\n currenciesConfig: CurrenciesConfig\n /**\n * The slug of the customers collection, defaults to 'users'.\n */\n customersSlug?: string\n /**\n * The slug of the orders collection, defaults to 'orders'.\n */\n ordersSlug?: string\n paymentMethod: PaymentAdapter\n /**\n * The slug of the products collection, defaults to 'products'.\n */\n productsSlug?: string\n /**\n * Customise the validation used for checking products or variants before a transaction is created.\n */\n productsValidation?: ProductsValidation\n /**\n * The slug of the transactions collection, defaults to 'transactions'.\n */\n transactionsSlug?: string\n /**\n * The slug of the variants collection, defaults to 'variants'.\n */\n variantsSlug?: string\n}\n\ntype ConfirmOrderHandler = (args: Args) => Endpoint['handler']\n\n/**\n * Handles the endpoint for initiating payments. We will handle checking the amount and product and variant prices here before it is sent to the payment provider.\n * This is the first step in the payment process.\n */\nexport const confirmOrderHandler: ConfirmOrderHandler =\n ({\n cartsSlug = 'carts',\n currenciesConfig,\n customersSlug = 'users',\n ordersSlug = 'orders',\n paymentMethod,\n productsSlug = 'products',\n productsValidation,\n transactionsSlug = 'transactions',\n variantsSlug = 'variants',\n }) =>\n async (req) => {\n await addDataAndFileToRequest(req)\n\n const data = req.data\n const payload = req.payload\n const user = req.user as null | UserWithCart\n\n let currency: string = currenciesConfig.defaultCurrency\n let cartID: DefaultDocumentIDType = data?.cartID\n let cart = undefined\n let customerEmail: string = user?.email ?? ''\n const cartSecret = data?.secret\n\n if (user) {\n if (user.cart?.docs && Array.isArray(user.cart.docs) && user.cart.docs.length > 0) {\n if (!cartID && user.cart.docs[0]) {\n // Use the user's cart instead\n if (typeof user.cart.docs[0] === 'object') {\n cartID = user.cart.docs[0].id\n cart = user.cart.docs[0]\n } else {\n cartID = user.cart.docs[0]\n }\n }\n }\n } else {\n // Get the email from the data if user is not available\n if (\n typeof data?.customerEmail === 'string' &&\n normalizeEmail(data.customerEmail).length > 0\n ) {\n customerEmail = data.customerEmail\n } else {\n return Response.json(\n {\n message: 'A customer email is required to make a purchase.',\n },\n {\n status: 400,\n },\n )\n }\n }\n\n if (!cart) {\n if (cartID) {\n // Add cart secret to query for guest cart access control\n if (cartSecret && typeof cartSecret === 'string') {\n req.query = req.query || {}\n req.query.secret = cartSecret\n }\n\n cart = await payload.findByID({\n id: cartID,\n collection: cartsSlug,\n depth: 2,\n overrideAccess: false,\n req,\n select: {\n id: true,\n currency: true,\n customerEmail: true,\n items: true,\n subtotal: true,\n },\n })\n\n if (!cart) {\n return Response.json(\n {\n message: `Cart with ID ${cartID} not found.`,\n },\n {\n status: 404,\n },\n )\n }\n } else {\n return Response.json(\n {\n message: 'Cart ID is required.',\n },\n {\n status: 400,\n },\n )\n }\n }\n\n if (cart.currency && typeof cart.currency === 'string') {\n currency = cart.currency\n }\n\n // Ensure the currency is provided or inferred in some way\n if (!currency) {\n return Response.json(\n {\n message: 'Currency is required.',\n },\n {\n status: 400,\n },\n )\n }\n\n let shouldCommit = false\n\n try {\n const canonicalCartID = cart.id\n if (\n canonicalCartID === null ||\n canonicalCartID === undefined ||\n (typeof canonicalCartID === 'string' && canonicalCartID.trim() === '')\n ) {\n throw new Error('Canonical cart ID is required.')\n }\n\n const cartCustomerEmail = 'customerEmail' in cart ? cart.customerEmail : undefined\n const normalizedCartCustomerEmail = normalizeEmail(cartCustomerEmail)\n const normalizedSubmittedCustomerEmail = normalizeEmail(customerEmail)\n const canonicalEmail = user\n ? normalizeEmail(user.email)\n : normalizedCartCustomerEmail || normalizedSubmittedCustomerEmail\n\n if (\n !user &&\n normalizedCartCustomerEmail &&\n normalizedSubmittedCustomerEmail !== normalizedCartCustomerEmail\n ) {\n throw new Error('Customer email does not match the cart.')\n }\n\n shouldCommit = await initTransaction(req)\n const hadActiveTransaction = Boolean(await req.transactionID)\n let didCallFinalizeOrder = false\n let didFinalizeOrder = false\n let didRecoverTransientConflict = false\n let finalizedTransactionID: DefaultDocumentIDType | undefined\n\n const finalizeOrder: FinalizeOrder = async ({ orderData, transactionID }) => {\n if (didCallFinalizeOrder) {\n throw new Error('Order settlement was already finalized for this request.')\n }\n\n didCallFinalizeOrder = true\n finalizedTransactionID = transactionID\n\n let order: RecordValue\n\n try {\n order = await finalizeTransactionOrder({\n cartID: canonicalCartID,\n cartsSlug,\n orderData,\n ordersSlug,\n productsSlug,\n req,\n transactionID,\n transactionsSlug,\n variantsSlug,\n })\n } catch (error) {\n if (!shouldCommit || !isTransientTransactionConflict(error)) {\n throw error\n }\n\n // MongoDB reports a losing transactional claim as a transient write conflict rather\n // than a null compare-and-set result. Leave the aborted snapshot before polling.\n await killTransaction(req)\n shouldCommit = false\n order = await waitForCanonicalOrder({\n ordersSlug,\n req,\n transactionID,\n transactionsSlug,\n })\n didRecoverTransientConflict = true\n }\n\n didFinalizeOrder = true\n\n return order\n }\n\n const paymentResponse = await paymentMethod.confirmOrder({\n cartsSlug,\n customersSlug,\n data: {\n ...data,\n cartID: canonicalCartID,\n customerEmail: canonicalEmail,\n },\n finalizeOrder,\n ordersSlug,\n req,\n transactionsSlug,\n })\n const hasActiveTransaction = Boolean(await req.transactionID)\n const transactionID = paymentResponse.transactionID\n\n if (!isValidDocumentID(transactionID)) {\n throw new Error('Transaction ID is missing or invalid.')\n }\n\n if (!didCallFinalizeOrder) {\n throw new Error('Payment adapter did not finalize the order.')\n }\n\n if (!didFinalizeOrder) {\n throw new Error('Order settlement did not complete successfully.')\n }\n\n if (\n didFinalizeOrder &&\n getRelationshipID(transactionID) !== getRelationshipID(finalizedTransactionID)\n ) {\n throw new Error('Confirmation response transaction does not match the settlement.')\n }\n\n if (hadActiveTransaction && !hasActiveTransaction && !didRecoverTransientConflict) {\n throw new Error('Order confirmation lost its active transaction.')\n }\n\n if (shouldCommit && hasActiveTransaction) {\n await commitTransaction(req)\n }\n\n return Response.json(paymentResponse)\n } catch (err) {\n if (shouldCommit) {\n await killTransaction(req)\n }\n\n payload.logger.error({ err, msg: 'Error confirming order.' })\n\n return Response.json(\n {\n message: 'Error confirming order.',\n },\n {\n status: 500,\n },\n )\n }\n }\n\nconst normalizeEmail = (email: unknown): string =>\n typeof email === 'string' ? email.trim().toLowerCase() : ''\n\nconst isValidDocumentID = (id: unknown): id is DefaultDocumentIDType =>\n (typeof id === 'number' && Number.isFinite(id)) ||\n (typeof id === 'string' && id.trim().length > 0)\n\nconst finalizeTransactionOrder = async ({\n cartID,\n cartsSlug,\n orderData,\n ordersSlug,\n productsSlug,\n req,\n transactionID,\n transactionsSlug,\n variantsSlug,\n}: {\n cartID: DefaultDocumentIDType\n cartsSlug: string\n orderData: Record<string, unknown>\n ordersSlug: string\n productsSlug: string\n req: ConfirmOrderArgs['req']\n transactionID: DefaultDocumentIDType\n transactionsSlug: string\n variantsSlug: string\n}): Promise<RecordValue> => {\n if (!isValidDocumentID(transactionID)) {\n throw new Error('Transaction ID is missing or invalid.')\n }\n\n if (!isRecord(orderData)) {\n throw new Error('Order data is missing or invalid.')\n }\n\n const claimedTransaction = await req.payload.db.updateOne({\n collection: transactionsSlug,\n data: { status: 'processing' },\n options: { atomic: true },\n req,\n where: {\n and: [\n { id: { equals: transactionID } },\n { status: { equals: 'pending' } },\n { order: { exists: false } },\n ],\n },\n })\n\n if (!claimedTransaction) {\n return waitForCanonicalOrder({ ordersSlug, req, transactionID, transactionsSlug })\n }\n\n if (getRelationshipID(claimedTransaction.id) !== getRelationshipID(transactionID)) {\n throw new Error('Claimed transaction does not match the requested transaction.')\n }\n\n const transaction = await req.payload.findByID({\n id: transactionID,\n collection: transactionsSlug,\n depth: 0,\n overrideAccess: true,\n req,\n })\n\n if (\n !transaction ||\n getRelationshipID(transaction.id) !== getRelationshipID(transactionID) ||\n transaction.status !== 'processing'\n ) {\n throw new Error('Claimed transaction could not be loaded for settlement.')\n }\n\n const referencedOrders = await req.payload.find({\n collection: ordersSlug,\n depth: 0,\n limit: 1,\n overrideAccess: true,\n pagination: false,\n req,\n where: { transactions: { equals: transactionID } },\n })\n\n if (referencedOrders.totalDocs !== 0 || referencedOrders.docs.length !== 0) {\n throw new Error('An order already references the claimed transaction.')\n }\n\n const order = (await req.payload.create({\n collection: ordersSlug,\n data: {\n ...orderData,\n transactions: [transactionID],\n },\n overrideAccess: true,\n req,\n })) as RecordValue\n const orderID = requireDocumentID({ fieldName: 'order ID', value: order.id })\n\n await req.payload.update({\n id: cartID,\n collection: cartsSlug,\n data: { purchasedAt: new Date().toISOString() },\n overrideAccess: true,\n req,\n })\n\n await decrementInventory({\n items: transaction.items,\n productsSlug,\n req,\n variantsSlug,\n })\n\n await req.payload.update({\n id: transactionID,\n collection: transactionsSlug,\n data: { order: orderID, status: 'succeeded' },\n overrideAccess: true,\n req,\n })\n\n return order\n}\n\nconst decrementInventory = async ({\n items,\n productsSlug,\n req,\n variantsSlug,\n}: {\n items: unknown\n productsSlug: string\n req: ConfirmOrderArgs['req']\n variantsSlug: string\n}): Promise<void> => {\n if (!Array.isArray(items) || items.length === 0) {\n throw new Error('Inventory transaction items are missing or invalid.')\n }\n\n for (const item of items) {\n if (\n !isRecord(item) ||\n typeof item.quantity !== 'number' ||\n !Number.isFinite(item.quantity) ||\n item.quantity <= 0\n ) {\n throw new Error('Inventory item quantity is missing or invalid.')\n }\n\n const hasVariant = item.variant !== null && item.variant !== undefined\n const id = hasVariant ? item.variant : item.product\n\n if (!isValidDocumentID(id)) {\n throw new Error('Inventory item target is missing or invalid.')\n }\n\n const updatedInventory = await req.payload.db.updateOne({\n id,\n collection: hasVariant ? variantsSlug : productsSlug,\n data: { inventory: { $inc: item.quantity * -1 } },\n req,\n })\n\n if (!updatedInventory) {\n throw new Error('Inventory item could not be updated.')\n }\n }\n}\n\nconst waitForCanonicalOrder = async ({\n ordersSlug,\n req,\n transactionID,\n transactionsSlug,\n}: {\n ordersSlug: string\n req: ConfirmOrderArgs['req']\n transactionID: DefaultDocumentIDType\n transactionsSlug: string\n}): Promise<RecordValue> => {\n const deadline = Date.now() + SETTLEMENT_WAIT_TIMEOUT_MS\n\n do {\n const transaction = await req.payload.findByID({\n id: transactionID,\n collection: transactionsSlug,\n depth: 0,\n overrideAccess: true,\n req,\n })\n\n if (!transaction) {\n throw new Error('Canonical transaction was not found.')\n }\n\n if (transaction.status === 'succeeded') {\n return findExactlyLinkedOrder({\n orderID: transaction.order,\n ordersSlug,\n req,\n transactionID,\n })\n }\n\n if (transaction.status !== 'pending' && transaction.status !== 'processing') {\n throw new Error('Transaction is not available for settlement.')\n }\n\n if (Date.now() >= deadline) {\n break\n }\n\n await new Promise<void>((resolve) =>\n setTimeout(resolve, Math.min(SETTLEMENT_POLL_INTERVAL_MS, deadline - Date.now())),\n )\n } while (Date.now() <= deadline)\n\n throw new Error('Transaction settlement did not complete in time.')\n}\n\nconst findExactlyLinkedOrder = async ({\n orderID,\n ordersSlug,\n req,\n transactionID,\n}: {\n orderID: unknown\n ordersSlug: string\n req: ConfirmOrderArgs['req']\n transactionID: DefaultDocumentIDType\n}): Promise<RecordValue> => {\n const canonicalOrderID = requireDocumentID({ fieldName: 'order ID', value: orderID })\n const result = await req.payload.find({\n collection: ordersSlug,\n depth: 0,\n limit: 2,\n overrideAccess: true,\n pagination: false,\n req,\n where: { transactions: { equals: transactionID } },\n })\n\n if (\n result.totalDocs !== 1 ||\n result.docs.length !== 1 ||\n getRelationshipID(result.docs[0]?.id) !== getRelationshipID(canonicalOrderID)\n ) {\n throw new Error('Transaction does not have exactly one canonical linked order.')\n }\n\n return result.docs[0] as RecordValue\n}\n\nconst getRelationshipID = (value: unknown): string | undefined => {\n const id = isRecord(value) ? value.id : value\n\n return isValidDocumentID(id) ? String(id) : undefined\n}\n\nconst requireDocumentID = ({\n fieldName,\n value,\n}: {\n fieldName: string\n value: unknown\n}): DefaultDocumentIDType => {\n const id = isRecord(value) ? value.id : value\n\n if (!isValidDocumentID(id)) {\n throw new Error(`${fieldName} is missing or invalid.`)\n }\n\n return id\n}\n\nconst isRecord = (value: unknown): value is RecordValue =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst isTransientTransactionConflict = (error: unknown): boolean => {\n if (!isRecord(error)) {\n return false\n }\n\n return (\n error.code === 112 ||\n error.codeName === 'WriteConflict' ||\n (Array.isArray(error.errorLabels) && error.errorLabels.includes('TransientTransactionError'))\n )\n}\n"],"names":["addDataAndFileToRequest","commitTransaction","initTransaction","killTransaction","SETTLEMENT_POLL_INTERVAL_MS","SETTLEMENT_WAIT_TIMEOUT_MS","confirmOrderHandler","cartsSlug","currenciesConfig","customersSlug","ordersSlug","paymentMethod","productsSlug","productsValidation","transactionsSlug","variantsSlug","req","data","payload","user","currency","defaultCurrency","cartID","cart","undefined","customerEmail","email","cartSecret","secret","docs","Array","isArray","length","id","normalizeEmail","Response","json","message","status","query","findByID","collection","depth","overrideAccess","select","items","subtotal","shouldCommit","canonicalCartID","trim","Error","cartCustomerEmail","normalizedCartCustomerEmail","normalizedSubmittedCustomerEmail","canonicalEmail","hadActiveTransaction","Boolean","transactionID","didCallFinalizeOrder","didFinalizeOrder","didRecoverTransientConflict","finalizedTransactionID","finalizeOrder","orderData","order","finalizeTransactionOrder","error","isTransientTransactionConflict","waitForCanonicalOrder","paymentResponse","confirmOrder","hasActiveTransaction","isValidDocumentID","getRelationshipID","err","logger","msg","toLowerCase","Number","isFinite","isRecord","claimedTransaction","db","updateOne","options","atomic","where","and","equals","exists","transaction","referencedOrders","find","limit","pagination","transactions","totalDocs","create","orderID","requireDocumentID","fieldName","value","update","purchasedAt","Date","toISOString","decrementInventory","item","quantity","hasVariant","variant","product","updatedInventory","inventory","$inc","deadline","now","findExactlyLinkedOrder","Promise","resolve","setTimeout","Math","min","canonicalOrderID","result","String","code","codeName","errorLabels","includes"],"mappings":"AAAA,SACEA,uBAAuB,EACvBC,iBAAiB,EAGjBC,eAAe,EACfC,eAAe,QACV,UAAS;AAahB,MAAMC,8BAA8B;AACpC,MAAMC,6BAA6B;AAqCnC;;;CAGC,GACD,OAAO,MAAMC,sBACX,CAAC,EACCC,YAAY,OAAO,EACnBC,gBAAgB,EAChBC,gBAAgB,OAAO,EACvBC,aAAa,QAAQ,EACrBC,aAAa,EACbC,eAAe,UAAU,EACzBC,kBAAkB,EAClBC,mBAAmB,cAAc,EACjCC,eAAe,UAAU,EAC1B,GACD,OAAOC;QACL,MAAMhB,wBAAwBgB;QAE9B,MAAMC,OAAOD,IAAIC,IAAI;QACrB,MAAMC,UAAUF,IAAIE,OAAO;QAC3B,MAAMC,OAAOH,IAAIG,IAAI;QAErB,IAAIC,WAAmBZ,iBAAiBa,eAAe;QACvD,IAAIC,SAAgCL,MAAMK;QAC1C,IAAIC,OAAOC;QACX,IAAIC,gBAAwBN,MAAMO,SAAS;QAC3C,MAAMC,aAAaV,MAAMW;QAEzB,IAAIT,MAAM;YACR,IAAIA,KAAKI,IAAI,EAAEM,QAAQC,MAAMC,OAAO,CAACZ,KAAKI,IAAI,CAACM,IAAI,KAAKV,KAAKI,IAAI,CAACM,IAAI,CAACG,MAAM,GAAG,GAAG;gBACjF,IAAI,CAACV,UAAUH,KAAKI,IAAI,CAACM,IAAI,C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,CAAA;AAE1D;;;GAGG;AACH,eAAO,MAAM,sBAAsB,EAAE,
|
|
1
|
+
{"version":3,"file":"initiatePayment.d.ts","sourceRoot":"","sources":["../../src/endpoints/initiatePayment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuD,KAAK,QAAQ,EAAE,MAAM,SAAS,CAAA;AAE5F,OAAO,KAAK,EACV,gBAAgB,EAChB,cAAc,EACd,kBAAkB,EAClB,8BAA8B,EAE/B,MAAM,mBAAmB,CAAA;AAI1B,KAAK,IAAI,GAAG;IACV;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,gBAAgB,EAAE,gBAAgB,CAAA;IAClC;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB;;;OAGG;IACH,SAAS,CAAC,EAAE,8BAA8B,CAAC,WAAW,CAAC,CAAA;IACvD,aAAa,EAAE,cAAc,CAAA;IAC7B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;OAEG;IACH,kBAAkB,CAAC,EAAE,kBAAkB,CAAA;IACvC;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB,CAAA;AAED,KAAK,eAAe,GAAG,CAAC,IAAI,EAAE,IAAI,KAAK,QAAQ,CAAC,SAAS,CAAC,CAAA;AAE1D;;;GAGG;AACH,eAAO,MAAM,sBAAsB,EAAE,eAmSlC,CAAA"}
|
|
@@ -113,6 +113,7 @@ import { defaultProductsValidation } from '../utilities/defaultProductsValidatio
|
|
|
113
113
|
id,
|
|
114
114
|
collection: productsSlug,
|
|
115
115
|
depth: 0,
|
|
116
|
+
overrideAccess: true,
|
|
116
117
|
select: {
|
|
117
118
|
inventory: true,
|
|
118
119
|
[priceField]: true
|
|
@@ -158,6 +159,7 @@ import { defaultProductsValidation } from '../utilities/defaultProductsValidatio
|
|
|
158
159
|
id,
|
|
159
160
|
collection: variantsSlug,
|
|
160
161
|
depth: 0,
|
|
162
|
+
overrideAccess: true,
|
|
161
163
|
select: {
|
|
162
164
|
inventory: true,
|
|
163
165
|
[priceField]: true
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/endpoints/initiatePayment.ts"],"sourcesContent":["import { addDataAndFileToRequest, type DefaultDocumentIDType, type Endpoint } from 'payload'\n\nimport type {\n CurrenciesConfig,\n PaymentAdapter,\n ProductsValidation,\n SanitizedEcommercePluginConfig,\n UserWithCart,\n} from '../types/index.js'\n\nimport { defaultProductsValidation } from '../utilities/defaultProductsValidation.js'\n\ntype Args = {\n /**\n * The slug of the carts collection, defaults to 'carts'.\n */\n cartsSlug?: string\n currenciesConfig: CurrenciesConfig\n /**\n * The slug of the customers collection, defaults to 'users'.\n */\n customersSlug?: string\n /**\n * Track inventory stock for the products and variants.\n * Accepts an object to override the default field name.\n */\n inventory?: SanitizedEcommercePluginConfig['inventory']\n paymentMethod: PaymentAdapter\n /**\n * The slug of the products collection, defaults to 'products'.\n */\n productsSlug?: string\n /**\n * Customise the validation used for checking products or variants before a transaction is created.\n */\n productsValidation?: ProductsValidation\n /**\n * The slug of the transactions collection, defaults to 'transactions'.\n */\n transactionsSlug?: string\n /**\n * The slug of the variants collection, defaults to 'variants'.\n */\n variantsSlug?: string\n}\n\ntype InitiatePayment = (args: Args) => Endpoint['handler']\n\n/**\n * Handles the endpoint for initiating payments. We will handle checking the amount and product and variant prices here before it is sent to the payment provider.\n * This is the first step in the payment process.\n */\nexport const initiatePaymentHandler: InitiatePayment =\n ({\n cartsSlug = 'carts',\n currenciesConfig,\n customersSlug = 'users',\n paymentMethod,\n productsSlug = 'products',\n productsValidation,\n transactionsSlug = 'transactions',\n variantsSlug = 'variants',\n }) =>\n async (req) => {\n await addDataAndFileToRequest(req)\n const data = req.data\n const payload = req.payload\n const user = req.user as null | UserWithCart\n\n let currency: string = currenciesConfig.defaultCurrency\n let cartID: DefaultDocumentIDType = data?.cartID\n let cart: any = undefined\n const billingAddress = data?.billingAddress\n const shippingAddress = data?.shippingAddress\n const cartSecret = data?.secret\n\n let customerEmail: string = user?.email ?? ''\n\n if (user) {\n if (user.cart?.docs && Array.isArray(user.cart.docs) && user.cart.docs.length > 0) {\n if (!cartID && user.cart.docs[0]) {\n // Use the user's cart instead\n if (typeof user.cart.docs[0] === 'object') {\n cartID = user.cart.docs[0].id\n cart = user.cart.docs[0]\n } else {\n cartID = user.cart.docs[0]\n }\n }\n }\n } else {\n // Get the email from the data if user is not available\n if (data?.customerEmail && typeof data.customerEmail === 'string') {\n customerEmail = data.customerEmail\n } else {\n return Response.json(\n {\n message: 'A customer email is required to make a purchase.',\n },\n {\n status: 400,\n },\n )\n }\n }\n\n if (!cart) {\n if (cartID) {\n // Add cart secret to query for guest cart access control\n if (cartSecret && typeof cartSecret === 'string') {\n req.query = req.query || {}\n req.query.secret = cartSecret\n }\n\n cart = await payload.findByID({\n id: cartID,\n collection: cartsSlug,\n depth: 2,\n overrideAccess: false,\n req,\n select: {\n id: true,\n currency: true,\n customerEmail: true,\n items: true,\n subtotal: true,\n },\n })\n\n if (!cart) {\n return Response.json(\n {\n message: `Cart with ID ${cartID} not found.`,\n },\n {\n status: 404,\n },\n )\n }\n } else {\n return Response.json(\n {\n message: 'Cart ID is required.',\n },\n {\n status: 400,\n },\n )\n }\n }\n\n if (cart.currency && typeof cart.currency === 'string') {\n currency = cart.currency\n }\n\n // Ensure the currency is provided or inferred in some way\n if (!currency) {\n return Response.json(\n {\n message: 'Currency is required.',\n },\n {\n status: 400,\n },\n )\n }\n\n // Ensure the selected currency is supported\n if (\n !currenciesConfig.supportedCurrencies.find(\n (c) => c.code.toLocaleLowerCase() === currency.toLocaleLowerCase(),\n )\n ) {\n return Response.json(\n {\n message: `Currency ${currency} is not supported.`,\n },\n {\n status: 400,\n },\n )\n }\n\n // Verify the cart is available and items are present in an array\n if (!cart || !cart.items || !Array.isArray(cart.items) || cart.items.length === 0) {\n return Response.json(\n {\n message: 'Cart is required and must contain at least one item.',\n },\n {\n status: 400,\n },\n )\n }\n\n for (const item of cart.items) {\n // Target field to check the price based on the currency so we can validate the total\n const priceField = `priceIn${currency.toUpperCase()}`\n const quantity = item.quantity || 1\n\n // If the item has a product but no variant, we assume the product has a price in the specified currency\n if (item.product && !item.variant) {\n const id = typeof item.product === 'object' ? item.product.id : item.product\n\n const product = await payload.findByID({\n id,\n collection: productsSlug,\n depth: 0,\n select: {\n inventory: true,\n [priceField]: true,\n },\n })\n\n if (!product) {\n return Response.json(\n {\n message: `Product with ID ${item.product} not found.`,\n },\n {\n status: 404,\n },\n )\n }\n\n try {\n if (productsValidation) {\n await productsValidation({ currenciesConfig, currency, product, quantity })\n } else {\n await defaultProductsValidation({\n currenciesConfig,\n currency,\n product,\n quantity,\n })\n }\n } catch (error) {\n payload.logger.error(\n error,\n 'Error validating product or variant during payment initiation.',\n )\n\n return Response.json(\n {\n message: error,\n ...(error instanceof Error ? { cause: error.cause } : {}),\n },\n {\n status: 400,\n },\n )\n }\n\n if (item.variant) {\n const id = typeof item.variant === 'object' ? item.variant.id : item.variant\n\n const variant = await payload.findByID({\n id,\n collection: variantsSlug,\n depth: 0,\n select: {\n inventory: true,\n [priceField]: true,\n },\n })\n\n if (!variant) {\n return Response.json(\n {\n message: `Variant with ID ${item.variant} not found.`,\n },\n {\n status: 404,\n },\n )\n }\n\n try {\n if (productsValidation) {\n await productsValidation({\n currenciesConfig,\n currency,\n product: item.product,\n quantity,\n variant,\n })\n } else {\n await defaultProductsValidation({\n currenciesConfig,\n currency,\n product: item.product,\n quantity,\n variant,\n })\n }\n } catch (error) {\n payload.logger.error(\n error,\n 'Error validating product or variant during payment initiation.',\n )\n\n return Response.json(\n {\n message: error,\n },\n {\n status: 400,\n },\n )\n }\n }\n }\n }\n\n try {\n const paymentResponse = await paymentMethod.initiatePayment({\n customersSlug,\n data: {\n billingAddress,\n cart,\n currency,\n customerEmail,\n shippingAddress,\n },\n req,\n transactionsSlug,\n })\n\n return Response.json(paymentResponse)\n } catch (error) {\n payload.logger.error(error, 'Error initiating payment.')\n\n return Response.json(\n {\n message: 'Error initiating payment.',\n },\n {\n status: 500,\n },\n )\n }\n }\n"],"names":["addDataAndFileToRequest","defaultProductsValidation","initiatePaymentHandler","cartsSlug","currenciesConfig","customersSlug","paymentMethod","productsSlug","productsValidation","transactionsSlug","variantsSlug","req","data","payload","user","currency","defaultCurrency","cartID","cart","undefined","billingAddress","shippingAddress","cartSecret","secret","customerEmail","email","docs","Array","isArray","length","id","Response","json","message","status","query","findByID","collection","depth","overrideAccess","select","items","subtotal","supportedCurrencies","find","c","code","toLocaleLowerCase","item","priceField","toUpperCase","quantity","product","variant","inventory","error","logger","Error","cause","paymentResponse","initiatePayment"],"mappings":"AAAA,SAASA,uBAAuB,QAAmD,UAAS;AAU5F,SAASC,yBAAyB,QAAQ,4CAA2C;AAsCrF;;;CAGC,GACD,OAAO,MAAMC,yBACX,CAAC,EACCC,YAAY,OAAO,EACnBC,gBAAgB,EAChBC,gBAAgB,OAAO,EACvBC,aAAa,EACbC,eAAe,UAAU,EACzBC,kBAAkB,EAClBC,mBAAmB,cAAc,EACjCC,eAAe,UAAU,EAC1B,GACD,OAAOC;QACL,MAAMX,wBAAwBW;QAC9B,MAAMC,OAAOD,IAAIC,IAAI;QACrB,MAAMC,UAAUF,IAAIE,OAAO;QAC3B,MAAMC,OAAOH,IAAIG,IAAI;QAErB,IAAIC,WAAmBX,iBAAiBY,eAAe;QACvD,IAAIC,SAAgCL,MAAMK;QAC1C,IAAIC,OAAYC;QAChB,MAAMC,iBAAiBR,MAAMQ;QAC7B,MAAMC,kBAAkBT,MAAMS;QAC9B,MAAMC,aAAaV,MAAMW;QAEzB,IAAIC,gBAAwBV,MAAMW,SAAS;QAE3C,IAAIX,MAAM;YACR,IAAIA,KAAKI,IAAI,EAAEQ,QAAQC,MAAMC,OAAO,CAACd,KAAKI,IAAI,CAACQ,IAAI,KAAKZ,KAAKI,IAAI,CAACQ,IAAI,CAACG,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,OAAO;4BACL,MAAMpD,0BAA0B;gCAC9BG;gCACAW;gCACAqC,SAASJ,KAAKI,OAAO;gCACrBD;gCACAE;4BACF;wBACF;oBACF,EAAE,OAAOE,OAAO;wBACd1C,QAAQ2C,MAAM,CAACD,KAAK,CAClBA,OACA;wBAGF,OAAOxB,SAASC,IAAI,CAClB;4BACEC,SAASsB;wBACX,GACA;4BACErB,QAAQ;wBACV;oBAEJ;gBACF;YACF;QACF;QAEA,IAAI;YACF,MAAMyB,kBAAkB,MAAMrD,cAAcsD,eAAe,CAAC;gBAC1DvD;gBACAO,MAAM;oBACJQ;oBACAF;oBACAH;oBACAS;oBACAH;gBACF;gBACAV;gBACAF;YACF;YAEA,OAAOsB,SAASC,IAAI,CAAC2B;QACvB,EAAE,OAAOJ,OAAO;YACd1C,QAAQ2C,MAAM,CAACD,KAAK,CAACA,OAAO;YAE5B,OAAOxB,SAASC,IAAI,CAClB;gBACEC,SAAS;YACX,GACA;gBACEC,QAAQ;YACV;QAEJ;IACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/endpoints/initiatePayment.ts"],"sourcesContent":["import { addDataAndFileToRequest, type DefaultDocumentIDType, type Endpoint } from 'payload'\n\nimport type {\n CurrenciesConfig,\n PaymentAdapter,\n ProductsValidation,\n SanitizedEcommercePluginConfig,\n UserWithCart,\n} from '../types/index.js'\n\nimport { defaultProductsValidation } from '../utilities/defaultProductsValidation.js'\n\ntype Args = {\n /**\n * The slug of the carts collection, defaults to 'carts'.\n */\n cartsSlug?: string\n currenciesConfig: CurrenciesConfig\n /**\n * The slug of the customers collection, defaults to 'users'.\n */\n customersSlug?: string\n /**\n * Track inventory stock for the products and variants.\n * Accepts an object to override the default field name.\n */\n inventory?: SanitizedEcommercePluginConfig['inventory']\n paymentMethod: PaymentAdapter\n /**\n * The slug of the products collection, defaults to 'products'.\n */\n productsSlug?: string\n /**\n * Customise the validation used for checking products or variants before a transaction is created.\n */\n productsValidation?: ProductsValidation\n /**\n * The slug of the transactions collection, defaults to 'transactions'.\n */\n transactionsSlug?: string\n /**\n * The slug of the variants collection, defaults to 'variants'.\n */\n variantsSlug?: string\n}\n\ntype InitiatePayment = (args: Args) => Endpoint['handler']\n\n/**\n * Handles the endpoint for initiating payments. We will handle checking the amount and product and variant prices here before it is sent to the payment provider.\n * This is the first step in the payment process.\n */\nexport const initiatePaymentHandler: InitiatePayment =\n ({\n cartsSlug = 'carts',\n currenciesConfig,\n customersSlug = 'users',\n paymentMethod,\n productsSlug = 'products',\n productsValidation,\n transactionsSlug = 'transactions',\n variantsSlug = 'variants',\n }) =>\n async (req) => {\n await addDataAndFileToRequest(req)\n const data = req.data\n const payload = req.payload\n const user = req.user as null | UserWithCart\n\n let currency: string = currenciesConfig.defaultCurrency\n let cartID: DefaultDocumentIDType = data?.cartID\n let cart: any = undefined\n const billingAddress = data?.billingAddress\n const shippingAddress = data?.shippingAddress\n const cartSecret = data?.secret\n\n let customerEmail: string = user?.email ?? ''\n\n if (user) {\n if (user.cart?.docs && Array.isArray(user.cart.docs) && user.cart.docs.length > 0) {\n if (!cartID && user.cart.docs[0]) {\n // Use the user's cart instead\n if (typeof user.cart.docs[0] === 'object') {\n cartID = user.cart.docs[0].id\n cart = user.cart.docs[0]\n } else {\n cartID = user.cart.docs[0]\n }\n }\n }\n } else {\n // Get the email from the data if user is not available\n if (data?.customerEmail && typeof data.customerEmail === 'string') {\n customerEmail = data.customerEmail\n } else {\n return Response.json(\n {\n message: 'A customer email is required to make a purchase.',\n },\n {\n status: 400,\n },\n )\n }\n }\n\n if (!cart) {\n if (cartID) {\n // Add cart secret to query for guest cart access control\n if (cartSecret && typeof cartSecret === 'string') {\n req.query = req.query || {}\n req.query.secret = cartSecret\n }\n\n cart = await payload.findByID({\n id: cartID,\n collection: cartsSlug,\n depth: 2,\n overrideAccess: false,\n req,\n select: {\n id: true,\n currency: true,\n customerEmail: true,\n items: true,\n subtotal: true,\n },\n })\n\n if (!cart) {\n return Response.json(\n {\n message: `Cart with ID ${cartID} not found.`,\n },\n {\n status: 404,\n },\n )\n }\n } else {\n return Response.json(\n {\n message: 'Cart ID is required.',\n },\n {\n status: 400,\n },\n )\n }\n }\n\n if (cart.currency && typeof cart.currency === 'string') {\n currency = cart.currency\n }\n\n // Ensure the currency is provided or inferred in some way\n if (!currency) {\n return Response.json(\n {\n message: 'Currency is required.',\n },\n {\n status: 400,\n },\n )\n }\n\n // Ensure the selected currency is supported\n if (\n !currenciesConfig.supportedCurrencies.find(\n (c) => c.code.toLocaleLowerCase() === currency.toLocaleLowerCase(),\n )\n ) {\n return Response.json(\n {\n message: `Currency ${currency} is not supported.`,\n },\n {\n status: 400,\n },\n )\n }\n\n // Verify the cart is available and items are present in an array\n if (!cart || !cart.items || !Array.isArray(cart.items) || cart.items.length === 0) {\n return Response.json(\n {\n message: 'Cart is required and must contain at least one item.',\n },\n {\n status: 400,\n },\n )\n }\n\n for (const item of cart.items) {\n // Target field to check the price based on the currency so we can validate the total\n const priceField = `priceIn${currency.toUpperCase()}`\n const quantity = item.quantity || 1\n\n // If the item has a product but no variant, we assume the product has a price in the specified currency\n if (item.product && !item.variant) {\n const id = typeof item.product === 'object' ? item.product.id : item.product\n\n const product = await payload.findByID({\n id,\n collection: productsSlug,\n depth: 0,\n overrideAccess: true,\n select: {\n inventory: true,\n [priceField]: true,\n },\n })\n\n if (!product) {\n return Response.json(\n {\n message: `Product with ID ${item.product} not found.`,\n },\n {\n status: 404,\n },\n )\n }\n\n try {\n if (productsValidation) {\n await productsValidation({ currenciesConfig, currency, product, quantity })\n } else {\n await defaultProductsValidation({\n currenciesConfig,\n currency,\n product,\n quantity,\n })\n }\n } catch (error) {\n payload.logger.error(\n error,\n 'Error validating product or variant during payment initiation.',\n )\n\n return Response.json(\n {\n message: error,\n ...(error instanceof Error ? { cause: error.cause } : {}),\n },\n {\n status: 400,\n },\n )\n }\n\n if (item.variant) {\n const id = typeof item.variant === 'object' ? item.variant.id : item.variant\n\n const variant = await payload.findByID({\n id,\n collection: variantsSlug,\n depth: 0,\n overrideAccess: true,\n select: {\n inventory: true,\n [priceField]: true,\n },\n })\n\n if (!variant) {\n return Response.json(\n {\n message: `Variant with ID ${item.variant} not found.`,\n },\n {\n status: 404,\n },\n )\n }\n\n try {\n if (productsValidation) {\n await productsValidation({\n currenciesConfig,\n currency,\n product: item.product,\n quantity,\n variant,\n })\n } else {\n await defaultProductsValidation({\n currenciesConfig,\n currency,\n product: item.product,\n quantity,\n variant,\n })\n }\n } catch (error) {\n payload.logger.error(\n error,\n 'Error validating product or variant during payment initiation.',\n )\n\n return Response.json(\n {\n message: error,\n },\n {\n status: 400,\n },\n )\n }\n }\n }\n }\n\n try {\n const paymentResponse = await paymentMethod.initiatePayment({\n customersSlug,\n data: {\n billingAddress,\n cart,\n currency,\n customerEmail,\n shippingAddress,\n },\n req,\n transactionsSlug,\n })\n\n return Response.json(paymentResponse)\n } catch (error) {\n payload.logger.error(error, 'Error initiating payment.')\n\n return Response.json(\n {\n message: 'Error initiating payment.',\n },\n {\n status: 500,\n },\n )\n }\n }\n"],"names":["addDataAndFileToRequest","defaultProductsValidation","initiatePaymentHandler","cartsSlug","currenciesConfig","customersSlug","paymentMethod","productsSlug","productsValidation","transactionsSlug","variantsSlug","req","data","payload","user","currency","defaultCurrency","cartID","cart","undefined","billingAddress","shippingAddress","cartSecret","secret","customerEmail","email","docs","Array","isArray","length","id","Response","json","message","status","query","findByID","collection","depth","overrideAccess","select","items","subtotal","supportedCurrencies","find","c","code","toLocaleLowerCase","item","priceField","toUpperCase","quantity","product","variant","inventory","error","logger","Error","cause","paymentResponse","initiatePayment"],"mappings":"AAAA,SAASA,uBAAuB,QAAmD,UAAS;AAU5F,SAASC,yBAAyB,QAAQ,4CAA2C;AAsCrF;;;CAGC,GACD,OAAO,MAAMC,yBACX,CAAC,EACCC,YAAY,OAAO,EACnBC,gBAAgB,EAChBC,gBAAgB,OAAO,EACvBC,aAAa,EACbC,eAAe,UAAU,EACzBC,kBAAkB,EAClBC,mBA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
1
|
-
{"version":3,"sources":["../../../../src/payments/adapters/stripe/confirmOrder.ts"],"sourcesContent":["import type { DefaultDocumentIDType } from 'payload'\n\nimport Stripe from 'stripe'\n\nimport type { PaymentAdapter } from '../../../types/index.js'\nimport type { StripeAdapterArgs } from './index.js'\n\nimport { normalizeEmail, validateSettlement } from './validateSettlement.js'\n\ntype Props = {\n apiVersion?: Stripe.StripeConfig['apiVersion']\n appInfo?: Stripe.StripeConfig['appInfo']\n secretKey: StripeAdapterArgs['secretKey']\n}\n\ntype RecordValue = Record<string, unknown>\n\nexport const confirmOrder: (props: Props) => NonNullable<PaymentAdapter>['confirmOrder'] =\n (props) =>\n async ({ data, finalizeOrder, req, transactionsSlug = 'transactions' }) => {\n const payload = req.payload\n const { apiVersion, appInfo, secretKey } = props || {}\n const paymentIntentID = data.paymentIntentID\n\n if (!secretKey) {\n throw new Error('Stripe secret key is required')\n }\n\n if (typeof paymentIntentID !== 'string' || !paymentIntentID) {\n throw new Error('PaymentIntent ID is required')\n }\n\n if (typeof finalizeOrder !== 'function') {\n throw new Error('Core order finalizer is required')\n }\n\n const stripe = new Stripe(secretKey, {\n // API version can only be the latest, stripe recommends ts ignoring it\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - ignoring since possible versions are not type safe, only the latest version is recognised\n apiVersion: apiVersion || '2025-03-31.basil',\n appInfo: appInfo || {\n name: 'Stripe Payload Plugin',\n url: 'https://payloadcms.com',\n },\n })\n\n try {\n const transaction = await findTransaction({ paymentIntentID, req, transactionsSlug })\n const transactionID = requireDocumentID({\n fieldName: 'transaction ID',\n value: transaction.id,\n })\n const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentID)\n const cartItemsSnapshot = parseRequiredMetadata({\n fieldName: 'cartItemsSnapshot',\n value: paymentIntent.metadata.cartItemsSnapshot,\n })\n const shippingAddress = parseOptionalMetadata({\n fieldName: 'shippingAddress',\n value: paymentIntent.metadata.shippingAddress,\n })\n const purchaser =\n req.user === null || req.user === undefined\n ? { customerEmail: normalizeEmail(data.customerEmail) }\n : {\n customer: requireDocumentID({\n fieldName: 'authenticated customer ID',\n value: req.user.id,\n }),\n }\n\n validateSettlement({\n canonicalCartID: data.cartID,\n cartItemsSnapshot,\n customerEmail: data.customerEmail,\n paymentIntent,\n paymentIntentID,\n transaction,\n user: req.user,\n })\n\n const order = await finalizeOrder({\n orderData: {\n amount: transaction.amount,\n currency: transaction.currency,\n ...purchaser,\n items: cartItemsSnapshot,\n shippingAddress,\n status: 'processing',\n },\n transactionID,\n })\n\n return createConfirmationResult({ order, transactionID })\n } catch (error) {\n payload.logger.error({ err: error, msg: 'Error confirming order with Stripe' })\n\n throw new Error(error instanceof Error ? error.message : 'Unknown error initiating payment')\n }\n }\n\nconst createConfirmationResult = ({\n order,\n transactionID,\n}: {\n order: RecordValue\n transactionID: DefaultDocumentIDType\n}) => ({\n message: 'Payment initiated successfully',\n orderID: requireDocumentID({ fieldName: 'order ID', value: order.id }),\n transactionID,\n ...(typeof order.accessToken === 'string' ? { accessToken: order.accessToken } : {}),\n})\n\nconst findTransaction = async ({\n paymentIntentID,\n req,\n transactionsSlug,\n}: {\n paymentIntentID: string\n req: Parameters<NonNullable<PaymentAdapter>['confirmOrder']>[0]['req']\n transactionsSlug: string\n}): Promise<RecordValue> => {\n const result = await req.payload.find({\n collection: transactionsSlug,\n depth: 0,\n limit: 2,\n pagination: false,\n req,\n where: {\n 'stripe.paymentIntentID': {\n equals: paymentIntentID,\n },\n },\n })\n\n if (result.totalDocs !== 1 || result.docs.length !== 1 || !result.docs[0]) {\n throw new Error('Expected exactly one transaction for the provided PaymentIntent ID')\n }\n\n return result.docs[0] as RecordValue\n}\n\nconst parseOptionalMetadata = ({\n fieldName,\n value,\n}: {\n fieldName: string\n value?: string\n}): RecordValue | undefined => {\n if (value === undefined) {\n return undefined\n }\n\n const parsedValue = parseRequiredMetadata({ fieldName, value })\n\n if (!isRecord(parsedValue)) {\n throw new Error(`${fieldName} metadata is invalid`)\n }\n\n return parsedValue\n}\n\nconst parseRequiredMetadata = ({\n fieldName,\n value,\n}: {\n fieldName: string\n value?: string\n}): unknown => {\n if (typeof value !== 'string' || !value) {\n throw new Error(`${fieldName} metadata is missing or invalid`)\n }\n\n try {\n return JSON.parse(value)\n } catch {\n throw new Error(`${fieldName} metadata is missing or invalid`)\n }\n}\n\nconst requireDocumentID = ({\n fieldName,\n value,\n}: {\n fieldName: string\n value: unknown\n}): DefaultDocumentIDType => {\n if (\n (typeof value !== 'number' || !Number.isFinite(value)) &&\n (typeof value !== 'string' || !value.trim())\n ) {\n throw new Error(`${fieldName} is missing or invalid`)\n }\n\n return value\n}\n\nconst isRecord = (value: unknown): value is RecordValue =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n"],"names":["Stripe","normalizeEmail","validateSettlement","confirmOrder","props","data","finalizeOrder","req","transactionsSlug","payload","apiVersion","appInfo","secretKey","paymentIntentID","Error","stripe","name","url","transaction","findTransaction","transactionID","requireDocumentID","fieldName","value","id","paymentIntent","paymentIntents","retrieve","cartItemsSnapshot","parseRequiredMetadata","metadata","shippingAddress","parseOptionalMetadata","purchaser","user","undefined","customerEmail","customer","canonicalCartID","cartID","order","orderData","amount","currency","items","status","createConfirmationResult","error","logger","err","msg","message","orderID","accessToken","result","find","collection","depth","limit","pagination","where","equals","totalDocs","docs","length","parsedValue","isRecord","JSON","parse","Number","isFinite","trim","Array","isArray"],"mappings":"AAEA,OAAOA,YAAY,SAAQ;AAK3B,SAASC,cAAc,EAAEC,kBAAkB,QAAQ,0BAAyB;AAU5E,OAAO,MAAMC,eACX,CAACC,QACD,OAAO,EAAEC,IAAI,EAAEC,aAAa,EAAEC,GAAG,EAAEC,mBAAmB,cAAc,EAAE;QACpE,MAAMC,UAAUF,IAAIE,OAAO;QAC3B,MAAM,EAAEC,UAAU,EAAEC,OAAO,EAAEC,SAAS,EAAE,GAAGR,SAAS,CAAC;QACrD,MAAMS,kBAAkBR,KAAKQ,eAAe;QAE5C,IAAI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zB,YAAYyB,QAAQ;oBAC9B,GAAGV,SAAS;oBACZW,OAAOhB;oBACPG;oBACAc,QAAQ;gBACV;gBACAzB;YACF;YAEA,OAAO0B,yBAAyB;gBAAEN;gBAAOpB;YAAc;QACzD,EAAE,OAAO2B,OAAO;YACdtC,QAAQuC,MAAM,CAACD,KAAK,CAAC;gBAAEE,KAAKF;gBAAOG,KAAK;YAAqC;YAE7E,MAAM,IAAIpC,MAAMiC,iBAAiBjC,QAAQiC,MAAMI,OAAO,GAAG;QAC3D;IACF,EAAC;AAEH,MAAML,2BAA2B,CAAC,EAChCN,KAAK,EACLpB,aAAa,EAId,GAAM,CAAA;QACL+B,SAAS;QACTC,SAAS/B,kBAAkB;YAAEC,WAAW;YAAYC,OAAOiB,MAAMhB,EAAE;QAAC;QACpEJ;QACA,GAAI,OAAOoB,MAAMa,WAAW,KAAK,WAAW;YAAEA,aAAab,MAAMa,WAAW;QAAC,IAAI,CAAC,CAAC;IACrF,CAAA;AAEA,MAAMlC,kBAAkB,OAAO,EAC7BN,eAAe,EACfN,GAAG,EACHC,gBAAgB,EAKjB;IACC,MAAM8C,SAAS,MAAM/C,IAAIE,OAAO,CAAC8C,IAAI,CAAC;QACpCC,YAAYhD;QACZiD,OAAO;QACPC,OAAO;QACPC,YAAY;
|
|
1
|
+
{"version":3,"sources":["../../../../src/payments/adapters/stripe/confirmOrder.ts"],"sourcesContent":["import type { DefaultDocumentIDType } from 'payload'\n\nimport Stripe from 'stripe'\n\nimport type { PaymentAdapter } from '../../../types/index.js'\nimport type { StripeAdapterArgs } from './index.js'\n\nimport { normalizeEmail, validateSettlement } from './validateSettlement.js'\n\ntype Props = {\n apiVersion?: Stripe.StripeConfig['apiVersion']\n appInfo?: Stripe.StripeConfig['appInfo']\n secretKey: StripeAdapterArgs['secretKey']\n}\n\ntype RecordValue = Record<string, unknown>\n\nexport const confirmOrder: (props: Props) => NonNullable<PaymentAdapter>['confirmOrder'] =\n (props) =>\n async ({ data, finalizeOrder, req, transactionsSlug = 'transactions' }) => {\n const payload = req.payload\n const { apiVersion, appInfo, secretKey } = props || {}\n const paymentIntentID = data.paymentIntentID\n\n if (!secretKey) {\n throw new Error('Stripe secret key is required')\n }\n\n if (typeof paymentIntentID !== 'string' || !paymentIntentID) {\n throw new Error('PaymentIntent ID is required')\n }\n\n if (typeof finalizeOrder !== 'function') {\n throw new Error('Core order finalizer is required')\n }\n\n const stripe = new Stripe(secretKey, {\n // API version can only be the latest, stripe recommends ts ignoring it\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - ignoring since possible versions are not type safe, only the latest version is recognised\n apiVersion: apiVersion || '2025-03-31.basil',\n appInfo: appInfo || {\n name: 'Stripe Payload Plugin',\n url: 'https://payloadcms.com',\n },\n })\n\n try {\n const transaction = await findTransaction({ paymentIntentID, req, transactionsSlug })\n const transactionID = requireDocumentID({\n fieldName: 'transaction ID',\n value: transaction.id,\n })\n const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentID)\n const cartItemsSnapshot = parseRequiredMetadata({\n fieldName: 'cartItemsSnapshot',\n value: paymentIntent.metadata.cartItemsSnapshot,\n })\n const shippingAddress = parseOptionalMetadata({\n fieldName: 'shippingAddress',\n value: paymentIntent.metadata.shippingAddress,\n })\n const purchaser =\n req.user === null || req.user === undefined\n ? { customerEmail: normalizeEmail(data.customerEmail) }\n : {\n customer: requireDocumentID({\n fieldName: 'authenticated customer ID',\n value: req.user.id,\n }),\n }\n\n validateSettlement({\n canonicalCartID: data.cartID,\n cartItemsSnapshot,\n customerEmail: data.customerEmail,\n paymentIntent,\n paymentIntentID,\n transaction,\n user: req.user,\n })\n\n const order = await finalizeOrder({\n orderData: {\n amount: transaction.amount,\n currency: transaction.currency,\n ...purchaser,\n items: cartItemsSnapshot,\n shippingAddress,\n status: 'processing',\n },\n transactionID,\n })\n\n return createConfirmationResult({ order, transactionID })\n } catch (error) {\n payload.logger.error({ err: error, msg: 'Error confirming order with Stripe' })\n\n throw new Error(error instanceof Error ? error.message : 'Unknown error initiating payment')\n }\n }\n\nconst createConfirmationResult = ({\n order,\n transactionID,\n}: {\n order: RecordValue\n transactionID: DefaultDocumentIDType\n}) => ({\n message: 'Payment initiated successfully',\n orderID: requireDocumentID({ fieldName: 'order ID', value: order.id }),\n transactionID,\n ...(typeof order.accessToken === 'string' ? { accessToken: order.accessToken } : {}),\n})\n\nconst findTransaction = async ({\n paymentIntentID,\n req,\n transactionsSlug,\n}: {\n paymentIntentID: string\n req: Parameters<NonNullable<PaymentAdapter>['confirmOrder']>[0]['req']\n transactionsSlug: string\n}): Promise<RecordValue> => {\n const result = await req.payload.find({\n collection: transactionsSlug,\n depth: 0,\n limit: 2,\n overrideAccess: true,\n pagination: false,\n req,\n where: {\n 'stripe.paymentIntentID': {\n equals: paymentIntentID,\n },\n },\n })\n\n if (result.totalDocs !== 1 || result.docs.length !== 1 || !result.docs[0]) {\n throw new Error('Expected exactly one transaction for the provided PaymentIntent ID')\n }\n\n return result.docs[0] as RecordValue\n}\n\nconst parseOptionalMetadata = ({\n fieldName,\n value,\n}: {\n fieldName: string\n value?: string\n}): RecordValue | undefined => {\n if (value === undefined) {\n return undefined\n }\n\n const parsedValue = parseRequiredMetadata({ fieldName, value })\n\n if (!isRecord(parsedValue)) {\n throw new Error(`${fieldName} metadata is invalid`)\n }\n\n return parsedValue\n}\n\nconst parseRequiredMetadata = ({\n fieldName,\n value,\n}: {\n fieldName: string\n value?: string\n}): unknown => {\n if (typeof value !== 'string' || !value) {\n throw new Error(`${fieldName} metadata is missing or invalid`)\n }\n\n try {\n return JSON.parse(value)\n } catch {\n throw new Error(`${fieldName} metadata is missing or invalid`)\n }\n}\n\nconst requireDocumentID = ({\n fieldName,\n value,\n}: {\n fieldName: string\n value: unknown\n}): DefaultDocumentIDType => {\n if (\n (typeof value !== 'number' || !Number.isFinite(value)) &&\n (typeof value !== 'string' || !value.trim())\n ) {\n throw new Error(`${fieldName} is missing or invalid`)\n }\n\n return value\n}\n\nconst isRecord = (value: unknown): value is RecordValue =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n"],"names":["Stripe","normalizeEmail","validateSettlement","confirmOrder","props","data","finalizeOrder","req","transactionsSlug","payload","apiVersion","appInfo","secretKey","paymentIntentID","Error","stripe","name","url","transaction","findTransaction","transactionID","requireDocumentID","fieldName","value","id","paymentIntent","paymentIntents","retrieve","cartItemsSnapshot","parseRequiredMetadata","metadata","shippingAddress","parseOptionalMetadata","purchaser","user","undefined","customerEmail","customer","canonicalCartID","cartID","order","orderData","amount","currency","items","status","createConfirmationResult","error","logger","err","msg","message","orderID","accessToken","result","find","collection","depth","limit","overrideAccess","pagination","where","equals","totalDocs","docs","length","parsedValue","isRecord","JSON","parse","Number","isFinite","trim","Array","isArray"],"mappings":"AAEA,OAAOA,YAAY,SAAQ;AAK3B,SAASC,cAAc,EAAEC,kBAAkB,QAAQ,0BAAyB;AAU5E,OAAO,MAAMC,eACX,CAACC,QACD,OAAO,EAAEC,IAAI,EAAEC,aAAa,EAAEC,GAAG,EAAEC,mBAAmB,cAAc,EAAE;QACpE,MAAMC,UAAUF,IAAIE,OAAO;QAC3B,MAAM,EAAEC,UAAU,EAAEC,OAAO,EAAEC,SAAS,EAAE,GAAGR,SAAS,CAAC;QACrD,MAAMS,kBAAkBR,KAAKQ,eAAe;QAE5C,IAAI,CAACD,WAAW;YACd,MAAM,IAAIE,MAAM;QAClB;QAEA,IAAI,OAAOD,oBAAoB,YAAY,CAACA,iBAAiB;YAC3D,MAAM,IAAIC,MAAM;QAClB;QAEA,IAAI,OAAOR,kBAAkB,YAAY;YACvC,MAAM,IAAIQ,MAAM;QAClB;QAEA,MAAMC,SAAS,IAAIf,OAAOY,WAAW;YACnC,uEAAuE;YACvE,6DAA6D;YAC7D,yGAAyG;YACzGF,YAAYA,cAAc;YAC1BC,SAASA,WAAW;gBAClBK,MAAM;gBACNC,KAAK;YACP;QACF;QAEA,IAAI;YACF,MAAMC,cAAc,MAAMC,gBAAgB;gBAAEN;gB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A,MAAMD,oBAAoB,CAAC,EACzBC,SAAS,EACTC,KAAK,EAIN;IACC,IACE,AAAC,CAAA,OAAOA,UAAU,YAAY,CAAC+C,OAAOC,QAAQ,CAAChD,MAAK,KACnD,CAAA,OAAOA,UAAU,YAAY,CAACA,MAAMiD,IAAI,EAAC,GAC1C;QACA,MAAM,IAAI1D,MAAM,GAAGQ,UAAU,sBAAsB,CAAC;IACtD;IAEA,OAAOC;AACT;AAEA,MAAM4C,WAAW,CAAC5C,QAChB,OAAOA,UAAU,YAAYA,UAAU,QAAQ,CAACkD,MAAMC,OAAO,CAACnD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initiatePayment.d.ts","sourceRoot":"","sources":["../../../../src/payments/adapters/stripe/initiatePayment.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAA;AAE3B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAC7D,OAAO,KAAK,EAA6B,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAE9E,KAAK,KAAK,GAAG;IACX,UAAU,CAAC,EAAE,MAAM,CAAC,YAAY,CAAC,YAAY,CAAC,CAAA;IAC9C,OAAO,CAAC,EAAE,MAAM,CAAC,YAAY,CAAC,SAAS,CAAC,CAAA;IACxC,SAAS,EAAE,iBAAiB,CAAC,WAAW,CAAC,CAAA;CAC1C,CAAA;AAED,eAAO,MAAM,eAAe,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,WAAW,CAAC,cAAc,CAAC,CAAC,iBAAiB,
|
|
1
|
+
{"version":3,"file":"initiatePayment.d.ts","sourceRoot":"","sources":["../../../../src/payments/adapters/stripe/initiatePayment.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAA;AAE3B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAC7D,OAAO,KAAK,EAA6B,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAE9E,KAAK,KAAK,GAAG;IACX,UAAU,CAAC,EAAE,MAAM,CAAC,YAAY,CAAC,YAAY,CAAC,CAAA;IAC9C,OAAO,CAAC,EAAE,MAAM,CAAC,YAAY,CAAC,SAAS,CAAC,CAAA;IACxC,SAAS,EAAE,iBAAiB,CAAC,WAAW,CAAC,CAAA;CAC1C,CAAA;AAED,eAAO,MAAM,eAAe,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,WAAW,CAAC,cAAc,CAAC,CAAC,iBAAiB,CA8H1F,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/payments/adapters/stripe/initiatePayment.ts"],"sourcesContent":["import Stripe from 'stripe'\n\nimport type { PaymentAdapter } from '../../../types/index.js'\nimport type { InitiatePaymentReturnType, StripeAdapterArgs } from './index.js'\n\ntype Props = {\n apiVersion?: Stripe.StripeConfig['apiVersion']\n appInfo?: Stripe.StripeConfig['appInfo']\n secretKey: StripeAdapterArgs['secretKey']\n}\n\nexport const initiatePayment: (props: Props) => NonNullable<PaymentAdapter>['initiatePayment'] =\n (props) =>\n async ({ data, req, transactionsSlug }) => {\n const payload = req.payload\n const { apiVersion, appInfo, secretKey } = props || {}\n\n const customerEmail = data.customerEmail\n const currency = data.currency\n const cart = data.cart\n const amount = cart.subtotal\n const billingAddressFromData = data.billingAddress\n const shippingAddressFromData = data.shippingAddress\n\n if (!secretKey) {\n throw new Error('Stripe secret key is required.')\n }\n\n if (!currency) {\n throw new Error('Currency is required.')\n }\n\n if (!cart || !cart.items || cart.items.length === 0) {\n throw new Error('Cart is empty or not provided.')\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 (!amount || typeof amount !== 'number' || amount <= 0) {\n throw new Error('A valid amount is required to initiate a payment.')\n }\n\n const stripe = new Stripe(secretKey, {\n // API version can only be the latest, stripe recommends ts ignoring it\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - ignoring since possible versions are not type safe, only the latest version is recognised\n apiVersion: apiVersion || '2025-06-30.preview',\n appInfo: appInfo || {\n name: 'Stripe Payload Plugin',\n url: 'https://payloadcms.com',\n },\n })\n\n try {\n let customer = (\n await stripe.customers.list({\n email: customerEmail,\n })\n ).data[0]\n\n if (!customer?.id) {\n customer = await stripe.customers.create({\n email: customerEmail,\n })\n }\n\n const flattenedCart = cart.items.map((item) => {\n const productID = typeof item.product === 'object' ? item.product.id : item.product\n const variantID = item.variant\n ? typeof item.variant === 'object'\n ? item.variant.id\n : item.variant\n : undefined\n\n // Preserve any additional custom properties (e.g., deliveryOption, customizations)\n // that may have been added via cartItemMatcher\n const { product: _product, variant: _variant, ...customProperties } = item\n\n return {\n ...customProperties,\n product: productID,\n quantity: item.quantity,\n ...(variantID ? { variant: variantID } : {}),\n }\n })\n\n const shippingAddressAsString = JSON.stringify(shippingAddressFromData)\n\n const paymentIntent = await stripe.paymentIntents.create({\n amount,\n automatic_payment_methods: {\n enabled: true,\n },\n currency,\n customer: customer.id,\n metadata: {\n cartID: cart.id,\n cartItemsSnapshot: JSON.stringify(flattenedCart),\n shippingAddress: shippingAddressAsString,\n },\n })\n\n // Create a transaction for the payment intent in the database\n const transaction = await payload.create({\n collection: transactionsSlug,\n data: {\n ...(req.user ? { customer: req.user.id } : { customerEmail }),\n amount: paymentIntent.amount,\n billingAddress: billingAddressFromData,\n cart: cart.id,\n currency: paymentIntent.currency.toUpperCase(),\n items: flattenedCart,\n paymentMethod: 'stripe',\n status: 'pending',\n stripe: {\n customerID: customer.id,\n paymentIntentID: paymentIntent.id,\n },\n },\n req,\n })\n\n const returnData: InitiatePaymentReturnType = {\n clientSecret: paymentIntent.client_secret || '',\n message: 'Payment initiated successfully',\n paymentIntentID: paymentIntent.id,\n }\n\n return returnData\n } catch (error) {\n payload.logger.error({ err: error, msg: 'Error initiating payment with Stripe' })\n\n throw new Error(error instanceof Error ? error.message : 'Unknown error initiating payment')\n }\n }\n"],"names":["Stripe","initiatePayment","props","data","req","transactionsSlug","payload","apiVersion","appInfo","secretKey","customerEmail","currency","cart","amount","subtotal","billingAddressFromData","billingAddress","shippingAddressFromData","shippingAddress","Error","items","length","stripe","name","url","customer","customers","list","email","id","create","flattenedCart","map","item","productID","product","variantID","variant","undefined","_product","_variant","customProperties","quantity","shippingAddressAsString","JSON","stringify","paymentIntent","paymentIntents","automatic_payment_methods","enabled","metadata","cartID","cartItemsSnapshot","transaction","collection","user","toUpperCase","paymentMethod","status","customerID","paymentIntentID","returnData","clientSecret","client_secret","message","error","logger","err","msg"],"mappings":"AAAA,OAAOA,YAAY,SAAQ;AAW3B,OAAO,MAAMC,kBACX,CAACC,QACD,OAAO,EAAEC,IAAI,EAAEC,GAAG,EAAEC,gBAAgB,EAAE;QACpC,MAAMC,UAAUF,IAAIE,OAAO;QAC3B,MAAM,EAAEC,UAAU,EAAEC,OAAO,EAAEC,SAAS,EAAE,GAAGP,SAAS,CAAC;QAErD,MAAMQ,gBAAgBP,KAAKO,aAAa;QACxC,MAAMC,WAAWR,KAAKQ,QAAQ;QAC9B,MAAMC,OAAOT,KAAKS,IAAI;QACtB,MAAMC,SAASD,KAAKE,QAAQ;QAC5B,MAAMC,yBAAyBZ,KAAKa,cAAc;QAClD,MAAMC,0BAA0Bd,KAAKe,eAAe;QAEpD,IAAI,CAACT,WAAW;YACd,MAAM,IAAIU,MAAM;QAClB;QAEA,IAAI,CAACR,UAAU;YACb,MAAM,IAAIQ,MAAM;QAClB;QAEA,IAAI,CAACP,QAAQ,CAACA,KAAKQ,KAAK,IAAIR,KAAKQ,KAAK,CAACC,MAAM,KAAK,GAAG;YACnD,MAAM,IAAIF,MAAM;QAClB;QAEA,IAAI,CAACT,iBAAiB,OAAOA,kBAAkB,UAAU;YACvD,MAAM,IAAIS,MAAM;QAClB;QAEA,IAAI,CAACN,UAAU,OAAOA,WAAW,YAAYA,UAAU,GAAG;YACxD,MAAM,IAAIM,MAAM;QAClB;QAEA,MAAMG,SAAS,I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Cb,iBAAiByB;gBACnB;YACF;YAEA,8DAA8D;YAC9D,MAAMU,cAAc,MAAM/C,QAAQwB,MAAM,CAAC;gBACvCwB,YAAYjD;gBACZF,MAAM;oBACJ,GAAIC,IAAImD,IAAI,GAAG;wBAAE9B,UAAUrB,IAAImD,IAAI,CAAC1B,EAAE;oBAAC,IAAI;wBAAEnB;oBAAc,CAAC;oBAC5DG,QAAQiC,cAAcjC,MAAM;oBAC5BG,gBAAgBD;oBAChBH,MAAMA,KAAKiB,EAAE;oBACblB,UAAUmC,cAAcnC,QAAQ,CAAC6C,WAAW;oBAC5CpC,OAAOW;oBACP0B,eAAe;oBACfC,QAAQ;oBACRpC,QAAQ;wBACNqC,YAAYlC,SAASI,EAAE;wBACvB+B,iBAAiBd,cAAcjB,EAAE;oBACnC;gBACF;
|
|
1
|
+
{"version":3,"sources":["../../../../src/payments/adapters/stripe/initiatePayment.ts"],"sourcesContent":["import Stripe from 'stripe'\n\nimport type { PaymentAdapter } from '../../../types/index.js'\nimport type { InitiatePaymentReturnType, StripeAdapterArgs } from './index.js'\n\ntype Props = {\n apiVersion?: Stripe.StripeConfig['apiVersion']\n appInfo?: Stripe.StripeConfig['appInfo']\n secretKey: StripeAdapterArgs['secretKey']\n}\n\nexport const initiatePayment: (props: Props) => NonNullable<PaymentAdapter>['initiatePayment'] =\n (props) =>\n async ({ data, req, transactionsSlug }) => {\n const payload = req.payload\n const { apiVersion, appInfo, secretKey } = props || {}\n\n const customerEmail = data.customerEmail\n const currency = data.currency\n const cart = data.cart\n const amount = cart.subtotal\n const billingAddressFromData = data.billingAddress\n const shippingAddressFromData = data.shippingAddress\n\n if (!secretKey) {\n throw new Error('Stripe secret key is required.')\n }\n\n if (!currency) {\n throw new Error('Currency is required.')\n }\n\n if (!cart || !cart.items || cart.items.length === 0) {\n throw new Error('Cart is empty or not provided.')\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 (!amount || typeof amount !== 'number' || amount <= 0) {\n throw new Error('A valid amount is required to initiate a payment.')\n }\n\n const stripe = new Stripe(secretKey, {\n // API version can only be the latest, stripe recommends ts ignoring it\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - ignoring since possible versions are not type safe, only the latest version is recognised\n apiVersion: apiVersion || '2025-06-30.preview',\n appInfo: appInfo || {\n name: 'Stripe Payload Plugin',\n url: 'https://payloadcms.com',\n },\n })\n\n try {\n let customer = (\n await stripe.customers.list({\n email: customerEmail,\n })\n ).data[0]\n\n if (!customer?.id) {\n customer = await stripe.customers.create({\n email: customerEmail,\n })\n }\n\n const flattenedCart = cart.items.map((item) => {\n const productID = typeof item.product === 'object' ? item.product.id : item.product\n const variantID = item.variant\n ? typeof item.variant === 'object'\n ? item.variant.id\n : item.variant\n : undefined\n\n // Preserve any additional custom properties (e.g., deliveryOption, customizations)\n // that may have been added via cartItemMatcher\n const { product: _product, variant: _variant, ...customProperties } = item\n\n return {\n ...customProperties,\n product: productID,\n quantity: item.quantity,\n ...(variantID ? { variant: variantID } : {}),\n }\n })\n\n const shippingAddressAsString = JSON.stringify(shippingAddressFromData)\n\n const paymentIntent = await stripe.paymentIntents.create({\n amount,\n automatic_payment_methods: {\n enabled: true,\n },\n currency,\n customer: customer.id,\n metadata: {\n cartID: cart.id,\n cartItemsSnapshot: JSON.stringify(flattenedCart),\n shippingAddress: shippingAddressAsString,\n },\n })\n\n // Create a transaction for the payment intent in the database\n const transaction = await payload.create({\n collection: transactionsSlug,\n data: {\n ...(req.user ? { customer: req.user.id } : { customerEmail }),\n amount: paymentIntent.amount,\n billingAddress: billingAddressFromData,\n cart: cart.id,\n currency: paymentIntent.currency.toUpperCase(),\n items: flattenedCart,\n paymentMethod: 'stripe',\n status: 'pending',\n stripe: {\n customerID: customer.id,\n paymentIntentID: paymentIntent.id,\n },\n },\n overrideAccess: true,\n req,\n })\n\n const returnData: InitiatePaymentReturnType = {\n clientSecret: paymentIntent.client_secret || '',\n message: 'Payment initiated successfully',\n paymentIntentID: paymentIntent.id,\n }\n\n return returnData\n } catch (error) {\n payload.logger.error({ err: error, msg: 'Error initiating payment with Stripe' })\n\n throw new Error(error instanceof Error ? error.message : 'Unknown error initiating payment')\n }\n }\n"],"names":["Stripe","initiatePayment","props","data","req","transactionsSlug","payload","apiVersion","appInfo","secretKey","customerEmail","currency","cart","amount","subtotal","billingAddressFromData","billingAddress","shippingAddressFromData","shippingAddress","Error","items","length","stripe","name","url","customer","customers","list","email","id","create","flattenedCart","map","item","productID","product","variantID","variant","undefined","_product","_variant","customProperties","quantity","shippingAddressAsString","JSON","stringify","paymentIntent","paymentIntents","automatic_payment_methods","enabled","metadata","cartID","cartItemsSnapshot","transaction","collection","user","toUpperCase","paymentMethod","status","customerID","paymentIntentID","overrideAccess","returnData","clientSecret","client_secret","message","error","logger","err","msg"],"mappings":"AAAA,OAAOA,YAAY,SAAQ;AAW3B,OAAO,MAAMC,kBACX,CAACC,QACD,OAAO,EAAEC,IAAI,EAAEC,GAAG,EAAEC,gBAAgB,EAAE;QACpC,MAAMC,UAAUF,IAAIE,OAAO;QAC3B,MAAM,EAAEC,UAAU,EAAEC,OAAO,EAAEC,SAAS,EAAE,GAAGP,SAAS,CAAC;QAErD,MAAMQ,gBAAgBP,KAAKO,aAAa;QACxC,MAAMC,WAAWR,KAAKQ,QAAQ;QAC9B,MAAMC,OAAOT,KAAKS,IAAI;QACtB,MAAMC,SAASD,KAAKE,QAAQ;QAC5B,MAAMC,yBAAyBZ,KAAKa,cAAc;QAClD,MAAMC,0BAA0Bd,KAAKe,eAAe;QAEpD,IAAI,CAACT,WAAW;YACd,MAAM,IAAIU,MAAM;QAClB;QAEA,IAAI,CAACR,UAAU;YACb,MAAM,IAAIQ,MAAM;QAClB;QAEA,IAAI,CAACP,QAAQ,CAACA,KAAKQ,KAAK,IAAIR,KAAKQ,KAAK,CAACC,MAAM,KAAK,GAAG;YACnD,MAAM,IAAIF,MAAM;QAClB;QAEA,IAAI,CA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AC;gBACvDjB;gBACAmC,2BAA2B;oBACzBC,SAAS;gBACX;gBACAtC;gBACAc,UAAUA,SAASI,EAAE;gBACrBqB,UAAU;oBACRC,QAAQvC,KAAKiB,EAAE;oBACfuB,mBAAmBR,KAAKC,SAAS,CAACd;oBAClCb,iBAAiByB;gBACnB;YACF;YAEA,8DAA8D;YAC9D,MAAMU,cAAc,MAAM/C,QAAQwB,MAAM,CAAC;gBACvCwB,YAAYjD;gBACZF,MAAM;oBACJ,GAAIC,IAAImD,IAAI,GAAG;wBAAE9B,UAAUrB,IAAImD,IAAI,CAAC1B,EAAE;oBAAC,IAAI;wBAAEnB;oBAAc,CAAC;oBAC5DG,QAAQiC,cAAcjC,MAAM;oBAC5BG,gBAAgBD;oBAChBH,MAAMA,KAAKiB,EAAE;oBACblB,UAAUmC,cAAcnC,QAAQ,CAAC6C,WAAW;oBAC5CpC,OAAOW;oBACP0B,eAAe;oBACfC,QAAQ;oBACRpC,QAAQ;wBACNqC,YAAYlC,SAASI,EAAE;wBACvB+B,iBAAiBd,cAAcjB,EAAE;oBACnC;gBACF;gBACAgC,gBAAgB;gBAChBzD;YACF;YAEA,MAAM0D,aAAwC;gBAC5CC,cAAcjB,cAAckB,aAAa,IAAI;gBAC7CC,SAAS;gBACTL,iBAAiBd,cAAcjB,EAAE;YACnC;YAEA,OAAOiC;QACT,EAAE,OAAOI,OAAO;YACd5D,QAAQ6D,MAAM,CAACD,KAAK,CAAC;gBAAEE,KAAKF;gBAAOG,KAAK;YAAuC;YAE/E,MAAM,IAAIlD,MAAM+C,iBAAiB/C,QAAQ+C,MAAMD,OAAO,GAAG;QAC3D;IACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/ui/VariantOptionsSelector/index.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAA;AAKrD,OAAO,aAAa,CAAA;AAGpB,KAAK,KAAK,GAAG,EAAE,GAAG,sBAAsB,CAAA;AAExC,eAAO,MAAM,sBAAsB,EAAE,KAAK,CAAC,EAAE,CAAC,KAAK,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/ui/VariantOptionsSelector/index.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAA;AAKrD,OAAO,aAAa,CAAA;AAGpB,KAAK,KAAK,GAAG,EAAE,GAAG,sBAAsB,CAAA;AAExC,eAAO,MAAM,sBAAsB,EAAE,KAAK,CAAC,EAAE,CAAC,KAAK,CAgFlD,CAAA"}
|
|
@@ -14,6 +14,7 @@ export const VariantOptionsSelector = async (props)=>{
|
|
|
14
14
|
collection: productsSlug,
|
|
15
15
|
depth: 0,
|
|
16
16
|
draft: true,
|
|
17
|
+
overrideAccess: true,
|
|
17
18
|
select: {
|
|
18
19
|
variants: true,
|
|
19
20
|
variantTypes: true
|
|
@@ -37,7 +38,8 @@ export const VariantOptionsSelector = async (props)=>{
|
|
|
37
38
|
options: {
|
|
38
39
|
sort: 'value'
|
|
39
40
|
}
|
|
40
|
-
}
|
|
41
|
+
},
|
|
42
|
+
overrideAccess: true
|
|
41
43
|
});
|
|
42
44
|
if (variantType) {
|
|
43
45
|
variantTypes.push(variantType);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/ui/VariantOptionsSelector/index.tsx"],"sourcesContent":["import type { SelectFieldServerProps } from 'payload'\n\nimport { FieldLabel } from '@payloadcms/ui'\n\nimport { ErrorBox } from './ErrorBox.js'\nimport './index.css'\nimport { OptionsSelect } from './OptionsSelect.js'\n\ntype Props = {} & SelectFieldServerProps\n\nexport const VariantOptionsSelector: React.FC<Props> = async (props) => {\n const { clientField, data, field, path, req, user } = props\n const { label } = clientField\n\n // Get collection slugs from field custom prop, with defaults for backwards compatibility\n const productsSlug = (field.custom?.productsSlug as string) || 'products'\n const variantTypesSlug = (field.custom?.variantTypesSlug as string) || 'variantTypes'\n\n const product = await req.payload.findByID({\n id: data.product,\n collection: productsSlug,\n depth: 0,\n draft: true,\n select: {\n variants: true,\n variantTypes: true,\n },\n user,\n })\n\n // @ts-expect-error - TODO: Fix types\n const existingVariantOptions = product.variants?.docs?.map((variant) => variant.options) ?? []\n\n const variantTypeIDs = product.variantTypes\n\n const variantTypes = []\n\n // Need to get the variant types separately so that the options are populated\n // @ts-expect-error - TODO: Fix types\n if (variantTypeIDs?.length && variantTypeIDs.length > 0) {\n // @ts-expect-error - TODO: Fix types\n for (const variantTypeID of variantTypeIDs) {\n const variantType = await req.payload.findByID({\n id: variantTypeID,\n collection: variantTypesSlug,\n depth: 1,\n joins: {\n options: {\n sort: 'value',\n },\n },\n })\n\n if (variantType) {\n variantTypes.push(variantType)\n }\n }\n }\n\n return (\n <div className=\"variantOptionsSelector\">\n <div className=\"variantOptionsSelectorHeading\">\n <FieldLabel as=\"span\" label={label} />\n </div>\n\n <ErrorBox existingOptions={existingVariantOptions} path={path}>\n <div className=\"variantOptionsSelectorList\">\n {variantTypes.map((type) => {\n // @ts-expect-error - TODO: Fix types\n const options = type.options.docs.map((option) => ({\n label: option.label,\n value: option.id,\n }))\n\n return (\n <OptionsSelect\n field={clientField}\n key={type.name}\n label={type.label || type.name}\n options={options}\n path={path}\n />\n )\n })}\n </div>\n </ErrorBox>\n </div>\n )\n}\n"],"names":["FieldLabel","ErrorBox","OptionsSelect","VariantOptionsSelector","props","clientField","data","field","path","req","user","label","productsSlug","custom","variantTypesSlug","product","payload","findByID","id","collection","depth","draft","select","variants","variantTypes","existingVariantOptions","docs","map","variant","options","variantTypeIDs","length","variantTypeID","variantType","joins","sort","push","div","className","as","existingOptions","type","option","value","name"],"mappings":";AAEA,SAASA,UAAU,QAAQ,iBAAgB;AAE3C,SAASC,QAAQ,QAAQ,gBAAe;AACxC,OAAO,cAAa;AACpB,SAASC,aAAa,QAAQ,qBAAoB;AAIlD,OAAO,MAAMC,yBAA0C,OAAOC;IAC5D,MAAM,EAAEC,WAAW,EAAEC,IAAI,EAAEC,KAAK,EAAEC,IAAI,EAAEC,GAAG,EAAEC,IAAI,EAAE,GAAGN;IACtD,MAAM,EAAEO,KAAK,EAAE,GAAGN;IAElB,yFAAyF;IACzF,MAAMO,eAAe,AAACL,MAAMM,MAAM,EAAED,gBAA2B;IAC/D,MAAME,mBAAmB,AAACP,MAAMM,MAAM,EAAEC,oBAA+B;IAEvE,MAAMC,UAAU,MAAMN,IAAIO,OAAO,CAACC,QAAQ,CAAC;QACzCC,IAAIZ,KAAKS,OAAO;QAChBI,YAAYP;QACZQ,OAAO;QACPC,OAAO;QACPC,QAAQ;YACNC,UAAU;YACVC,cAAc;QAChB;
|
|
1
|
+
{"version":3,"sources":["../../../src/ui/VariantOptionsSelector/index.tsx"],"sourcesContent":["import type { SelectFieldServerProps } from 'payload'\n\nimport { FieldLabel } from '@payloadcms/ui'\n\nimport { ErrorBox } from './ErrorBox.js'\nimport './index.css'\nimport { OptionsSelect } from './OptionsSelect.js'\n\ntype Props = {} & SelectFieldServerProps\n\nexport const VariantOptionsSelector: React.FC<Props> = async (props) => {\n const { clientField, data, field, path, req, user } = props\n const { label } = clientField\n\n // Get collection slugs from field custom prop, with defaults for backwards compatibility\n const productsSlug = (field.custom?.productsSlug as string) || 'products'\n const variantTypesSlug = (field.custom?.variantTypesSlug as string) || 'variantTypes'\n\n const product = await req.payload.findByID({\n id: data.product,\n collection: productsSlug,\n depth: 0,\n draft: true,\n overrideAccess: true,\n select: {\n variants: true,\n variantTypes: true,\n },\n user,\n })\n\n // @ts-expect-error - TODO: Fix types\n const existingVariantOptions = product.variants?.docs?.map((variant) => variant.options) ?? []\n\n const variantTypeIDs = product.variantTypes\n\n const variantTypes = []\n\n // Need to get the variant types separately so that the options are populated\n // @ts-expect-error - TODO: Fix types\n if (variantTypeIDs?.length && variantTypeIDs.length > 0) {\n // @ts-expect-error - TODO: Fix types\n for (const variantTypeID of variantTypeIDs) {\n const variantType = await req.payload.findByID({\n id: variantTypeID,\n collection: variantTypesSlug,\n depth: 1,\n joins: {\n options: {\n sort: 'value',\n },\n },\n overrideAccess: true,\n })\n\n if (variantType) {\n variantTypes.push(variantType)\n }\n }\n }\n\n return (\n <div className=\"variantOptionsSelector\">\n <div className=\"variantOptionsSelectorHeading\">\n <FieldLabel as=\"span\" label={label} />\n </div>\n\n <ErrorBox existingOptions={existingVariantOptions} path={path}>\n <div className=\"variantOptionsSelectorList\">\n {variantTypes.map((type) => {\n // @ts-expect-error - TODO: Fix types\n const options = type.options.docs.map((option) => ({\n label: option.label,\n value: option.id,\n }))\n\n return (\n <OptionsSelect\n field={clientField}\n key={type.name}\n label={type.label || type.name}\n options={options}\n path={path}\n />\n )\n })}\n </div>\n </ErrorBox>\n </div>\n )\n}\n"],"names":["FieldLabel","ErrorBox","OptionsSelect","VariantOptionsSelector","props","clientField","data","field","path","req","user","label","productsSlug","custom","variantTypesSlug","product","payload","findByID","id","collection","depth","draft","overrideAccess","select","variants","variantTypes","existingVariantOptions","docs","map","variant","options","variantTypeIDs","length","variantTypeID","variantType","joins","sort","push","div","className","as","existingOptions","type","option","value","name"],"mappings":";AAEA,SAASA,UAAU,QAAQ,iBAAgB;AAE3C,SAASC,QAAQ,QAAQ,gBAAe;AACxC,OAAO,cAAa;AACpB,SAASC,aAAa,QAAQ,qBAAoB;AAIlD,OAAO,MAAMC,yBAA0C,OAAOC;IAC5D,MAAM,EAAEC,WAAW,EAAEC,IAAI,EAAEC,KAAK,EAAEC,IAAI,EAAEC,GAAG,EAAEC,IAAI,EAAE,GAAGN;IACtD,MAAM,EAAEO,KAAK,EAAE,GAAGN;IAElB,yFAAyF;IACzF,MAAMO,eAAe,AAACL,MAAMM,MAAM,EAAED,gBAA2B;IAC/D,MAAME,mBAAmB,AAACP,MAAMM,MAAM,EAAEC,oBAA+B;IAEvE,MAAMC,UAAU,MAAMN,IAAIO,OAAO,CAACC,QAAQ,CAAC;QACzCC,IAAIZ,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BAMpB;;;;;AAKV,EAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@payloadcms/plugin-ecommerce",
|
|
3
|
-
"version": "4.0.0-internal.
|
|
3
|
+
"version": "4.0.0-internal.7d5c665",
|
|
4
4
|
"description": "Ecommerce plugin for Payload",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"payload",
|
|
@@ -74,23 +74,23 @@
|
|
|
74
74
|
],
|
|
75
75
|
"dependencies": {
|
|
76
76
|
"qs-esm": "8.0.1",
|
|
77
|
-
"@payloadcms/translations": "4.0.0-internal.
|
|
78
|
-
"@payloadcms/ui": "4.0.0-internal.
|
|
77
|
+
"@payloadcms/translations": "4.0.0-internal.7d5c665",
|
|
78
|
+
"@payloadcms/ui": "4.0.0-internal.7d5c665"
|
|
79
79
|
},
|
|
80
80
|
"devDependencies": {
|
|
81
81
|
"@types/json-schema": "7.0.15",
|
|
82
|
-
"@types/react": "19.
|
|
83
|
-
"@types/react-dom": "19.
|
|
82
|
+
"@types/react": "19.3.0",
|
|
83
|
+
"@types/react-dom": "19.3.0",
|
|
84
84
|
"stripe": "18.3.0",
|
|
85
85
|
"@payloadcms/eslint-config": "3.28.0",
|
|
86
|
-
"@payloadcms/
|
|
87
|
-
"@payloadcms/
|
|
88
|
-
"payload": "4.0.0-internal.
|
|
86
|
+
"@payloadcms/translations": "4.0.0-internal.7d5c665",
|
|
87
|
+
"@payloadcms/next": "4.0.0-internal.7d5c665",
|
|
88
|
+
"payload": "4.0.0-internal.7d5c665"
|
|
89
89
|
},
|
|
90
90
|
"peerDependencies": {
|
|
91
91
|
"react": "^19.0.1 || ^19.1.2 || ^19.2.1",
|
|
92
92
|
"react-dom": "^19.0.1 || ^19.1.2 || ^19.2.1",
|
|
93
|
-
"payload": "4.0.0-internal.
|
|
93
|
+
"payload": "4.0.0-internal.7d5c665"
|
|
94
94
|
},
|
|
95
95
|
"publishConfig": {
|
|
96
96
|
"registry": "https://registry.npmjs.org/"
|