@myparcel-dev/pdk-admin 2.3.0 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/actions/composables/mutations/orders/useExportOrdersMutation.d.ts +1 -1
  3. package/dist/composables/language/useLanguage.d.ts +6 -0
  4. package/dist/pdk/PdkAdmin.d.ts +26 -2
  5. package/dist/pdk/boot.d.ts +5 -0
  6. package/dist/sdk/index.d.ts +1 -0
  7. package/dist/sdk/requestHeaders.d.ts +10 -0
  8. package/dist/services/mutations/getModalMutationOptions.d.ts +7 -1
  9. package/dist/services/mutations/index.d.ts +1 -0
  10. package/dist/services/mutations/modalMutationToken.d.ts +16 -0
  11. package/dist/stores/useModalStore.d.ts +9 -1
  12. package/dist/types/admin.types.d.ts +10 -0
  13. package/dist/types/configuration.types.d.ts +12 -0
  14. package/package.json +2 -2
  15. package/src/actions/composables/mutations/orders/useExportOrdersMutation.spec.ts +75 -0
  16. package/src/actions/composables/mutations/orders/useExportOrdersMutation.ts +17 -6
  17. package/src/components/common/TabNavigation.spec.ts +78 -0
  18. package/src/components/common/TabNavigation.vue +7 -5
  19. package/src/composables/language/resetLanguageCache.spec.ts +24 -0
  20. package/src/composables/language/useLanguage.ts +13 -0
  21. package/src/forms/helpers/useFormCapabilities.spec.ts +15 -9
  22. package/src/forms/helpers/useFormCapabilities.ts +27 -13
  23. package/src/pdk/PdkAdmin.spec.ts +97 -0
  24. package/src/pdk/PdkAdmin.ts +63 -7
  25. package/src/pdk/boot.ts +13 -3
  26. package/src/pdk/createPdkAdmin.spec.ts +75 -0
  27. package/src/pdk/createPdkAdmin.ts +2 -0
  28. package/src/pdk/instance/plugins/createStorePlugin.spec.ts +44 -0
  29. package/src/pdk/instance/plugins/createStorePlugin.ts +12 -7
  30. package/src/pdk/instance/plugins/createVueQueryPlugin.spec.ts +29 -0
  31. package/src/pdk/instance/plugins/createVueQueryPlugin.ts +7 -7
  32. package/src/pdk/setupAdminApp.ts +3 -0
  33. package/src/sdk/composables/usePdkAdminApi.ts +3 -0
  34. package/src/sdk/index.ts +1 -0
  35. package/src/sdk/requestHeaders.spec.ts +54 -0
  36. package/src/sdk/requestHeaders.ts +36 -0
  37. package/src/services/mutations/getModalMutationOptions.spec.ts +59 -0
  38. package/src/services/mutations/getModalMutationOptions.ts +23 -15
  39. package/src/services/mutations/index.ts +1 -0
  40. package/src/services/mutations/modalMutationToken.ts +27 -0
  41. package/src/stores/useModalStore.spec.ts +33 -0
  42. package/src/stores/useModalStore.ts +13 -1
  43. package/src/types/admin.types.ts +12 -0
  44. package/src/types/configuration.types.ts +14 -0
package/CHANGELOG.md CHANGED
@@ -2,6 +2,28 @@
2
2
 
3
3
  <!-- MONOWEAVE:BELOW -->
4
4
 
5
+ ## [2.4.1](https://github.com/myparcelnl/js-pdk/compare/@myparcel-dev/pdk-admin@2.4.0...@myparcel-dev/pdk-admin@2.4.1) "@myparcel-dev/pdk-admin" (2026-11-06)
6
+
7
+
8
+ ### Bug Fixes
9
+
10
+ * **admin:** offer the €100 insurance tier in the shipment options form ([#520](https://github.com/myparcelnl/js-pdk/issues/520)) ([498b0db](https://github.com/myparcelnl/js-pdk/commit/498b0db6087bb0836c89c328be5cc1550ade35ff)), closes [myparcelnl/prestashop#269](https://github.com/myparcelnl/prestashop/issues/269) [myparcelnl/prestashop#238](https://github.com/myparcelnl/prestashop/issues/238)
11
+
12
+
13
+
14
+
15
+ ## [2.4.0](https://github.com/myparcelnl/js-pdk/compare/@myparcel-dev/pdk-admin@2.3.0...@myparcel-dev/pdk-admin@2.4.0) "@myparcel-dev/pdk-admin" (2026-10-22)
16
+
17
+
18
+ ### Features
19
+
20
+ * **admin:** allow dynamic request headers ([#499](https://github.com/myparcelnl/js-pdk/issues/499)) ([35c3b02](https://github.com/myparcelnl/js-pdk/commit/35c3b02f7307043e5c6a7a3fa8cae545703b067c))
21
+ * **admin:** allow turning off the tab hash ([#502](https://github.com/myparcelnl/js-pdk/issues/502)) ([f1bb842](https://github.com/myparcelnl/js-pdk/commit/f1bb8424b155958cf2d7cc1541758142b94eb8a0))
22
+ * **admin:** support remounting the admin in a single-page app ([#501](https://github.com/myparcelnl/js-pdk/issues/501)) ([9912af5](https://github.com/myparcelnl/js-pdk/commit/9912af591f2e72ef128d5bd5f7a5cc4389ab13d8))
23
+
24
+
25
+
26
+
5
27
  ## [2.3.0](https://github.com/myparcelnl/js-pdk/compare/@myparcel-dev/pdk-admin@2.2.7...@myparcel-dev/pdk-admin@2.3.0) "@myparcel-dev/pdk-admin" (2026-10-15)
6
28
 
7
29
 
@@ -1,5 +1,5 @@
1
- import { BackendEndpoint } from '@myparcel-dev/pdk-common';
2
1
  import { type OneOrMore } from '@myparcel-dev/ts-utils';
2
+ import { BackendEndpoint } from '@myparcel-dev/pdk-common';
3
3
  import { type ResolvedQuery } from '../../../../stores';
4
4
  import { MutationMode } from '../../../../services';
5
5
  export declare const useExportOrdersMutation: (orderIds?: OneOrMore<string>, mode?: MutationMode) => ResolvedQuery<BackendEndpoint.ExportOrders>;
@@ -19,5 +19,11 @@ type UseLanguage = {
19
19
  */
20
20
  translate(key?: Translation, replacers?: Replacers): string;
21
21
  };
22
+ /**
23
+ * Clears the cached translations. createPdkAdmin() calls it, so a new admin
24
+ * instance, for example after a language change in a single-page app, uses its
25
+ * own translations.
26
+ */
27
+ export declare const resetLanguageCache: () => void;
22
28
  export declare const useLanguage: () => UseLanguage;
23
29
  export {};
@@ -5,11 +5,35 @@ export declare class PdkAdmin {
5
5
  readonly config: AdminConfiguration;
6
6
  readonly context: AdminContextObject;
7
7
  readonly renderedComponents: string[];
8
+ /**
9
+ * One store and one query client per instance, shared by its apps. A page that
10
+ * creates a new instance after unmounting the apps of the previous one (for
11
+ * example a single-page admin) then starts without stale queries.
12
+ */
13
+ protected readonly store: import("pinia").Pinia;
14
+ protected readonly queryClient: import("@tanstack/vue-query").QueryClient;
15
+ private readonly disposers;
8
16
  constructor(config: AdminConfiguration, context: AdminContextObject);
9
17
  /**
10
- * Render a views in given selector.
18
+ * Register cleanup work for dispose().
19
+ */
20
+ onDispose(disposer: () => void): void;
21
+ /**
22
+ * Stop this instance, for example when a single-page app leaves the page.
23
+ * Unmount the apps that render() returned first. Safe to call twice.
24
+ *
25
+ * createPdkAdmin() reads the context from the boot element once. To create
26
+ * the next instance, render a new boot element.
27
+ *
28
+ * The cached queries go at once. A request that is still running reports to
29
+ * the admin on screen when it finishes.
30
+ */
31
+ dispose(): void;
32
+ /**
33
+ * Render a view in the given selector. Returns the app, so the caller can
34
+ * unmount it, or undefined when mounting failed.
11
35
  */
12
- render(view: AdminView, selector: string): Promise<void>;
36
+ render(view: AdminView, selector: string): Promise<App | undefined>;
13
37
  protected createApp(view: AdminView, appConfig: AdminAppConfig): Promise<App>;
14
38
  /**
15
39
  * Create a unique app name for components that are rendered multiple times.
@@ -1,3 +1,8 @@
1
1
  import { type AdminContextObject } from '../types';
2
2
  import { type PdkAdmin } from './PdkAdmin';
3
+ /**
4
+ * Sends the boot event now and again on every ping, until the instance is
5
+ * disposed. The listener and its cleanup exist before the first event, so a
6
+ * handler of that event can already dispose the instance.
7
+ */
3
8
  export declare const boot: (pdkAdmin: PdkAdmin, context: AdminContextObject) => void;
@@ -1,3 +1,4 @@
1
1
  export * from './PdkFetchClient';
2
2
  export * from './composables';
3
3
  export * from './endpoints';
4
+ export * from './requestHeaders';
@@ -0,0 +1,10 @@
1
+ export type RequestHeaders = Record<string, string>;
2
+ export type RequestHeadersProvider = () => RequestHeaders | Promise<RequestHeaders>;
3
+ export declare const setRequestHeadersProvider: (newProvider: RequestHeadersProvider | undefined) => void;
4
+ /**
5
+ * Request interceptor. Calls the provider for every request, so a short-lived
6
+ * token is always current.
7
+ */
8
+ export declare const addRequestHeaders: <T extends {
9
+ headers?: RequestHeaders;
10
+ }>(options: T) => Promise<T>;
@@ -1,2 +1,8 @@
1
1
  import { type MutationOptions } from '@tanstack/vue-query';
2
- export declare const getModalMutationOptions: <TData = unknown, TError = unknown, TVariables = void, TContext = unknown>() => MutationOptions<TData, TError, TVariables, TContext>;
2
+ import { type ModalMutationContext } from './modalMutationToken';
3
+ /**
4
+ * Options for a mutation that a modal starts. The callbacks only change the
5
+ * modal when it is still the modal that started the mutation. Pass the default
6
+ * mutation options, so their onMutate still runs.
7
+ */
8
+ export declare const getModalMutationOptions: <TData = unknown, TError = unknown, TVariables = void>(defaultOptions?: MutationOptions<TData, TError, TVariables>) => MutationOptions<TData, TError, TVariables, ModalMutationContext>;
@@ -1,3 +1,4 @@
1
1
  export * from './getCallbackForMutationMode';
2
2
  export * from './getModalMutationOptions';
3
+ export * from './modalMutationToken';
3
4
  export * from './mutationMode';
@@ -0,0 +1,16 @@
1
+ import { type ModalToken } from '../../stores';
2
+ export type ModalMutationContext = {
3
+ modalToken: ModalToken | null;
4
+ };
5
+ /**
6
+ * Creates an onMutate that keeps the token of the modal that is open when the
7
+ * mutation starts. Pass the onMutate it replaces, for example the default one
8
+ * of the query client, so that one still runs.
9
+ */
10
+ export declare const keepModalToken: <TVariables>(onMutate?: (variables: TVariables) => unknown) => (variables: TVariables) => ModalMutationContext;
11
+ /**
12
+ * Tells if the modal that was open when the mutation started is still open.
13
+ * Use it in late mutation callbacks, so they do not change a modal that the
14
+ * user opened in the meantime.
15
+ */
16
+ export declare const isSameModal: (context: ModalMutationContext | undefined) => boolean;
@@ -3,14 +3,22 @@ import { type AdminModalContext } from '../types';
3
3
  import { type AdminModalKey } from '../data';
4
4
  type ModalOpenFn = <K extends AdminModalKey>(modal: K, context?: AdminModalContext<K>) => void;
5
5
  type ModalCloseFn = <K extends AdminModalKey>(modal: K) => void;
6
+ /**
7
+ * Identifies one opened modal. Every open() creates a new object, so a token
8
+ * never matches another modal, also not a modal in another admin instance.
9
+ */
10
+ export type ModalToken = Readonly<{
11
+ modal: AdminModalKey;
12
+ }>;
6
13
  type ModalStore = {
7
14
  loading: Ref<boolean>;
8
15
  opened: Ref<AdminModalKey | null>;
9
16
  context: Ref<UnwrapNestedRefs<AdminModalContext>>;
17
+ token: Ref<ModalToken | null>;
10
18
  onOpen(callback: ModalOpenFn): void;
11
19
  onClose(callback: ModalCloseFn): void;
12
20
  open<K extends AdminModalKey>(modal: K, newContext?: AdminModalContext<K>): void;
13
21
  close(): void;
14
22
  };
15
- export declare const useModalStore: import("pinia").StoreDefinition<"modal", import("pinia")._UnwrapAll<Pick<ModalStore, "context" | "loading" | "opened">>, Pick<ModalStore, never>, Pick<ModalStore, "open" | "close" | "onOpen" | "onClose">>;
23
+ export declare const useModalStore: import("pinia").StoreDefinition<"modal", import("pinia")._UnwrapAll<Pick<ModalStore, "context" | "loading" | "opened" | "token">>, Pick<ModalStore, never>, Pick<ModalStore, "open" | "close" | "onOpen" | "onClose">>;
16
24
  export {};
@@ -1,4 +1,6 @@
1
1
  import { type Component } from 'vue';
2
+ import { type Pinia } from 'pinia';
3
+ import { type QueryClient } from '@tanstack/vue-query';
2
4
  import { type PdkLogger } from '../services';
3
5
  import { type ADMIN_COMPONENT_PREFIX, type AdminComponent, type AdminView, type optionalAdminActionContainerComponentNames, type optionalAdminComponentNames, type optionalAdminPlainWrapperComponentNames, type requiredAdminComponentNames } from '../data';
4
6
  import { type AdminContextObject, type AdminInstanceContext } from './context.types';
@@ -20,6 +22,14 @@ export interface AdminAppConfig {
20
22
  context: AdminContextObject;
21
23
  logger: PdkLogger;
22
24
  view?: AdminView;
25
+ /**
26
+ * Store of the PdkAdmin instance, shared by its apps. Without it, all apps share one store.
27
+ */
28
+ store?: Pinia;
29
+ /**
30
+ * Query client of the PdkAdmin instance, shared by its apps. Without it, all apps share one client.
31
+ */
32
+ queryClient?: QueryClient;
23
33
  }
24
34
  export interface AdminInstance extends Omit<AdminAppConfig, 'context'> {
25
35
  context: Partial<AdminInstanceContext>;
@@ -2,6 +2,7 @@ import { type PiniaPluginContext } from 'pinia';
2
2
  import { type FormConfiguration, type InteractiveElementInstance } from '@myparcel-dev/vue-form-builder';
3
3
  import { type MakeOptional } from '@myparcel-dev/ts-utils';
4
4
  import { type LogLevel } from '../services';
5
+ import { type RequestHeadersProvider } from '../sdk/requestHeaders';
5
6
  import { type FORM_KEYS } from '../forms';
6
7
  import { type FormatterObject } from '../composables';
7
8
  import { type AdminContextObject } from './context.types';
@@ -90,6 +91,17 @@ export type AdminConfiguration = {
90
91
  * Callback to generate a field id.
91
92
  */
92
93
  generateFieldId(element: InteractiveElementInstance): string;
94
+ /**
95
+ * Gives extra headers for every request to the PDK backend endpoint, for
96
+ * example a short-lived bearer token. Called once per request.
97
+ */
98
+ getRequestHeaders?: RequestHeadersProvider;
99
+ /**
100
+ * Read and write the active tab in window.location.hash. Turn it off when the
101
+ * host app routes with the hash, such as the Shopware administration.
102
+ * Defaults to true.
103
+ */
104
+ useLocationHash?: boolean;
93
105
  };
94
106
  export type AdminConfigurationPreset = Omit<Partial<AdminConfiguration>, 'components'>;
95
107
  export type InputAdminConfiguration = MakeOptional<AdminConfiguration, 'generateFieldId'>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myparcel-dev/pdk-admin",
3
- "version": "2.3.0",
3
+ "version": "2.4.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/myparcelnl/js-pdk.git",
@@ -37,7 +37,7 @@
37
37
  },
38
38
  "dependencies": {
39
39
  "@myparcel-dev/constants": "^2.9.0",
40
- "@myparcel-dev/pdk-common": "^2.3.0",
40
+ "@myparcel-dev/pdk-common": "^2.3.1",
41
41
  "@myparcel-dev/sdk": "^5.1.0",
42
42
  "@myparcel-dev/vue-form-builder": "1.0.0-beta.42.6",
43
43
  "@tanstack/vue-query": "~4.43.0",
@@ -0,0 +1,75 @@
1
+ // @vitest-environment happy-dom
2
+
3
+ import {createApp, defineComponent} from 'vue';
4
+ import {afterEach, describe, expect, it, vi} from 'vitest';
5
+ import {createPinia} from 'pinia';
6
+ import {QueryClient, VueQueryPlugin} from '@tanstack/vue-query';
7
+ import {useModalStore} from '../../../../stores';
8
+ import {AdminModalKey} from '../../../../data';
9
+ import {useExportOrdersMutation} from './useExportOrdersMutation';
10
+
11
+ const exportOrders = vi.fn();
12
+
13
+ vi.mock('../../../../sdk', () => ({usePdkAdminApi: () => ({exportOrders})}));
14
+
15
+ const mountMutation = () => {
16
+ let mutation: ReturnType<typeof useExportOrdersMutation> | undefined;
17
+ const app = createApp(
18
+ defineComponent({
19
+ setup() {
20
+ mutation = useExportOrdersMutation('1');
21
+
22
+ return () => null;
23
+ },
24
+ }),
25
+ );
26
+
27
+ app.use(createPinia());
28
+ app.use(VueQueryPlugin, {queryClient: new QueryClient()});
29
+ app.mount(document.createElement('div'));
30
+
31
+ return {
32
+ app,
33
+ mutation: mutation as ReturnType<typeof useExportOrdersMutation>,
34
+ };
35
+ };
36
+
37
+ describe('useExportOrdersMutation', () => {
38
+ afterEach(() => {
39
+ exportOrders.mockReset();
40
+ });
41
+
42
+ it('closes the modal that started the export', async () => {
43
+ exportOrders.mockResolvedValue([]);
44
+ const {app, mutation} = mountMutation();
45
+ const modalStore = app.runWithContext(() => useModalStore());
46
+
47
+ modalStore.open(AdminModalKey.ShipmentOptions);
48
+ await mutation.mutateAsync({} as never);
49
+
50
+ expect(modalStore.opened).toBeNull();
51
+ });
52
+
53
+ it('leaves a modal open that the user opened while the export ran', async () => {
54
+ let finish: (value: unknown[]) => void = () => undefined;
55
+ exportOrders.mockReturnValue(
56
+ new Promise((resolve) => {
57
+ finish = resolve;
58
+ }),
59
+ );
60
+ const {app, mutation} = mountMutation();
61
+ const modalStore = app.runWithContext(() => useModalStore());
62
+
63
+ modalStore.open(AdminModalKey.ShipmentOptions);
64
+ const done = mutation.mutateAsync({} as never);
65
+ await vi.waitFor(() => expect(exportOrders).toHaveBeenCalled());
66
+
67
+ // The user closes the modal with Escape and opens the modal of another order.
68
+ modalStore.close();
69
+ modalStore.open(AdminModalKey.ShipmentOptions);
70
+ finish([]);
71
+ await done;
72
+
73
+ expect(modalStore.opened).toBe(AdminModalKey.ShipmentOptions);
74
+ });
75
+ });
@@ -1,11 +1,17 @@
1
1
  import {useQueryClient} from '@tanstack/vue-query';
2
- import {BackendEndpoint} from '@myparcel-dev/pdk-common';
3
2
  import {type OneOrMore, toArray} from '@myparcel-dev/ts-utils';
3
+ import {BackendEndpoint} from '@myparcel-dev/pdk-common';
4
4
  import {usePdkMutation} from '../usePdkMutation';
5
5
  import {encodeArrayParameter, formToBody} from '../../../../utils';
6
6
  import {type BackendEndpointOptions} from '../../../../types';
7
7
  import {type ResolvedQuery, useModalStore} from '../../../../stores';
8
- import {getCallbackForMutationMode, getModalMutationOptions, MutationMode} from '../../../../services';
8
+ import {
9
+ getCallbackForMutationMode,
10
+ getModalMutationOptions,
11
+ isSameModal,
12
+ keepModalToken,
13
+ MutationMode,
14
+ } from '../../../../services';
9
15
  import {usePdkAdminApi} from '../../../../sdk';
10
16
  import {fillShipmentsQueryData} from '../../../../pdk';
11
17
 
@@ -14,6 +20,7 @@ export const useExportOrdersMutation = (
14
20
  mode: MutationMode = MutationMode.Default,
15
21
  ): ResolvedQuery<BackendEndpoint.ExportOrders> => {
16
22
  const queryClient = useQueryClient();
23
+ const defaultMutationOptions = queryClient.defaultMutationOptions();
17
24
 
18
25
  return usePdkMutation(
19
26
  BackendEndpoint.ExportOrders,
@@ -32,11 +39,15 @@ export const useExportOrdersMutation = (
32
39
  return pdk.exportOrders(options);
33
40
  },
34
41
  {
35
- ...queryClient.defaultMutationOptions(),
36
- ...(mode === MutationMode.Modal ? getModalMutationOptions() : {}),
42
+ ...defaultMutationOptions,
43
+ ...(mode === MutationMode.Modal ? getModalMutationOptions(defaultMutationOptions) : {}),
44
+ // Also in the default mode: onSuccess closes the modal that started the export.
45
+ onMutate: keepModalToken(defaultMutationOptions.onMutate),
37
46
 
38
- async onSuccess(data, input) {
39
- useModalStore().close();
47
+ async onSuccess(data, input, context) {
48
+ if (isSameModal(context)) {
49
+ useModalStore().close();
50
+ }
40
51
 
41
52
  toArray(data).forEach((order) => {
42
53
  fillShipmentsQueryData(queryClient, order.shipments?.slice(-1) ?? [], order);
@@ -0,0 +1,78 @@
1
+ // @vitest-environment happy-dom
2
+
3
+ import {defineComponent, h} from 'vue';
4
+ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
5
+ import {mount} from '@vue/test-utils';
6
+ import {useAdminConfig} from '../../composables';
7
+ import TabNavigation from './TabNavigation.vue';
8
+
9
+ vi.mock('../../composables', () => ({
10
+ useAdminConfig: vi.fn(),
11
+ useLanguage: vi.fn(() => ({translate: (key: string) => key})),
12
+ }));
13
+
14
+ const createTab = (name: string) => ({
15
+ name,
16
+ label: name,
17
+ component: defineComponent({name: `Tab-${name}`, render: () => h('p', name)}),
18
+ });
19
+
20
+ // eslint-disable-next-line @typescript-eslint/naming-convention
21
+ const PdkTabNavContentWrapper = defineComponent({
22
+ render() {
23
+ return h('div', this.$slots.default?.());
24
+ },
25
+ });
26
+
27
+ const mountTabs = () =>
28
+ mount(TabNavigation, {
29
+ props: {tabs: [createTab('general'), createTab('label')], button: 'button', buttonWrapper: 'div'},
30
+ global: {stubs: {PdkTabNavContentWrapper}},
31
+ });
32
+
33
+ const clickTab = async (wrapper: ReturnType<typeof mountTabs>, name: string) => {
34
+ await wrapper
35
+ .findAll('button')
36
+ .find((button) => button.text() === name)
37
+ ?.trigger('click');
38
+ };
39
+
40
+ describe('TabNavigation', () => {
41
+ beforeEach(() => {
42
+ window.location.hash = '';
43
+ });
44
+
45
+ afterEach(() => {
46
+ window.location.hash = '';
47
+ });
48
+
49
+ it('writes the active tab to the location hash by default', async () => {
50
+ vi.mocked(useAdminConfig).mockReturnValue({} as never);
51
+ const wrapper = mountTabs();
52
+
53
+ await clickTab(wrapper, 'label');
54
+
55
+ expect(window.location.hash).toBe('#label');
56
+ expect(wrapper.text()).toContain('label');
57
+ });
58
+
59
+ it('opens the tab from the location hash by default', () => {
60
+ vi.mocked(useAdminConfig).mockReturnValue({} as never);
61
+ window.location.hash = '#label';
62
+
63
+ expect(mountTabs().find('p').text()).toBe('label');
64
+ });
65
+
66
+ it('leaves the location hash alone when the host app routes with it', async () => {
67
+ vi.mocked(useAdminConfig).mockReturnValue({useLocationHash: false} as never);
68
+ window.location.hash = '#/myparcel/settings/index';
69
+ const wrapper = mountTabs();
70
+
71
+ expect(wrapper.find('p').text()).toBe('general');
72
+
73
+ await clickTab(wrapper, 'label');
74
+
75
+ expect(window.location.hash).toBe('#/myparcel/settings/index');
76
+ expect(wrapper.find('p').text()).toBe('label');
77
+ });
78
+ });
@@ -79,8 +79,13 @@ const props = defineProps({
79
79
 
80
80
  const activeTab = ref<string | null>(null);
81
81
 
82
+ const config = useAdminConfig();
83
+ const {translate} = useLanguage();
84
+
85
+ const useLocationHash = config.useLocationHash !== false;
86
+
82
87
  const handleClick = (tab: TabDefinition) => {
83
- if (props.initialTab !== false) {
88
+ if (useLocationHash && props.initialTab !== false) {
84
89
  window.location.hash = props.hashPrefix + tab.name;
85
90
  }
86
91
 
@@ -96,9 +101,6 @@ const activeTabContents = computed(() => {
96
101
  return (props.tabs as unknown as TabDefinition[])?.find((tab) => tab.name === activeTab.value);
97
102
  });
98
103
 
99
- const config = useAdminConfig();
100
- const {translate} = useLanguage();
101
-
102
104
  watch(
103
105
  () => [props.tabs, props.initialTab],
104
106
  () => {
@@ -113,7 +115,7 @@ watch(
113
115
 
114
116
  let initialTab = props.initialTab === true ? null : props.initialTab;
115
117
 
116
- if (!props.initialTab) {
118
+ if (!props.initialTab && useLocationHash) {
117
119
  const hash = window.location.hash.replace('#', '').replace(props.hashPrefix ?? '', '');
118
120
  const tabName = hash.split(HASH_SEPARATOR)[0];
119
121
 
@@ -0,0 +1,24 @@
1
+ // @vitest-environment happy-dom
2
+
3
+ import {describe, expect, it, vi} from 'vitest';
4
+ import {useGlobalContext} from '../context';
5
+ import {resetLanguageCache, useLanguage} from './useLanguage';
6
+
7
+ vi.mock('../context', () => ({useGlobalContext: vi.fn()}));
8
+
9
+ const useTranslations = (translations: Record<string, string>) => {
10
+ vi.mocked(useGlobalContext).mockReturnValue({translations} as never);
11
+ };
12
+
13
+ describe('resetLanguageCache', () => {
14
+ it('translates with the translations of the next admin instance after a reset', () => {
15
+ useTranslations({settings_title: 'Settings'});
16
+ expect(useLanguage().translate('settings_title')).toBe('Settings');
17
+
18
+ useTranslations({settings_title: 'Einstellungen'});
19
+ resetLanguageCache();
20
+
21
+ expect(useLanguage().translate('settings_title')).toBe('Einstellungen');
22
+ expect(useLanguage().has('settings_title')).toBe(true);
23
+ });
24
+ });
@@ -104,6 +104,19 @@ const memoizedAll = useMemoize(all);
104
104
  const memoizedHas = useMemoize(has);
105
105
  const memoizedTranslate = useMemoize(translate);
106
106
 
107
+ /**
108
+ * Clears the cached translations. createPdkAdmin() calls it, so a new admin
109
+ * instance, for example after a language change in a single-page app, uses its
110
+ * own translations.
111
+ */
112
+ export const resetLanguageCache = (): void => {
113
+ memoizedAll.clear();
114
+ memoizedHas.clear();
115
+ memoizedTranslate.clear();
116
+ useCache().clear();
117
+ useMissingKeys().value = [];
118
+ };
119
+
107
120
  export const useLanguage = (): UseLanguage => {
108
121
  const missingKeys = useMissingKeys();
109
122
 
@@ -195,14 +195,21 @@ describe('useFormCapabilities', () => {
195
195
  expect(useFormCapabilities().getInsuranceOptions(formStub('POSTNL'), formatter)).toEqual([]);
196
196
  });
197
197
 
198
- it('switches step from 250 to 500 across the 500€ threshold', async () => {
198
+ // Same cases as InsuranceTierMathTest in the PHP PDK, so both sides offer the same tiers.
199
+ it.each([
200
+ [100, 100, ['100']],
201
+ [500, 100, ['500']],
202
+ [0, 200_000, ['0', '10000', '25000', '50000', '100000', '150000', '200000']],
203
+ [30_000, 100_000, ['30000', '50000', '100000']],
204
+ [50_000, 150_000, ['50000', '100000', '150000']],
205
+ [0, 37_500, ['0', '10000', '25000', '37500']],
206
+ ])('builds the tier ladder for min %i and max %i', async (min, max, expected) => {
199
207
  const shipment = buildCarrier({
200
208
  carrier: 'POSTNL',
201
209
  options: {
202
210
  insurance: {
203
- min: {amount: 0, currency: 'EUR'},
204
- // max is 1000€ in cents
205
- max: {amount: 100_000, currency: 'EUR'},
211
+ min: {amount: min, currency: 'EUR'},
212
+ max: {amount: max, currency: 'EUR'},
206
213
  default: {amount: 0, currency: 'EUR'},
207
214
  } as never,
208
215
  },
@@ -210,14 +217,13 @@ describe('useFormCapabilities', () => {
210
217
  queryStore.setQuery(shipmentModifier('order-1'), 'success', [shipment]);
211
218
 
212
219
  const {useFormCapabilities} = await import('./useFormCapabilities');
213
- const opts = useFormCapabilities().getInsuranceOptions(formStub('POSTNL'), formatter);
214
- const values = opts.map((o) => o.value);
220
+ const values = useFormCapabilities()
221
+ .getInsuranceOptions(formStub('POSTNL'), formatter)
222
+ .map((o) => o.value);
215
223
 
216
224
  // First entry is the inherit default; subsequent values are cent amounts as strings.
217
225
  expect(values[0]).toBe(TriState.Inherit);
218
- // 0, 250, 500 (low steps) — then 1000 (high step from 500). Exact sequence verifies
219
- // the boundary semantics — replacing `<` with `<=` on LOW_THRESHOLD would shift these.
220
- expect(values.slice(1)).toEqual(['0', '25000', '50000', '100000']);
226
+ expect(values.slice(1)).toEqual(expected);
221
227
  });
222
228
 
223
229
  it('returns [] when the carrier advertises insurance without limits', async () => {
@@ -7,6 +7,30 @@ import {type AdminContext, type SelectOption} from '../../types';
7
7
  import {useQueryStore, type ResolvedQuery} from '../../stores';
8
8
  import {Format, type Formatter} from '../../composables';
9
9
 
10
+ const INSURANCE_FLOOR_TIERS = [10_000, 25_000, 50_000];
11
+ const INSURANCE_STEP = 50_000;
12
+
13
+ /**
14
+ * Build the insurance tier ladder for a min/max range, in cents. Mirrors
15
+ * `InsuranceTierMath::buildTiers` in the PHP PDK, so the dropdown offers the same amounts the
16
+ * backend accepts: min, the floor tiers €100, €250 and €500, then €500 steps, then max.
17
+ */
18
+ const buildInsuranceTiers = (min: number, max: number): number[] => {
19
+ if (min >= max) {
20
+ return [min];
21
+ }
22
+
23
+ const tiers = [min, ...INSURANCE_FLOOR_TIERS.filter((tier) => tier > min && tier < max)];
24
+
25
+ for (let tier = Math.max(min, INSURANCE_STEP) + INSURANCE_STEP; tier < max; tier += INSURANCE_STEP) {
26
+ tiers.push(tier);
27
+ }
28
+
29
+ tiers.push(max);
30
+
31
+ return [...new Set(tiers)];
32
+ };
33
+
10
34
  /**
11
35
  * Bag of capability resolvers, each pre-bound to a Pinia store + orderId snapshot captured at
12
36
  * the composable's invocation time. Returned by {@link useFormCapabilities}.
@@ -129,25 +153,15 @@ export const useFormCapabilities = (): FormCapabilities => {
129
153
  };
130
154
 
131
155
  const getInsuranceOptions = (form: FormInstance, formatter: Formatter): SelectOption[] => {
132
- // Insurance bracket steps: €250 increments below €500, €500 increments above. Switching
133
- // step size at the threshold keeps the dropdown short for high-value shipments.
134
- const STEP_BELOW_THRESHOLD = 250;
135
- const STEP_ABOVE_THRESHOLD = 500;
136
- const STEP_THRESHOLD = 500;
137
-
138
156
  const carrier = getCarrierCapabilitiesForShipment(form);
139
157
  const insuranceData = carrier?.options?.insurance;
140
158
 
141
- const min = insuranceData?.min?.amount ? insuranceData.min.amount / 100 : 0;
142
- const max = insuranceData?.max?.amount ? insuranceData.max.amount / 100 : 0;
159
+ const min = insuranceData?.min?.amount ?? 0;
160
+ const max = insuranceData?.max?.amount ?? 0;
143
161
 
144
162
  if (max === 0) return [];
145
163
 
146
- const insurancePossibilities: number[] = [];
147
-
148
- for (let i = min; i <= max; i += i < STEP_THRESHOLD ? STEP_BELOW_THRESHOLD : STEP_ABOVE_THRESHOLD) {
149
- insurancePossibilities.push(i * 100);
150
- }
164
+ const insurancePossibilities = buildInsuranceTiers(min, max);
151
165
 
152
166
  return [
153
167
  {label: 'option_default', value: TriState.Inherit},