@jarwizz/create-jarshop 0.3.1 → 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.
package/dist/presets.d.ts CHANGED
@@ -12,6 +12,8 @@ export interface PresetMarket {
12
12
  readonly currency: string;
13
13
  readonly countries: readonly string[];
14
14
  readonly domains: readonly string[];
15
+ /** Standard VAT rate in percent for the demo seed; omitted keeps 0%. */
16
+ readonly vatRate?: number;
15
17
  }
16
18
  export interface PresetConfig {
17
19
  readonly defaultMarket: string;
package/dist/presets.js CHANGED
@@ -19,7 +19,7 @@ export const presetConfigs = {
19
19
  "multi-market": {
20
20
  defaultMarket: "sk",
21
21
  markets: [
22
- { ...slovakMarket, domains: ["sk.jarshop.test"] },
22
+ { ...slovakMarket, domains: ["sk.jarshop.test"], vatRate: 23 },
23
23
  {
24
24
  code: "cz",
25
25
  channelToken: "cz",
@@ -28,6 +28,7 @@ export const presetConfigs = {
28
28
  currency: "CZK",
29
29
  countries: ["CZ"],
30
30
  domains: ["cz.jarshop.test"],
31
+ vatRate: 21,
31
32
  },
32
33
  {
33
34
  code: "hu",
@@ -37,6 +38,7 @@ export const presetConfigs = {
37
38
  currency: "HUF",
38
39
  countries: ["HU"],
39
40
  domains: ["hu.jarshop.test"],
41
+ vatRate: 27,
40
42
  },
41
43
  ],
42
44
  },
@@ -63,6 +65,9 @@ export function renderJarShopConfig(preset) {
63
65
  ` currency: ${JSON.stringify(market.currency)},`,
64
66
  ` countries: ${stringArray(market.countries)},`,
65
67
  ` domains: ${stringArray(market.domains)},`,
68
+ ...(market.vatRate === undefined
69
+ ? []
70
+ : [` vatRate: ${market.vatRate},`]),
66
71
  " },",
67
72
  ].join("\n"))
68
73
  .join("\n");
@@ -80,6 +85,12 @@ export function renderJarShopConfig(preset) {
80
85
  * with several markets answers such a host with 404. The server and the
81
86
  * storefront validate this file when they start. Keep it plain data: it is
82
87
  * loaded without a build.
88
+ *
89
+ * An optional \`vatRate\` (percent, 0-100) per market gives that market's demo
90
+ * tax zone a standard VAT rate when \`pnpm db:seed\` runs; without it the demo
91
+ * seed keeps a 0% rate. With a \`vatRate\` the seed also makes that market's
92
+ * Channel price-inclusive, so a demo price stays the gross price.
93
+ * Production tax setup stays in the Dashboard.
83
94
  */
84
95
  const config = {
85
96
  defaultMarket: ${JSON.stringify(config.defaultMarket)},
@@ -1 +1 @@
1
- {"version":3,"file":"presets.js","sourceRoot":"","sources":["../src/presets.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,aAAa,EAAE,cAAc,CAAU,CAAC;AAmBpE,MAAM,YAAY,GAAiB;IACjC,IAAI,EAAE,IAAI;IACV,YAAY,EAAE,IAAI;IAClB,eAAe,EAAE,IAAI;IACrB,SAAS,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC;IACvB,QAAQ,EAAE,KAAK;IACf,SAAS,EAAE,CAAC,IAAI,CAAC;IACjB,OAAO,EAAE,EAAE;CACZ,CAAC;AAEF,MAAM,CAAC,MAAM,aAAa,GAA+C;IACvE,qEAAqE;IACrE,aAAa,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,YAAY,CAAC,EAAE;IAC/D,2DAA2D;IAC3D,cAAc,EAAE;QACd,aAAa,EAAE,IAAI;QACnB,OAAO,EAAE;YACP,EAAE,GAAG,YAAY,EAAE,OAAO,EAAE,CAAC,iBAAiB,CAAC,EAAE;YACjD;gBACE,IAAI,EAAE,IAAI;gBACV,YAAY,EAAE,IAAI;gBAClB,eAAe,EAAE,IAAI;gBACrB,SAAS,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC;gBACvB,QAAQ,EAAE,KAAK;gBACf,SAAS,EAAE,CAAC,IAAI,CAAC;gBACjB,OAAO,EAAE,CAAC,iBAAiB,CAAC;aAC7B;YACD;gBACE,IAAI,EAAE,IAAI;gBACV,YAAY,EAAE,IAAI;gBAClB,eAAe,EAAE,IA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,CAAC,CAAC;QAC1C,QAAQ;KACT,CAAC,IAAI,CAAC,IAAI,CAAC,CACb;SACA,IAAI,CAAC,IAAI,CAAC,CAAC;IACd,OAAO;;;8DAGqD,MAAM;;;;;;;;;;;;;;;;;;;mBAmBjD,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,aAAa,CAAC;;EAErD,OAAO;;;;;CAKR,CAAC;AACF,CAAC"}
@@ -12,6 +12,12 @@ import type { JarShopConfig } from "./src/jarshop-config.js";
12
12
  * with several markets answers such a host with 404. The server and the
13
13
  * storefront validate this file when they start. Keep it plain data: it is
14
14
  * loaded without a build.
15
+ *
16
+ * An optional `vatRate` (percent, 0-100) per market gives that market's demo
17
+ * tax zone a standard VAT rate when `pnpm db:seed` runs; without it the demo
18
+ * seed keeps a 0% rate. With a `vatRate` the seed also makes that market's
19
+ * Channel price-inclusive, so a demo price stays the gross price.
20
+ * Production tax setup stays in the Dashboard.
15
21
  */
16
22
  const config = {
17
23
  defaultMarket: "sk",
@@ -45,6 +45,36 @@ const czechia = {
45
45
  };
46
46
  const multiMarket = { defaultMarket: "sk", markets: [slovakia, czechia] };
47
47
 
48
+ describe("market vatRate", () => {
49
+ const withVat = (vatRate: unknown) => ({
50
+ defaultMarket: "sk",
51
+ markets: [{ ...slovakia, vatRate }],
52
+ });
53
+
54
+ it("is optional and omitted from a market that does not set it", () => {
55
+ expect(parseJarShopConfig(multiMarket).markets[0]).not.toHaveProperty(
56
+ "vatRate",
57
+ );
58
+ });
59
+
60
+ it.each([0, 5.5, 23, 100])("accepts %s percent", (vatRate) => {
61
+ expect(parseJarShopConfig(withVat(vatRate)).markets[0]?.vatRate).toBe(
62
+ vatRate,
63
+ );
64
+ });
65
+
66
+ it.each([-1, 100.5, Number.NaN, "23", null])(
67
+ "rejects %j with a readable error",
68
+ (vatRate) => {
69
+ expect(issuesOf(withVat(vatRate))).toEqual([
70
+ expect.stringContaining(
71
+ 'market "sk" vatRate must be a number from 0 to 100',
72
+ ),
73
+ ]);
74
+ },
75
+ );
76
+ });
77
+
48
78
  function issuesOf(value: unknown): readonly string[] {
49
79
  try {
50
80
  parseJarShopConfig(value);
@@ -32,6 +32,13 @@ export interface JarShopMarket {
32
32
  readonly countries: readonly JarShopCountryCode[];
33
33
  /** Host names, without scheme or port, that serve this market. */
34
34
  readonly domains: readonly string[];
35
+ /**
36
+ * Standard VAT rate in percent (0-100) the demo seed gives this market's tax
37
+ * zone, for example `23`. Optional: without it the seed keeps a 0% demo
38
+ * rate. It also makes the market's Channel `pricesIncludeTax`, so a demo
39
+ * price stays the gross price and only its tax part changes.
40
+ */
41
+ readonly vatRate?: number;
35
42
  }
36
43
 
37
44
  export interface JarShopConfig {
@@ -254,6 +261,19 @@ export function parseJarShopConfig(
254
261
  domainOwners.set(domain, marketLabel);
255
262
  }
256
263
 
264
+ const vatRate = candidate.vatRate;
265
+ if (
266
+ vatRate !== undefined &&
267
+ (typeof vatRate !== "number" ||
268
+ !Number.isFinite(vatRate) ||
269
+ vatRate < 0 ||
270
+ vatRate > 100)
271
+ ) {
272
+ issues.push(
273
+ `${marketLabel} vatRate must be a number from 0 to 100 percent (got ${JSON.stringify(vatRate)})`,
274
+ );
275
+ }
276
+
257
277
  markets.push(
258
278
  Object.freeze({
259
279
  code: String(code),
@@ -263,6 +283,9 @@ export function parseJarShopConfig(
263
283
  currency: String(currency),
264
284
  countries: Object.freeze([...countries]),
265
285
  domains: Object.freeze([...domains]),
286
+ ...(typeof vatRate === "number" && vatRate >= 0 && vatRate <= 100
287
+ ? { vatRate }
288
+ : {}),
266
289
  }),
267
290
  );
268
291
  });
@@ -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
+ }
@@ -97,3 +97,7 @@ export {
97
97
  registerJarShopOrderLifecycle,
98
98
  } from "./order-lifecycle-process.js";
99
99
  export { JarShopCheckoutPlugin } from "./jarshop-checkout.plugin.js";
100
+ export {
101
+ JarShopMarketActiveOrderStrategy,
102
+ registerJarShopMarketActiveOrder,
103
+ } from "./market-active-order.js";
@@ -54,6 +54,7 @@ import {
54
54
  isOrderAvailableInChannel,
55
55
  toOrderEmailDeliveryStatus,
56
56
  } from "./order-email-delivery-status.js";
57
+ import { registerJarShopMarketActiveOrder } from "./market-active-order.js";
57
58
  import { JarShopMarketChannelCheck } from "./market-channels.js";
58
59
  import { JarShopOperationCodeCheck } from "./operation-code-check.js";
59
60
  import { createPendingOrderEmailDelivery } from "./order-email-outbox.js";
@@ -1101,7 +1102,11 @@ function toLegalConfiguration(configuration: JarShopLegalConfiguration) {
1101
1102
  JarShopOrderEmailWorker,
1102
1103
  ],
1103
1104
  configuration: (config) =>
1104
- registerJarShopOrderEmailWorkerTask(registerJarShopOrderLifecycle(config)),
1105
+ registerJarShopMarketActiveOrder(
1106
+ registerJarShopOrderEmailWorkerTask(
1107
+ registerJarShopOrderLifecycle(config),
1108
+ ),
1109
+ ),
1105
1110
  entities: [
1106
1111
  CheckoutAttempt,
1107
1112
  JarShopConfirmationToken,
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Market-scoped active Order selection.
3
+ *
4
+ * One market is one Vendure Channel, and a client such as the mobile app sends
5
+ * ONE session token for every market (the local storefront does the same: all
6
+ * markets share one session cookie on `localhost`). Vendure's default strategy
7
+ * looks up `session.activeOrderId` in the current Channel and, for a guest that
8
+ * finds nothing, creates a new Order and overwrites `activeOrderId`. A guest
9
+ * who switches SK -> CZ -> SK would therefore lose the SK cart.
10
+ *
11
+ * This module keeps the decision free of Vendure runtime imports so it can be
12
+ * unit-tested: the storage access is injected as {@link MarketOrderStore}.
13
+ */
14
+
15
+ /** Name of the internal Order custom field that remembers a guest's session. */
16
+ export const GUEST_SESSION_FIELD = "jarshopGuestSessionId";
17
+
18
+ /** The part of an Order the selection needs. */
19
+ export interface MarketOrder {
20
+ readonly id: string | number;
21
+ readonly active: boolean;
22
+ }
23
+
24
+ /** The part of the RequestContext the selection needs. */
25
+ export interface MarketOrderContext {
26
+ readonly channelId: string | number;
27
+ readonly activeUserId?: string | number | undefined;
28
+ readonly session?:
29
+ | {
30
+ readonly id: string | number;
31
+ readonly activeOrderId?: string | number | undefined;
32
+ }
33
+ | undefined;
34
+ }
35
+
36
+ export interface MarketOrderStore<
37
+ Ctx extends MarketOrderContext,
38
+ Order extends MarketOrder,
39
+ > {
40
+ /** The Order with this id when it belongs to the context's Channel. */
41
+ findInChannel(ctx: Ctx, orderId: string | number): Promise<Order | undefined>;
42
+ /** Vendure's Channel-scoped lookup of a signed-in user's active Order. */
43
+ findActiveForUser(
44
+ ctx: Ctx,
45
+ userId: string | number,
46
+ ): Promise<Order | undefined>;
47
+ /**
48
+ * The most recently updated active Order of the context's Channel that was
49
+ * stamped with this guest session id.
50
+ */
51
+ findActiveForGuestSession(
52
+ ctx: Ctx,
53
+ sessionId: string,
54
+ ): Promise<Order | undefined>;
55
+ /** Detaches an inactive Order that is still referenced by the session. */
56
+ unsetSessionOrder(ctx: Ctx): Promise<void>;
57
+ create(ctx: Ctx, userId: string | number | undefined): Promise<Order>;
58
+ /** Stamps the guest session id on the Order custom field. */
59
+ stampGuestSession(ctx: Ctx, order: Order, sessionId: string): Promise<Order>;
60
+ }
61
+
62
+ export function guestSessionKey(ctx: MarketOrderContext): string | undefined {
63
+ const id = ctx.session?.id;
64
+ return id === undefined || id === null || id === "" ? undefined : String(id);
65
+ }
66
+
67
+ export async function determineMarketActiveOrder<
68
+ Ctx extends MarketOrderContext,
69
+ Order extends MarketOrder,
70
+ >(store: MarketOrderStore<Ctx, Order>, ctx: Ctx): Promise<Order | undefined> {
71
+ if (!ctx.session) {
72
+ throw new Error("A market-scoped active Order needs a session");
73
+ }
74
+ if (
75
+ ctx.session.activeOrderId !== undefined &&
76
+ ctx.session.activeOrderId !== null
77
+ ) {
78
+ const current = await store.findInChannel(ctx, ctx.session.activeOrderId);
79
+ if (current?.active === false) {
80
+ // An inactive Order that the interrupted regular process left on the
81
+ // session; Vendure's default strategy detaches it the same way.
82
+ await store.unsetSessionOrder(ctx);
83
+ } else if (current) {
84
+ return current;
85
+ }
86
+ }
87
+ if (ctx.activeUserId !== undefined && ctx.activeUserId !== null) {
88
+ return store.findActiveForUser(ctx, ctx.activeUserId);
89
+ }
90
+ const sessionKey = guestSessionKey(ctx);
91
+ return sessionKey
92
+ ? store.findActiveForGuestSession(ctx, sessionKey)
93
+ : undefined;
94
+ }
95
+
96
+ export async function createMarketActiveOrder<
97
+ Ctx extends MarketOrderContext,
98
+ Order extends MarketOrder,
99
+ >(store: MarketOrderStore<Ctx, Order>, ctx: Ctx): Promise<Order> {
100
+ const hasUser = ctx.activeUserId !== undefined && ctx.activeUserId !== null;
101
+ const order = await store.create(ctx, hasUser ? ctx.activeUserId : undefined);
102
+ const sessionKey = guestSessionKey(ctx);
103
+ // A signed-in user's carts are found through their Customer, so only a guest
104
+ // Order needs the session stamp.
105
+ return hasUser || !sessionKey
106
+ ? order
107
+ : store.stampGuestSession(ctx, order, sessionKey);
108
+ }
@@ -0,0 +1,205 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import {
4
+ createMarketActiveOrder,
5
+ determineMarketActiveOrder,
6
+ type MarketOrder,
7
+ type MarketOrderContext,
8
+ type MarketOrderStore,
9
+ } from "./market-active-order-core.js";
10
+
11
+ interface FakeOrder extends MarketOrder {
12
+ active: boolean;
13
+ channelId: string;
14
+ userId?: string;
15
+ guestSessionId?: string;
16
+ updatedAt: number;
17
+ }
18
+ interface FakeContext extends MarketOrderContext {
19
+ session: { id: string; activeOrderId?: string | undefined };
20
+ }
21
+
22
+ /** Mimics Vendure: orders live in one Channel, the session may point at any. */
23
+ function fakeShop() {
24
+ const orders: FakeOrder[] = [];
25
+ let sequence = 0;
26
+ let clock = 0;
27
+ const store: MarketOrderStore<FakeContext, FakeOrder> = {
28
+ findInChannel: async (ctx, id) =>
29
+ orders.find((o) => o.id === id && o.channelId === String(ctx.channelId)),
30
+ findActiveForUser: async (ctx, userId) =>
31
+ orders.find(
32
+ (o) =>
33
+ o.active &&
34
+ o.userId === String(userId) &&
35
+ o.channelId === String(ctx.channelId),
36
+ ),
37
+ findActiveForGuestSession: async (ctx, sessionId) =>
38
+ orders
39
+ .filter(
40
+ (o) =>
41
+ o.active &&
42
+ o.channelId === String(ctx.channelId) &&
43
+ o.guestSessionId === sessionId,
44
+ )
45
+ .sort((a, b) => b.updatedAt - a.updatedAt)[0],
46
+ unsetSessionOrder: async (ctx) => {
47
+ ctx.session.activeOrderId = undefined;
48
+ },
49
+ create: async (ctx, userId) => {
50
+ const order: FakeOrder = {
51
+ id: `order-${++sequence}`,
52
+ active: true,
53
+ channelId: String(ctx.channelId),
54
+ updatedAt: ++clock,
55
+ ...(userId === undefined ? {} : { userId: String(userId) }),
56
+ };
57
+ orders.push(order);
58
+ return order;
59
+ },
60
+ stampGuestSession: async (_ctx, order, sessionId) => {
61
+ order.guestSessionId = sessionId;
62
+ return order;
63
+ },
64
+ };
65
+ /** Vendure's ActiveOrderService stores the strategy's result on the session. */
66
+ async function getActiveOrder(ctx: FakeContext, createIfNotExists: boolean) {
67
+ let order = await determineMarketActiveOrder(store, ctx);
68
+ if (!order && createIfNotExists)
69
+ order = await createMarketActiveOrder(store, ctx);
70
+ if (order) ctx.session.activeOrderId = String(order.id);
71
+ return order;
72
+ }
73
+ const context = (
74
+ channelId: string,
75
+ session: FakeContext["session"],
76
+ activeUserId?: string,
77
+ ): FakeContext => ({ channelId, session, activeUserId });
78
+ return { orders, store, getActiveOrder, context };
79
+ }
80
+
81
+ describe("market-scoped active Order", () => {
82
+ it("reuses the session's cart inside one market", async () => {
83
+ const shop = fakeShop();
84
+ const session = { id: "s1" };
85
+ const first = await shop.getActiveOrder(shop.context("sk", session), true);
86
+ const again = await shop.getActiveOrder(shop.context("sk", session), true);
87
+ expect(again?.id).toBe(first?.id);
88
+ expect(shop.orders).toHaveLength(1);
89
+ });
90
+
91
+ it("returns the original guest cart after SK -> CZ -> SK on one session", async () => {
92
+ const shop = fakeShop();
93
+ const session = { id: "s1" };
94
+ const sk = await shop.getActiveOrder(shop.context("sk", session), true);
95
+ const cz = await shop.getActiveOrder(shop.context("cz", session), true);
96
+ expect(cz?.id).not.toBe(sk?.id);
97
+ const backInSk = await shop.getActiveOrder(
98
+ shop.context("sk", session),
99
+ true,
100
+ );
101
+ expect(backInSk?.id).toBe(sk?.id);
102
+ const backInCz = await shop.getActiveOrder(
103
+ shop.context("cz", session),
104
+ true,
105
+ );
106
+ expect(backInCz?.id).toBe(cz?.id);
107
+ expect(shop.orders).toHaveLength(2);
108
+ });
109
+
110
+ it("does not show a guest cart to another session", async () => {
111
+ const shop = fakeShop();
112
+ const owner = await shop.getActiveOrder(
113
+ shop.context("sk", { id: "s1" }),
114
+ true,
115
+ );
116
+ const other = await shop.getActiveOrder(
117
+ shop.context("sk", { id: "s2" }),
118
+ false,
119
+ );
120
+ expect(other).toBeUndefined();
121
+ const stranger = await shop.getActiveOrder(
122
+ shop.context("sk", { id: "s2" }),
123
+ true,
124
+ );
125
+ expect(stranger?.id).not.toBe(owner?.id);
126
+ });
127
+
128
+ it("ignores inactive guest carts and detaches a stale session order", async () => {
129
+ const shop = fakeShop();
130
+ const session: FakeContext["session"] = { id: "s1" };
131
+ const placed = await shop.getActiveOrder(shop.context("sk", session), true);
132
+ placed!.active = false;
133
+ const ctx = shop.context("sk", session);
134
+ expect(await determineMarketActiveOrder(shop.store, ctx)).toBeUndefined();
135
+ expect(ctx.session.activeOrderId).toBeUndefined();
136
+ });
137
+
138
+ it("prefers the most recently updated guest cart", async () => {
139
+ const shop = fakeShop();
140
+ const older = await shop.getActiveOrder(
141
+ shop.context("sk", { id: "s1" }),
142
+ true,
143
+ );
144
+ const newer = await shop.getActiveOrder(
145
+ shop.context("sk", { id: "s1" }),
146
+ true,
147
+ );
148
+ expect(newer?.id).toBe(older?.id);
149
+ // A second stamped cart (e.g. created by a concurrent request) wins by recency.
150
+ const extra = await createMarketActiveOrder(
151
+ shop.store,
152
+ shop.context("sk", { id: "s1" }),
153
+ );
154
+ const found = await determineMarketActiveOrder(
155
+ shop.store,
156
+ shop.context("sk", { id: "s1" }),
157
+ );
158
+ expect(found?.id).toBe(extra.id);
159
+ });
160
+
161
+ it("finds a signed-in user's cart per market without the guest stamp", async () => {
162
+ const shop = fakeShop();
163
+ const session = { id: "s1" };
164
+ const sk = await shop.getActiveOrder(
165
+ shop.context("sk", session, "u1"),
166
+ true,
167
+ );
168
+ const cz = await shop.getActiveOrder(
169
+ shop.context("cz", session, "u1"),
170
+ true,
171
+ );
172
+ expect(cz?.id).not.toBe(sk?.id);
173
+ expect(
174
+ (await shop.getActiveOrder(shop.context("sk", session, "u1"), true))?.id,
175
+ ).toBe(sk?.id);
176
+ });
177
+
178
+ it("stamps the session id on guest carts only", async () => {
179
+ const shop = fakeShop();
180
+ const guest = await shop.getActiveOrder(
181
+ shop.context("sk", { id: "s1" }),
182
+ true,
183
+ );
184
+ const user = await shop.getActiveOrder(
185
+ shop.context("sk", { id: "s2" }, "u1"),
186
+ true,
187
+ );
188
+ expect(shop.orders.find((o) => o.id === guest?.id)?.guestSessionId).toBe(
189
+ "s1",
190
+ );
191
+ expect(
192
+ shop.orders.find((o) => o.id === user?.id)?.guestSessionId,
193
+ ).toBeUndefined();
194
+ expect(shop.orders.find((o) => o.id === user?.id)?.userId).toBe("u1");
195
+ });
196
+
197
+ it("requires a session", async () => {
198
+ const shop = fakeShop();
199
+ await expect(
200
+ determineMarketActiveOrder(shop.store, {
201
+ channelId: "sk",
202
+ } as FakeContext),
203
+ ).rejects.toThrow("session");
204
+ });
205
+ });
@@ -0,0 +1,186 @@
1
+ import {
2
+ type ActiveOrderStrategy,
3
+ DefaultActiveOrderStrategy,
4
+ type CustomFieldConfig,
5
+ CustomerService,
6
+ type Injector,
7
+ Order,
8
+ OrderService,
9
+ type RequestContext,
10
+ SessionService,
11
+ TransactionalConnection,
12
+ type VendureConfig,
13
+ } from "@vendure/core";
14
+ import { DEFAULT_CHANNEL_CODE } from "@vendure/common/lib/shared-constants";
15
+ import { Index, type SelectQueryBuilder } from "typeorm";
16
+
17
+ import {
18
+ GUEST_SESSION_FIELD,
19
+ createMarketActiveOrder,
20
+ determineMarketActiveOrder,
21
+ type MarketOrderStore,
22
+ } from "./market-active-order-core.js";
23
+
24
+ /**
25
+ * Internal Order custom field. `internal` keeps it out of both GraphQL APIs;
26
+ * it only ties a guest cart to the session that created it. The matching
27
+ * column and index are created by the `JarShopGuestOrderSession` migration.
28
+ */
29
+ export const guestSessionCustomField: CustomFieldConfig = {
30
+ name: GUEST_SESSION_FIELD,
31
+ type: "string",
32
+ nullable: true,
33
+ internal: true,
34
+ readonly: true,
35
+ public: false,
36
+ };
37
+
38
+ /**
39
+ * Keeps one cart per market on a session that is used across markets: guest
40
+ * carts through the session stamp, signed-in carts through the Customer, both
41
+ * limited to Orders that belong to the request's market.
42
+ */
43
+ export class JarShopMarketActiveOrderStrategy implements ActiveOrderStrategy {
44
+ readonly name = "jarshop-market-active-order";
45
+
46
+ private connection!: TransactionalConnection;
47
+ private orderService!: OrderService;
48
+ private customerService!: CustomerService;
49
+ private sessionService!: SessionService;
50
+ /**
51
+ * Orders of the context's market. Vendure also assigns every Order to the
52
+ * default Channel, so a market's cart is visible in the default market's
53
+ * Channel too; an Order that belongs to another market's Channel is not a
54
+ * cart of this one.
55
+ */
56
+ private marketOrders(ctx: RequestContext): SelectQueryBuilder<Order> {
57
+ return this.connection
58
+ .getRepository(ctx, Order)
59
+ .createQueryBuilder("order")
60
+ .innerJoin("order.channels", "channel", "channel.id = :channelId", {
61
+ channelId: ctx.channelId,
62
+ })
63
+ .andWhere(
64
+ `NOT EXISTS (
65
+ SELECT 1 FROM "order_channels_channel" "other_link"
66
+ INNER JOIN "channel" "other_channel"
67
+ ON "other_channel"."id" = "other_link"."channelId"
68
+ WHERE "other_link"."orderId" = "order"."id"
69
+ AND "other_link"."channelId" <> :channelId
70
+ AND "other_channel"."code" <> :defaultChannelCode
71
+ )`,
72
+ { channelId: ctx.channelId, defaultChannelCode: DEFAULT_CHANNEL_CODE },
73
+ );
74
+ }
75
+
76
+ private readonly store: MarketOrderStore<RequestContext, Order> = {
77
+ findInChannel: (ctx, orderId) =>
78
+ this.marketOrders(ctx)
79
+ .andWhere("order.id = :orderId", { orderId })
80
+ .getOne()
81
+ .then((order) => order ?? undefined),
82
+ findActiveForUser: async (ctx, userId) => {
83
+ const customer = await this.customerService.findOneByUserId(ctx, userId);
84
+ if (!customer) return undefined;
85
+ const match = await this.marketOrders(ctx)
86
+ .andWhere("order.active = :active", { active: true })
87
+ .andWhere("order.customerId = :customerId", {
88
+ customerId: customer.id,
89
+ })
90
+ .orderBy("order.createdAt", "DESC")
91
+ .getOne();
92
+ return match ? this.orderService.findOne(ctx, match.id) : undefined;
93
+ },
94
+ findActiveForGuestSession: async (ctx, sessionId) => {
95
+ const match = await this.marketOrders(ctx)
96
+ .andWhere("order.active = :active", { active: true })
97
+ .andWhere(`order.customFields.${GUEST_SESSION_FIELD} = :sessionId`, {
98
+ sessionId,
99
+ })
100
+ .orderBy("order.updatedAt", "DESC")
101
+ .getOne();
102
+ return match ? this.orderService.findOne(ctx, match.id) : undefined;
103
+ },
104
+ unsetSessionOrder: async (ctx) => {
105
+ if (ctx.session)
106
+ await this.sessionService.unsetActiveOrder(ctx, ctx.session);
107
+ },
108
+ create: (ctx, userId) => this.orderService.create(ctx, userId),
109
+ stampGuestSession: async (ctx, order, sessionId) => {
110
+ await this.connection
111
+ .getRepository(ctx, Order)
112
+ .createQueryBuilder()
113
+ .update(Order)
114
+ .set({ customFields: { [GUEST_SESSION_FIELD]: sessionId } })
115
+ .where("id = :id", { id: order.id })
116
+ .execute();
117
+ return order;
118
+ },
119
+ };
120
+
121
+ init(injector: Injector): void {
122
+ this.connection = injector.get(TransactionalConnection);
123
+ this.orderService = injector.get(OrderService);
124
+ this.customerService = injector.get(CustomerService);
125
+ // Vendure's own `getActiveOrderForUser` is also what sign-in uses to pick
126
+ // the Order a guest cart merges into. In the default Channel it would pick
127
+ // the newest cart of ANY market and merge the guest cart into it, mixing
128
+ // currencies. Scope it to the context's market like the strategy above.
129
+ this.orderService.getActiveOrderForUser = (ctx, userId) =>
130
+ this.store.findActiveForUser(ctx, userId);
131
+ this.sessionService = injector.get(SessionService);
132
+ }
133
+
134
+ determineActiveOrder(ctx: RequestContext): Promise<Order | undefined> {
135
+ return determineMarketActiveOrder(this.store, ctx);
136
+ }
137
+
138
+ createActiveOrder(ctx: RequestContext): Promise<Order> {
139
+ return createMarketActiveOrder(this.store, ctx);
140
+ }
141
+ }
142
+
143
+ const GUEST_SESSION_INDEX = "IDX_jarshop_order_guest_session";
144
+ let guestSessionIndexDeclared = false;
145
+
146
+ /**
147
+ * Vendure only supports a unique index on a custom field. The guest lookup
148
+ * runs for every anonymous cart request, so declare a partial index on the
149
+ * Order entity metadata; the migration creates the same index, which keeps
150
+ * TypeORM's schema comparison (and Vendure's migration warning) clean.
151
+ */
152
+ function declareGuestSessionIndex(): void {
153
+ if (guestSessionIndexDeclared) return;
154
+ guestSessionIndexDeclared = true;
155
+ Index(GUEST_SESSION_INDEX, [`customFields.${GUEST_SESSION_FIELD}`], {
156
+ where: `"customFieldsJarshopguestsessionid" IS NOT NULL`,
157
+ })(Order);
158
+ }
159
+
160
+ /** Registers the Order custom field and replaces the default strategy. */
161
+ export function registerJarShopMarketActiveOrder<Config extends VendureConfig>(
162
+ config: Config,
163
+ ): Config {
164
+ declareGuestSessionIndex();
165
+ config.customFields ??= {};
166
+ const orderFields = (config.customFields.Order ??= []);
167
+ if (!orderFields.some((field) => field.name === GUEST_SESSION_FIELD)) {
168
+ orderFields.push(guestSessionCustomField);
169
+ }
170
+ config.orderOptions ??= {};
171
+ const current = config.orderOptions.activeOrderStrategy;
172
+ const strategies = (
173
+ Array.isArray(current) ? current : current ? [current] : []
174
+ )
175
+ // The default strategy is session-only and would shadow this one.
176
+ .filter((strategy) => !(strategy instanceof DefaultActiveOrderStrategy));
177
+ if (
178
+ !strategies.some(
179
+ (strategy) => strategy instanceof JarShopMarketActiveOrderStrategy,
180
+ )
181
+ ) {
182
+ strategies.push(new JarShopMarketActiveOrderStrategy());
183
+ }
184
+ config.orderOptions.activeOrderStrategy = strategies;
185
+ return config;
186
+ }
@@ -71,6 +71,23 @@ function demoTranslations<T extends object>(
71
71
  }));
72
72
  }
73
73
 
74
+ const zeroTaxRateName = "JarShop demo zero tax";
75
+ const standardVatRateNamePattern = /^Standard VAT \d+(?:\.\d+)?%$/u;
76
+
77
+ /** The demo rate for a market: its standard VAT, or 0% when none is set. */
78
+ function demoTaxRate(vatRate: number | undefined): {
79
+ readonly name: string;
80
+ readonly value: number;
81
+ } {
82
+ return vatRate === undefined
83
+ ? { name: zeroTaxRateName, value: 0 }
84
+ : { name: `Standard VAT ${vatRate}%`, value: vatRate };
85
+ }
86
+
87
+ function isSeededTaxRateName(name: string): boolean {
88
+ return name === zeroTaxRateName || standardVatRateNamePattern.test(name);
89
+ }
90
+
74
91
  function countryName(countryCode: string, languageCode: string): string {
75
92
  return (
76
93
  new Intl.DisplayNames([languageCode], { type: "region" }).of(countryCode) ??
@@ -177,10 +194,15 @@ async function seed(): Promise<void> {
177
194
  languageCode as LanguageCode,
178
195
  ),
179
196
  );
197
+ // EU consumer prices are gross: a market with a VAT rate keeps its demo
198
+ // prices tax-inclusive. Markets without `vatRate` keep today's behaviour.
199
+ const pricesIncludeTaxMissing =
200
+ primaryMarket.vatRate !== undefined && !channel.pricesIncludeTax;
180
201
  if (
181
202
  !channel.defaultTaxZone ||
182
203
  channel.defaultCurrencyCode !== primaryCurrency ||
183
- channelLanguagesMissing
204
+ channelLanguagesMissing ||
205
+ pricesIncludeTaxMissing
184
206
  ) {
185
207
  await channelService.update(ctx, {
186
208
  id: channel.id,
@@ -189,6 +211,9 @@ async function seed(): Promise<void> {
189
211
  availableCurrencyCodes: [primaryCurrency],
190
212
  defaultLanguageCode: primaryLanguage,
191
213
  availableLanguageCodes: primaryMarket.languages as LanguageCode[],
214
+ ...(primaryMarket.vatRate !== undefined
215
+ ? { pricesIncludeTax: true }
216
+ : {}),
192
217
  });
193
218
  channel = await channelService.getDefaultChannel(ctx);
194
219
  ctx = await requestContextService.create({
@@ -226,7 +251,8 @@ async function seed(): Promise<void> {
226
251
  availableCurrencyCodes: [market.currency as CurrencyCode],
227
252
  defaultTaxZoneId: zone.id,
228
253
  defaultShippingZoneId: zone.id,
229
- pricesIncludeTax: channel.pricesIncludeTax,
254
+ pricesIncludeTax:
255
+ market.vatRate !== undefined ? true : channel.pricesIncludeTax,
230
256
  ...(channel.sellerId ? { sellerId: channel.sellerId } : {}),
231
257
  };
232
258
  const saved = existingChannel
@@ -476,20 +502,39 @@ async function seed(): Promise<void> {
476
502
  taxCategories.items[0] ??
477
503
  (await taxCategoryService.create(ctx, { name: "JarShop demo tax" }));
478
504
  const taxRates = await taxRateService.findAll(ctx);
479
- for (const zone of [taxZone, ...marketChannels.map((item) => item.zone)]) {
480
- if (
481
- !taxRates.items.some(
482
- (rate) =>
483
- rate.zoneId === zone.id && rate.categoryId === taxCategory.id,
484
- )
485
- ) {
505
+ // A market with a configured `vatRate` gets a named standard-VAT rate; one
506
+ // without keeps the 0% demo rate. Only rates this seed named are updated,
507
+ // so a rate a client edited in the Dashboard is never overwritten.
508
+ for (const { zone, market } of [
509
+ { zone: taxZone, market: primaryMarket },
510
+ ...marketChannels,
511
+ ]) {
512
+ const existingRate = taxRates.items.find(
513
+ (rate) => rate.zoneId === zone.id && rate.categoryId === taxCategory.id,
514
+ );
515
+ const desired = demoTaxRate(market.vatRate);
516
+ if (!existingRate) {
486
517
  await taxRateService.create(ctx, {
487
518
  zoneId: zone.id,
488
519
  categoryId: taxCategory.id,
489
- name: "JarShop demo zero tax",
490
- value: 0,
520
+ name: desired.name,
521
+ value: desired.value,
491
522
  enabled: true,
492
523
  });
524
+ } else if (
525
+ market.vatRate !== undefined &&
526
+ isSeededTaxRateName(existingRate.name) &&
527
+ (existingRate.value !== desired.value ||
528
+ existingRate.name !== desired.name)
529
+ ) {
530
+ await taxRateService.update(ctx, {
531
+ id: existingRate.id,
532
+ name: desired.name,
533
+ value: desired.value,
534
+ });
535
+ console.log(
536
+ `Updated ${market.code} tax rate to ${desired.name} (was ${existingRate.name})`,
537
+ );
493
538
  }
494
539
  }
495
540
  const product =
@@ -1,3 +1,3 @@
1
1
  {
2
- "digest": "sha256:031c00bda4ee42e3c9fb7cfeb606261018edd8ca1b7017550fbacbd3fabef6ea"
2
+ "digest": "sha256:f8498a82131b82168696ff78ae285d39514e9cd98849a429371b34305451a6f4"
3
3
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jarwizz/create-jarshop",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "private": false,
5
5
  "description": "Generate an independent JarShop Client Project.",
6
6
  "license": "MIT",