@jarwizz/create-jarshop 0.1.9 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +15 -0
  2. package/dist/cli.d.ts +1 -0
  3. package/dist/cli.js +1 -0
  4. package/dist/cli.js.map +1 -1
  5. package/dist/generator.d.ts +11 -1
  6. package/dist/generator.js +45 -11
  7. package/dist/generator.js.map +1 -1
  8. package/dist/presets.d.ts +28 -0
  9. package/dist/presets.js +105 -0
  10. package/dist/presets.js.map +1 -0
  11. package/dist/template/CONTEXT.md +4 -2
  12. package/dist/template/README.md +255 -3
  13. package/dist/template/env.example.template +19 -0
  14. package/dist/template/gitignore.template +1 -0
  15. package/dist/template/jarshop.config.ts +37 -0
  16. package/dist/template/package.json +4 -0
  17. package/dist/template/pnpm-lock.yaml +3284 -1815
  18. package/dist/template/pnpm-workspace.yaml +6 -1
  19. package/dist/template/src/client/features.ts +41 -0
  20. package/dist/template/src/client/invoicing.ts +29 -0
  21. package/dist/template/src/dev-storefront-environment.test.ts +45 -0
  22. package/dist/template/src/dev-storefront-environment.ts +32 -0
  23. package/dist/template/src/dev-storefront.ts +3 -12
  24. package/dist/template/src/environment.d.ts +8 -0
  25. package/dist/template/src/invoice-email-recover.ts +59 -0
  26. package/dist/template/src/jarshop-config-loader.ts +118 -0
  27. package/dist/template/src/jarshop-config.test.ts +365 -0
  28. package/dist/template/src/jarshop-config.ts +462 -0
  29. package/dist/template/src/jarshop-features.test.ts +222 -0
  30. package/dist/template/src/jarshop-features.ts +112 -0
  31. package/dist/template/src/migrations/1788100000000-jarshop-guest-order-session.ts +27 -0
  32. package/dist/template/src/operation-codes.ts +34 -0
  33. package/dist/template/src/packeta-config.test.ts +95 -0
  34. package/dist/template/src/packeta-countries.test.ts +161 -0
  35. package/dist/template/src/packeta-countries.ts +120 -0
  36. package/dist/template/src/packeta-validation.test.ts +35 -0
  37. package/dist/template/src/packeta-validation.ts +52 -0
  38. package/dist/template/src/payment-return-url.test.ts +57 -0
  39. package/dist/template/src/payment-return-url.ts +34 -0
  40. package/dist/template/src/plugins/jarshop-checkout/confirmation-view.test.ts +79 -0
  41. package/dist/template/src/plugins/jarshop-checkout/confirmation.ts +51 -0
  42. package/dist/template/src/plugins/jarshop-checkout/dashboard/index.tsx +1 -0
  43. package/dist/template/src/plugins/jarshop-checkout/index.ts +4 -0
  44. package/dist/template/src/plugins/jarshop-checkout/invoice-delivery.plugin.ts +79 -0
  45. package/dist/template/src/plugins/jarshop-checkout/invoice-email-events.ts +35 -0
  46. package/dist/template/src/plugins/jarshop-checkout/invoice-email-lifecycle.ts +235 -0
  47. package/dist/template/src/plugins/jarshop-checkout/invoice-email-worker.test.ts +426 -0
  48. package/dist/template/src/plugins/jarshop-checkout/invoice-email.test.ts +107 -0
  49. package/dist/template/src/plugins/jarshop-checkout/jarshop-checkout.plugin.ts +167 -58
  50. package/dist/template/src/plugins/jarshop-checkout/market-active-order-core.ts +108 -0
  51. package/dist/template/src/plugins/jarshop-checkout/market-active-order.test.ts +205 -0
  52. package/dist/template/src/plugins/jarshop-checkout/market-active-order.ts +186 -0
  53. package/dist/template/src/plugins/jarshop-checkout/market-channels.test.ts +58 -0
  54. package/dist/template/src/plugins/jarshop-checkout/market-channels.ts +87 -0
  55. package/dist/template/src/plugins/jarshop-checkout/operation-code-check.ts +36 -0
  56. package/dist/template/src/plugins/jarshop-checkout/order-email-configuration.entity.ts +1 -1
  57. package/dist/template/src/plugins/jarshop-checkout/order-email-configuration.ts +1 -0
  58. package/dist/template/src/plugins/jarshop-checkout/order-email-delivery-core.ts +94 -1
  59. package/dist/template/src/plugins/jarshop-checkout/order-email-delivery.entity.ts +1 -0
  60. package/dist/template/src/plugins/jarshop-checkout/order-email-outbox.ts +83 -1
  61. package/dist/template/src/plugins/jarshop-checkout/order-email-worker.ts +136 -1
  62. package/dist/template/src/plugins/jarshop-checkout/shipping-tax.test.ts +109 -0
  63. package/dist/template/src/plugins/jarshop-checkout/shipping.test.ts +156 -0
  64. package/dist/template/src/plugins/jarshop-checkout/shipping.ts +75 -11
  65. package/dist/template/src/seed.ts +473 -185
  66. package/dist/template/src/vendure-config.ts +258 -113
  67. package/dist/template/storefront/README.md +7 -0
  68. package/dist/template/storefront/app/[locale]/[slug]/page.tsx +3 -2
  69. package/dist/template/storefront/app/[locale]/account/login/page.tsx +3 -2
  70. package/dist/template/storefront/app/[locale]/account/page.tsx +10 -4
  71. package/dist/template/storefront/app/[locale]/account/password-reset/callback/route.ts +4 -2
  72. package/dist/template/storefront/app/[locale]/account/password-reset/complete/page.tsx +3 -2
  73. package/dist/template/storefront/app/[locale]/account/password-reset/page.tsx +3 -2
  74. package/dist/template/storefront/app/[locale]/account/register/page.tsx +3 -2
  75. package/dist/template/storefront/app/[locale]/account/verify/complete/route.ts +4 -2
  76. package/dist/template/storefront/app/[locale]/account/verify/page.tsx +3 -2
  77. package/dist/template/storefront/app/[locale]/cart/page.tsx +3 -2
  78. package/dist/template/storefront/app/[locale]/checkout/actions.ts +43 -0
  79. package/dist/template/storefront/app/[locale]/checkout/checkout-form.tsx +188 -36
  80. package/dist/template/storefront/app/[locale]/checkout/confirmation/route.ts +2 -2
  81. package/dist/template/storefront/app/[locale]/checkout/packeta-chooser.tsx +96 -0
  82. package/dist/template/storefront/app/[locale]/checkout/page.tsx +60 -2
  83. package/dist/template/storefront/app/[locale]/checkout/payment-return/actions.ts +55 -0
  84. package/dist/template/storefront/app/[locale]/checkout/payment-return/page.tsx +32 -0
  85. package/dist/template/storefront/app/[locale]/checkout/payment-return/payment-return.tsx +84 -0
  86. package/dist/template/storefront/app/[locale]/checkout/success/page.tsx +32 -2
  87. package/dist/template/storefront/app/[locale]/layout.tsx +3 -2
  88. package/dist/template/storefront/app/[locale]/page.tsx +3 -2
  89. package/dist/template/storefront/app/globals.css +16 -0
  90. package/dist/template/storefront/app/layout.tsx +6 -2
  91. package/dist/template/storefront/lib/cart.ts +2 -4
  92. package/dist/template/storefront/lib/checkout-contract.test.ts +18 -1
  93. package/dist/template/storefront/lib/checkout-contract.ts +8 -0
  94. package/dist/template/storefront/lib/checkout-countries.test.ts +61 -0
  95. package/dist/template/storefront/lib/checkout-countries.ts +67 -0
  96. package/dist/template/storefront/lib/checkout.ts +22 -11
  97. package/dist/template/storefront/lib/commerce.ts +262 -2
  98. package/dist/template/storefront/lib/confirmation.test.ts +116 -0
  99. package/dist/template/storefront/lib/confirmation.ts +13 -7
  100. package/dist/template/storefront/lib/i18n.test.ts +32 -12
  101. package/dist/template/storefront/lib/i18n.ts +29 -8
  102. package/dist/template/storefront/lib/market-config.ts +40 -0
  103. package/dist/template/storefront/lib/market-routing.test.ts +107 -0
  104. package/dist/template/storefront/lib/market-routing.ts +57 -0
  105. package/dist/template/storefront/lib/market.ts +51 -0
  106. package/dist/template/storefront/lib/packeta-selection.test.ts +141 -0
  107. package/dist/template/storefront/lib/packeta-selection.ts +98 -0
  108. package/dist/template/storefront/lib/payment-return-actions.test.ts +61 -0
  109. package/dist/template/storefront/lib/payment-return-page.test.ts +30 -0
  110. package/dist/template/storefront/lib/payment-return-polling.test.ts +37 -0
  111. package/dist/template/storefront/lib/payment-return-polling.ts +58 -0
  112. package/dist/template/storefront/messages/en.json +13 -1
  113. package/dist/template/storefront/messages/sk.json +13 -1
  114. package/dist/template/storefront/package.json +2 -1
  115. package/dist/template/storefront/proxy.ts +35 -0
  116. package/dist/template/turbo.json +5 -1
  117. package/dist/template-manifest.json +1 -1
  118. package/dist/template.js +1 -0
  119. package/dist/template.js.map +1 -1
  120. package/package.json +1 -1
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Stable public API for client-owned `src/client/`.
3
+ *
4
+ * `src/client/features.ts` imports from this module, and upgrades never touch
5
+ * that file, so every export here is a contract with existing Client
6
+ * Projects: `JarShopFeatures` and its item types (`JarShopPaymentMethodHandler`,
7
+ * `JarShopShippingEligibilityChecker`, `JarShopShippingCalculator`,
8
+ * `JarShopPlugin`, `JarShopMigration`), `jarShopCodPaymentHandler` and
9
+ * `referenceRedirectPaymentHandler`. Renaming or removing one, or narrowing a
10
+ * type, is a breaking change of the Starter Release and needs a major
11
+ * create-jarshop version and an upgrade note (ADR-0016). Add new exports
12
+ * instead of changing existing ones.
13
+ */
14
+ import type {
15
+ PaymentOptions,
16
+ ShippingOptions,
17
+ VendureConfig,
18
+ } from "@vendure/core";
19
+ import type { MigrationInterface } from "typeorm";
20
+ import { createRedirectPaymentMethodHandler } from "@jarwizz/feature-adapter-kit/server";
21
+ import { createReferenceRedirectPaymentAdapter } from "@jarwizz/feature-adapter-kit";
22
+ import type { JarShopInvoicingConfig } from "@jarwizz/jarshop-invoicing/server";
23
+
24
+ export { jarShopCodPaymentHandler } from "./plugins/jarshop-checkout/index.js";
25
+
26
+ type Item<List> = List extends readonly (infer Value)[] ? Value : never;
27
+
28
+ export type JarShopPaymentMethodHandler = Item<
29
+ PaymentOptions["paymentMethodHandlers"]
30
+ >;
31
+ export type JarShopShippingEligibilityChecker = Item<
32
+ NonNullable<ShippingOptions["shippingEligibilityCheckers"]>
33
+ >;
34
+ export type JarShopShippingCalculator = Item<
35
+ NonNullable<ShippingOptions["shippingCalculators"]>
36
+ >;
37
+ export type JarShopPlugin = Item<NonNullable<VendureConfig["plugins"]>>;
38
+ /** A migration class, or a glob of compiled migration files. */
39
+ export type JarShopMigration = string | (new () => MigrationInterface);
40
+
41
+ /**
42
+ * The client-owned feature composition read from `src/client/features.ts`.
43
+ *
44
+ * Platform-managed `vendure-config.ts` builds the Vendure configuration from
45
+ * it, so a Client Project adds, replaces or switches off payment, shipping,
46
+ * invoicing and extra plugins without editing managed source. Everything that
47
+ * is not listed here — checkout, the order-email outbox, the shipping
48
+ * selection kit, assets, search, email and the Dashboard — is JarShop Core
49
+ * and always registered.
50
+ */
51
+ export interface JarShopFeatures {
52
+ /**
53
+ * Every payment method handler a PaymentMethod may use. The list is the
54
+ * whole set: a handler left out is not registered, and a PaymentMethod that
55
+ * still names it cannot take payments.
56
+ */
57
+ readonly paymentMethodHandlers: readonly JarShopPaymentMethodHandler[];
58
+ /**
59
+ * Every shipping eligibility checker and calculator a ShippingMethod may
60
+ * use, apart from Packeta's own, which `packeta` adds.
61
+ */
62
+ readonly shippingEligibilityCheckers: readonly JarShopShippingEligibilityChecker[];
63
+ readonly shippingCalculators: readonly JarShopShippingCalculator[];
64
+ /**
65
+ * Packeta pickup points for the markets that ship to a Packeta country.
66
+ * `JARSHOP_PACKETA_ENABLED=0` still switches it off for one environment.
67
+ */
68
+ readonly packeta: boolean;
69
+ /**
70
+ * Built-in Slovak invoicing, or `false` to leave the invoicing plugin, its
71
+ * migrations, invoice email delivery and the seeded template out. Switching
72
+ * it off never drops an existing invoice table or row.
73
+ */
74
+ readonly invoicing: JarShopInvoicingConfig | false;
75
+ /**
76
+ * Extra Vendure plugins, registered after JarShop's own. A plugin's
77
+ * `dashboard` extension is picked up by the Dashboard build with it.
78
+ */
79
+ readonly plugins?: readonly JarShopPlugin[];
80
+ /**
81
+ * Migrations of the extra plugins. They run only through `pnpm db:migrate`,
82
+ * never at startup.
83
+ */
84
+ readonly migrations?: readonly JarShopMigration[];
85
+ }
86
+
87
+ const referenceRedirectGateway = createReferenceRedirectPaymentAdapter();
88
+
89
+ /**
90
+ * The in-memory reference redirect gateway. It proves the redirect payment
91
+ * protocol end to end and never charges anyone; a real shop replaces it with
92
+ * a provider Feature such as Comgate.
93
+ */
94
+ export const referenceRedirectPaymentHandler =
95
+ createRedirectPaymentMethodHandler({
96
+ code: "reference-redirect",
97
+ description: "Reference redirect payment",
98
+ adapter: () => referenceRedirectGateway.adapter,
99
+ });
100
+
101
+ /** Whether Packeta is wanted by the features and not vetoed by the environment. */
102
+ export function isPacketaRequested(
103
+ features: Pick<JarShopFeatures, "packeta">,
104
+ environment: NodeJS.ProcessEnv = process.env,
105
+ ): boolean {
106
+ return features.packeta && environment.JARSHOP_PACKETA_ENABLED !== "0";
107
+ }
108
+
109
+ export {
110
+ assertUniqueOperationCodes,
111
+ duplicateOperationCodes,
112
+ } from "./operation-codes.js";
@@ -0,0 +1,27 @@
1
+ import { MigrationInterface, QueryRunner } from "typeorm";
2
+
3
+ /**
4
+ * Adds the internal `jarshopGuestSessionId` Order custom field. It ties a guest
5
+ * cart to the session that created it, so a session shared by several markets
6
+ * (several Channels) finds each market's cart again. The lookup index is
7
+ * partial: only guest carts carry a session id.
8
+ */
9
+ export class JarShopGuestOrderSession1788100000000 implements MigrationInterface {
10
+ name = "JarShopGuestOrderSession1788100000000";
11
+
12
+ public async up(queryRunner: QueryRunner): Promise<void> {
13
+ await queryRunner.query(
14
+ `ALTER TABLE "order" ADD "customFieldsJarshopguestsessionid" character varying(255)`,
15
+ );
16
+ await queryRunner.query(
17
+ `CREATE INDEX "IDX_jarshop_order_guest_session" ON "order" ("customFieldsJarshopguestsessionid") WHERE "customFieldsJarshopguestsessionid" IS NOT NULL`,
18
+ );
19
+ }
20
+
21
+ public async down(queryRunner: QueryRunner): Promise<void> {
22
+ await queryRunner.query(`DROP INDEX "IDX_jarshop_order_guest_session"`);
23
+ await queryRunner.query(
24
+ `ALTER TABLE "order" DROP COLUMN "customFieldsJarshopguestsessionid"`,
25
+ );
26
+ }
27
+ }
@@ -0,0 +1,34 @@
1
+ /** Problems for two operations of one kind that share a code. */
2
+ export function duplicateOperationCodes(
3
+ groups: Readonly<Record<string, readonly { code: string }[]>>,
4
+ ): string[] {
5
+ return Object.entries(groups).flatMap(([kind, operations]) => {
6
+ const seen = new Set<string>();
7
+ return operations.flatMap(({ code }) => {
8
+ if (!seen.has(code)) {
9
+ seen.add(code);
10
+ return [];
11
+ }
12
+ return [`${kind} code "${code}" is registered more than once`];
13
+ });
14
+ });
15
+ }
16
+
17
+ /**
18
+ * Rejects two operations of one kind that share a code. Vendure looks an
19
+ * operation up by its code, so the second one would silently shadow the first.
20
+ *
21
+ * `createVendureConfig` runs it on the lists `src/client/features.ts`
22
+ * declares; `JarShopOperationCodeCheck` runs it again at startup on Vendure's
23
+ * final configuration, which also holds the operations a plugin added in its
24
+ * own `configuration` hook.
25
+ */
26
+ export function assertUniqueOperationCodes(
27
+ groups: Readonly<Record<string, readonly { code: string }[]>>,
28
+ source = "Invalid JarShop features in src/client/features.ts",
29
+ ): void {
30
+ const problems = duplicateOperationCodes(groups);
31
+ if (problems.length > 0) {
32
+ throw new Error(`${source}:\n- ${problems.join("\n- ")}`);
33
+ }
34
+ }
@@ -0,0 +1,95 @@
1
+ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
2
+
3
+ import {
4
+ JarShopShippingSelectionPlugin,
5
+ jarShopKitMigrations,
6
+ jarShopShippingSelectionOrderProcess,
7
+ } from "@jarwizz/feature-adapter-kit/server";
8
+ import { JarShopPacketaPlugin } from "@jarwizz/feature-packeta/server";
9
+
10
+ import type { VendureConfig } from "@vendure/core";
11
+
12
+ let config: VendureConfig;
13
+ const originalAppEnvironment = process.env.APP_ENV;
14
+ const originalPacketaApiKey = process.env.PACKETA_API_KEY;
15
+ const originalPacketaEnabled = process.env.JARSHOP_PACKETA_ENABLED;
16
+ const originalFakePacketaValidation =
17
+ process.env.JARSHOP_FAKE_PACKETA_VALIDATION;
18
+
19
+ beforeAll(async () => {
20
+ process.env.APP_ENV = "test";
21
+ process.env.PACKETA_API_KEY = "0000000000000000";
22
+ ({ config } = await import("./vendure-config.js"));
23
+ });
24
+
25
+ afterAll(() => {
26
+ if (originalAppEnvironment === undefined) delete process.env.APP_ENV;
27
+ else process.env.APP_ENV = originalAppEnvironment;
28
+ if (originalPacketaApiKey === undefined) delete process.env.PACKETA_API_KEY;
29
+ else process.env.PACKETA_API_KEY = originalPacketaApiKey;
30
+ if (originalPacketaEnabled === undefined)
31
+ delete process.env.JARSHOP_PACKETA_ENABLED;
32
+ else process.env.JARSHOP_PACKETA_ENABLED = originalPacketaEnabled;
33
+ if (originalFakePacketaValidation === undefined)
34
+ delete process.env.JARSHOP_FAKE_PACKETA_VALIDATION;
35
+ else
36
+ process.env.JARSHOP_FAKE_PACKETA_VALIDATION = originalFakePacketaValidation;
37
+ });
38
+
39
+ describe("the generated Packeta server installation", () => {
40
+ it("registers Packeta and the selection boundary as one Vendure configuration", () => {
41
+ expect(config.plugins).toContain(JarShopPacketaPlugin);
42
+ expect(config.plugins).toContain(JarShopShippingSelectionPlugin);
43
+ expect(config.orderOptions?.process).toContain(
44
+ jarShopShippingSelectionOrderProcess,
45
+ );
46
+ expect(config.dbConnectionOptions.migrations).toEqual(
47
+ expect.arrayContaining([...jarShopKitMigrations]),
48
+ );
49
+ expect(
50
+ config.shippingOptions?.shippingEligibilityCheckers?.map(
51
+ (checker) => checker.code,
52
+ ),
53
+ ).toEqual(
54
+ expect.arrayContaining([
55
+ "default-shipping-eligibility-checker",
56
+ "packeta-eligibility",
57
+ ]),
58
+ );
59
+ expect(
60
+ config.shippingOptions?.shippingCalculators?.map(
61
+ (calculator) => calculator.code,
62
+ ),
63
+ ).toEqual(
64
+ expect.arrayContaining([
65
+ "jarshop-tariff-shipping-calculator",
66
+ "packeta-calculator",
67
+ ]),
68
+ );
69
+ });
70
+
71
+ it("can disable only the Packeta Feature while retaining the selection kit", async () => {
72
+ process.env.JARSHOP_PACKETA_ENABLED = "0";
73
+ process.env.APP_ENV = "production";
74
+ delete process.env.PACKETA_API_KEY;
75
+ process.env.JARSHOP_FAKE_PACKETA_VALIDATION = "1";
76
+ vi.resetModules();
77
+ const { config: disabled } = await import("./vendure-config.js");
78
+ const pluginNames = disabled.plugins?.map((plugin) =>
79
+ "module" in plugin ? plugin.module.name : plugin.name,
80
+ );
81
+
82
+ expect(pluginNames).not.toContain("JarShopPacketaPlugin");
83
+ expect(pluginNames).toContain("JarShopShippingSelectionPlugin");
84
+ expect(
85
+ disabled.shippingOptions?.shippingEligibilityCheckers?.map(
86
+ (checker) => checker.code,
87
+ ),
88
+ ).not.toContain("packeta-eligibility");
89
+ expect(
90
+ disabled.shippingOptions?.shippingCalculators?.map(
91
+ (calculator) => calculator.code,
92
+ ),
93
+ ).not.toContain("packeta-calculator");
94
+ });
95
+ });
@@ -0,0 +1,161 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+
3
+ import type { ShippingAdapter } from "@jarwizz/feature-adapter-kit";
4
+
5
+ import type { JarShopConfig, JarShopMarket } from "./jarshop-config.js";
6
+ import {
7
+ assertPacketaMarketsDistinguishable,
8
+ packetaCountriesForMarket,
9
+ packetaServedCountries,
10
+ scopePacketaToMarkets,
11
+ } from "./packeta-countries.js";
12
+
13
+ function market(
14
+ code: string,
15
+ currency: string,
16
+ countries: string[],
17
+ ): JarShopMarket {
18
+ return {
19
+ code,
20
+ channelToken: code,
21
+ defaultLanguage: "en",
22
+ languages: ["en"],
23
+ currency,
24
+ countries,
25
+ domains: [],
26
+ };
27
+ }
28
+
29
+ const multiMarket: JarShopConfig = {
30
+ defaultMarket: "sk",
31
+ markets: [
32
+ market("sk", "EUR", ["SK"]),
33
+ market("cz", "CZK", ["CZ"]),
34
+ market("hu", "HUF", ["HU"]),
35
+ ],
36
+ };
37
+
38
+ describe("Packeta countries of the configured markets", () => {
39
+ it("serves exactly the market countries Packeta has a network in", () => {
40
+ expect(
41
+ packetaCountriesForMarket(market("de", "EUR", ["DE", "AT"])),
42
+ ).toEqual([]);
43
+ expect(
44
+ packetaCountriesForMarket(market("ce", "EUR", ["AT", "SK", "CZ"])),
45
+ ).toEqual(["SK", "CZ"]);
46
+ });
47
+
48
+ it("lists each served country once across markets", () => {
49
+ expect(packetaServedCountries(multiMarket)).toEqual(["SK", "CZ", "HU"]);
50
+ expect(
51
+ packetaServedCountries({
52
+ defaultMarket: "a",
53
+ markets: [market("a", "EUR", ["SK"]), market("b", "EUR", ["SK", "AT"])],
54
+ }),
55
+ ).toEqual(["SK"]);
56
+ expect(
57
+ packetaServedCountries({
58
+ defaultMarket: "a",
59
+ markets: [market("a", "EUR", ["DE"])],
60
+ }),
61
+ ).toEqual([]);
62
+ });
63
+ });
64
+
65
+ describe("scoping the Packeta adapter to markets", () => {
66
+ function inner() {
67
+ const adapter = {
68
+ code: "packeta",
69
+ availability: vi.fn(async () => ({
70
+ ok: true as const,
71
+ value: { available: true },
72
+ })),
73
+ quote: vi.fn(async () => ({
74
+ ok: true as const,
75
+ value: { priceWithTax: 350 },
76
+ })),
77
+ validateSelection: vi.fn(async () => ({
78
+ ok: true as const,
79
+ value: {
80
+ selectionKey: "packeta:1",
81
+ snapshot: {
82
+ id: "1",
83
+ label: "x",
84
+ addressLines: [],
85
+ countryCode: "CZ",
86
+ },
87
+ },
88
+ })),
89
+ } satisfies ShippingAdapter;
90
+ return adapter;
91
+ }
92
+ const czk = { countryCode: "CZ", currencyCode: "CZK", subtotalWithTax: 1 };
93
+ const eurCz = { ...czk, currencyCode: "EUR" };
94
+
95
+ it("passes through an order whose country belongs to its market currency", async () => {
96
+ const adapter = scopePacketaToMarkets(inner(), multiMarket);
97
+
98
+ await expect(adapter.availability(czk)).resolves.toMatchObject({
99
+ value: { available: true },
100
+ });
101
+ await expect(adapter.quote(czk)).resolves.toMatchObject({ ok: true });
102
+ await expect(adapter.validateSelection(czk, {})).resolves.toMatchObject({
103
+ ok: true,
104
+ });
105
+ });
106
+
107
+ it("refuses a country served only by another market's Channel", async () => {
108
+ const wrapped = inner();
109
+ const adapter = scopePacketaToMarkets(wrapped, multiMarket);
110
+
111
+ await expect(adapter.availability(eurCz)).resolves.toEqual({
112
+ ok: true,
113
+ value: { available: false },
114
+ });
115
+ await expect(adapter.quote(eurCz)).resolves.toMatchObject({
116
+ ok: false,
117
+ error: { kind: "NOT_ELIGIBLE" },
118
+ });
119
+ await expect(adapter.validateSelection(eurCz, {})).resolves.toMatchObject({
120
+ ok: false,
121
+ error: { kind: "NOT_ELIGIBLE" },
122
+ });
123
+ expect(wrapped.validateSelection).not.toHaveBeenCalled();
124
+ });
125
+ });
126
+
127
+ describe("markets Packeta cannot tell apart", () => {
128
+ it("refuses two Packeta markets that share a currency at startup", () => {
129
+ const shared: JarShopConfig = {
130
+ defaultMarket: "sk",
131
+ markets: [
132
+ market("sk", "EUR", ["SK"]),
133
+ market("ro", "EUR", ["RO"]),
134
+ market("cz", "CZK", ["CZ"]),
135
+ ],
136
+ };
137
+ expect(() => assertPacketaMarketsDistinguishable(shared)).toThrow(
138
+ 'Packeta cannot tell apart markets that share a currency: "sk", "ro" (EUR)',
139
+ );
140
+ expect(() =>
141
+ scopePacketaToMarkets(
142
+ { code: "packeta" } as unknown as Parameters<
143
+ typeof scopePacketaToMarkets
144
+ >[0],
145
+ shared,
146
+ ),
147
+ ).toThrow("share a currency");
148
+ });
149
+
150
+ it("allows a shared currency when only one of the markets uses Packeta", () => {
151
+ expect(() =>
152
+ assertPacketaMarketsDistinguishable({
153
+ defaultMarket: "sk",
154
+ markets: [market("sk", "EUR", ["SK"]), market("at", "EUR", ["AT"])],
155
+ }),
156
+ ).not.toThrow();
157
+ expect(() =>
158
+ assertPacketaMarketsDistinguishable(multiMarket),
159
+ ).not.toThrow();
160
+ });
161
+ });
@@ -0,0 +1,120 @@
1
+ import type {
2
+ ShippingAdapter,
3
+ ShippingOrderContext,
4
+ } from "@jarwizz/feature-adapter-kit";
5
+
6
+ import type { JarShopConfig, JarShopMarket } from "./jarshop-config.js";
7
+
8
+ /**
9
+ * Destination countries with Packeta's own pickup-point and Z-BOX network,
10
+ * the only point type the Packeta Feature accepts. A market for any other
11
+ * country simply has no Packeta shipping method.
12
+ */
13
+ export const packetaNetworkCountries: readonly string[] = [
14
+ "CZ",
15
+ "HU",
16
+ "RO",
17
+ "SK",
18
+ ];
19
+
20
+ /** The countries of one market that Packeta serves, in the market's order. */
21
+ export function packetaCountriesForMarket(
22
+ market: JarShopMarket,
23
+ ): readonly string[] {
24
+ return market.countries.filter((country) =>
25
+ packetaNetworkCountries.includes(country),
26
+ );
27
+ }
28
+
29
+ /**
30
+ * The installation-wide served countries: every market's Packeta country,
31
+ * each listed once. Empty when no market ships through Packeta.
32
+ */
33
+ export function packetaServedCountries(config: JarShopConfig): string[] {
34
+ return [
35
+ ...new Set(
36
+ config.markets.flatMap((market) => packetaCountriesForMarket(market)),
37
+ ),
38
+ ];
39
+ }
40
+
41
+ /**
42
+ * The currency is the only market identity the shipping bridge passes to the
43
+ * adapter, so two markets that both ship through Packeta must not share one:
44
+ * an order in either Channel could otherwise choose the other market's points.
45
+ * Throws at startup with the markets and the fix instead.
46
+ */
47
+ export function assertPacketaMarketsDistinguishable(
48
+ config: JarShopConfig,
49
+ ): void {
50
+ const byCurrency = new Map<string, string[]>();
51
+ for (const market of config.markets) {
52
+ if (packetaCountriesForMarket(market).length === 0) continue;
53
+ byCurrency.set(market.currency, [
54
+ ...(byCurrency.get(market.currency) ?? []),
55
+ market.code,
56
+ ]);
57
+ }
58
+ const clashes = [...byCurrency].filter(([, codes]) => codes.length > 1);
59
+ if (clashes.length === 0) return;
60
+ throw new Error(
61
+ `Packeta cannot tell apart markets that share a currency: ${clashes
62
+ .map(
63
+ ([currency, codes]) =>
64
+ `${codes.map((code) => `"${code}"`).join(", ")} (${currency})`,
65
+ )
66
+ .join(
67
+ "; ",
68
+ )}. Packeta scopes pickup points by the order's currency and country, ` +
69
+ "so give each Packeta market its own currency, move the countries into one market, " +
70
+ "or set JARSHOP_PACKETA_ENABLED=0.",
71
+ );
72
+ }
73
+
74
+ /**
75
+ * Narrows the Packeta adapter to the markets' own country and currency pairs.
76
+ *
77
+ * The adapter knows only the installation-wide countries, and the shipping
78
+ * bridge hands it the order's country and currency but not its Channel. A
79
+ * market's currency identifies its Channel, so an order in the Slovak EUR
80
+ * Channel cannot choose a Czech pickup point just because another market
81
+ * ships to Czechia. Markets sharing a currency are refused up front.
82
+ */
83
+ export function scopePacketaToMarkets<
84
+ Adapter extends ShippingAdapter &
85
+ Required<Pick<ShippingAdapter, "validateSelection">>,
86
+ >(adapter: Adapter, config: JarShopConfig): Adapter {
87
+ assertPacketaMarketsDistinguishable(config);
88
+ const allowed = new Set(
89
+ config.markets.flatMap((market) =>
90
+ packetaCountriesForMarket(market).map(
91
+ (country) => `${market.currency}:${country}`,
92
+ ),
93
+ ),
94
+ );
95
+ const permitted = (context: ShippingOrderContext): boolean =>
96
+ allowed.has(
97
+ `${context.currencyCode.toUpperCase()}:${context.countryCode.toUpperCase()}`,
98
+ );
99
+ const refusal = {
100
+ ok: false as const,
101
+ error: {
102
+ kind: "NOT_ELIGIBLE" as const,
103
+ message: "Packeta is not offered to this market's destination country",
104
+ },
105
+ };
106
+
107
+ return {
108
+ ...adapter,
109
+ availability: (context) =>
110
+ permitted(context)
111
+ ? adapter.availability(context)
112
+ : Promise.resolve({ ok: true as const, value: { available: false } }),
113
+ quote: (context) =>
114
+ permitted(context) ? adapter.quote(context) : Promise.resolve(refusal),
115
+ validateSelection: (context, payload) =>
116
+ permitted(context)
117
+ ? adapter.validateSelection(context, payload)
118
+ : Promise.resolve(refusal),
119
+ };
120
+ }
@@ -0,0 +1,35 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+
3
+ import { createPacketaValidationFetch } from "./packeta-validation.js";
4
+
5
+ describe("the generated fake Packeta validation transport", () => {
6
+ it("is absent by default and forbidden outside development or test", () => {
7
+ expect(
8
+ createPacketaValidationFetch({ APP_ENV: "production" }),
9
+ ).toBeUndefined();
10
+ expect(() =>
11
+ createPacketaValidationFetch({
12
+ APP_ENV: "production",
13
+ JARSHOP_FAKE_PACKETA_VALIDATION: "1",
14
+ }),
15
+ ).toThrow("only in development or test");
16
+ });
17
+
18
+ it("answers the smoke point without reaching the network", async () => {
19
+ const fallback = vi.fn<typeof globalThis.fetch>();
20
+ const transport = createPacketaValidationFetch(
21
+ { APP_ENV: "test", JARSHOP_FAKE_PACKETA_VALIDATION: "1" },
22
+ fallback,
23
+ );
24
+ const response = await transport?.(
25
+ "https://widget.packeta.com/v6/pps/api/widget/v1/validate",
26
+ { body: JSON.stringify({ point: { id: "12345" } }), method: "POST" },
27
+ );
28
+
29
+ expect(response?.ok).toBe(true);
30
+ expect(await response?.json()).toMatchObject({
31
+ point: { name: "Z-BOX Bratislava Nivy", group: "zbox" },
32
+ });
33
+ expect(fallback).not.toHaveBeenCalled();
34
+ });
35
+ });
@@ -0,0 +1,52 @@
1
+ const validationUrl =
2
+ "https://widget.packeta.com/v6/pps/api/widget/v1/validate";
3
+
4
+ export function createPacketaValidationFetch(
5
+ environment: NodeJS.ProcessEnv,
6
+ fallback: typeof globalThis.fetch = globalThis.fetch,
7
+ ): typeof globalThis.fetch | undefined {
8
+ if (environment.JARSHOP_FAKE_PACKETA_VALIDATION !== "1") return undefined;
9
+ if (environment.APP_ENV !== "dev" && environment.APP_ENV !== "test") {
10
+ throw new Error(
11
+ "JARSHOP_FAKE_PACKETA_VALIDATION is allowed only in development or test",
12
+ );
13
+ }
14
+ return async (input, init) => {
15
+ const url =
16
+ typeof input === "string"
17
+ ? input
18
+ : input instanceof URL
19
+ ? input.href
20
+ : input.url;
21
+ if (url !== validationUrl) return fallback(input, init);
22
+ const body = JSON.parse(String(init?.body ?? "{}")) as {
23
+ point?: { id?: string };
24
+ };
25
+ if (body.point?.id === "88888") {
26
+ return new Response("unavailable", { status: 503 });
27
+ }
28
+ if (body.point?.id === "99999") {
29
+ return Response.json({
30
+ isValid: false,
31
+ errors: [{ code: "NotFound" }],
32
+ });
33
+ }
34
+ if (body.point?.id !== "12345") {
35
+ return new Response("invalid", { status: 400 });
36
+ }
37
+ return Response.json({
38
+ isValid: true,
39
+ point: {
40
+ name: "Z-BOX Bratislava Nivy",
41
+ address: {
42
+ street: "Mlynske nivy 5",
43
+ city: "Bratislava",
44
+ zip: "821 09",
45
+ country: "sk",
46
+ },
47
+ group: "zbox",
48
+ },
49
+ errors: [],
50
+ });
51
+ };
52
+ }