@myparcel-dev/pdk-admin 2.2.7 → 2.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 (69) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/actions/composables/mutations/orders/useExportOrdersMutation.d.ts +1 -1
  3. package/dist/actions/print/resolvePrintParameters.d.ts +1 -0
  4. package/dist/composables/language/useLanguage.d.ts +6 -0
  5. package/dist/pdk/PdkAdmin.d.ts +26 -2
  6. package/dist/pdk/boot.d.ts +5 -0
  7. package/dist/sdk/index.d.ts +1 -0
  8. package/dist/sdk/requestHeaders.d.ts +10 -0
  9. package/dist/services/mutations/getModalMutationOptions.d.ts +7 -1
  10. package/dist/services/mutations/index.d.ts +1 -0
  11. package/dist/services/mutations/modalMutationToken.d.ts +16 -0
  12. package/dist/services/print/createPdfObjectUrl.d.ts +2 -0
  13. package/dist/services/print/index.d.ts +3 -0
  14. package/dist/services/print/labelsNotification.d.ts +5 -0
  15. package/dist/services/print/pollLabelPdf.d.ts +9 -0
  16. package/dist/stores/useModalStore.d.ts +9 -1
  17. package/dist/stores/useNotificationStore.d.ts +15 -0
  18. package/dist/types/actions/endpoints.types.d.ts +1 -1
  19. package/dist/types/actions/parameters.types.d.ts +3 -0
  20. package/dist/types/admin.types.d.ts +10 -0
  21. package/dist/types/common.types.d.ts +7 -0
  22. package/dist/types/configuration.types.d.ts +12 -0
  23. package/dist/types/sdk.types.d.ts +14 -1
  24. package/dist/utils/encodeArrayParameter.d.ts +1 -0
  25. package/package.json +2 -2
  26. package/src/actions/composables/mutations/orders/useExportOrdersMutation.spec.ts +75 -0
  27. package/src/actions/composables/mutations/orders/useExportOrdersMutation.ts +17 -6
  28. package/src/actions/print/openOrPrintPdf.spec.ts +119 -0
  29. package/src/actions/print/openOrPrintPdf.ts +48 -3
  30. package/src/actions/print/resolvePrintParameters.ts +13 -3
  31. package/src/components/common/TabNavigation.spec.ts +78 -0
  32. package/src/components/common/TabNavigation.vue +7 -5
  33. package/src/composables/language/resetLanguageCache.spec.ts +24 -0
  34. package/src/composables/language/useLanguage.ts +13 -0
  35. package/src/pdk/PdkAdmin.spec.ts +97 -0
  36. package/src/pdk/PdkAdmin.ts +63 -7
  37. package/src/pdk/boot.ts +13 -3
  38. package/src/pdk/createPdkAdmin.spec.ts +75 -0
  39. package/src/pdk/createPdkAdmin.ts +2 -0
  40. package/src/pdk/instance/plugins/createStorePlugin.spec.ts +44 -0
  41. package/src/pdk/instance/plugins/createStorePlugin.ts +12 -7
  42. package/src/pdk/instance/plugins/createVueQueryPlugin.spec.ts +29 -0
  43. package/src/pdk/instance/plugins/createVueQueryPlugin.ts +7 -7
  44. package/src/pdk/setupAdminApp.ts +3 -0
  45. package/src/sdk/composables/usePdkAdminApi.ts +3 -0
  46. package/src/sdk/index.ts +1 -0
  47. package/src/sdk/requestHeaders.spec.ts +54 -0
  48. package/src/sdk/requestHeaders.ts +36 -0
  49. package/src/services/mutations/getModalMutationOptions.spec.ts +59 -0
  50. package/src/services/mutations/getModalMutationOptions.ts +23 -15
  51. package/src/services/mutations/index.ts +1 -0
  52. package/src/services/mutations/modalMutationToken.ts +27 -0
  53. package/src/services/print/createPdfObjectUrl.ts +6 -0
  54. package/src/services/print/index.ts +3 -0
  55. package/src/services/print/labelsNotification.ts +52 -0
  56. package/src/services/print/pollLabelPdf.spec.ts +58 -0
  57. package/src/services/print/pollLabelPdf.ts +47 -0
  58. package/src/stores/useModalStore.spec.ts +33 -0
  59. package/src/stores/useModalStore.ts +13 -1
  60. package/src/stores/useNotificationStore.spec.ts +30 -0
  61. package/src/stores/useNotificationStore.ts +1 -1
  62. package/src/types/actions/endpoints.types.ts +1 -0
  63. package/src/types/actions/parameters.types.ts +2 -0
  64. package/src/types/admin.types.ts +12 -0
  65. package/src/types/common.types.ts +7 -0
  66. package/src/types/configuration.types.ts +14 -0
  67. package/src/types/sdk.types.ts +16 -0
  68. package/src/utils/encodeArrayParameter.spec.ts +26 -0
  69. package/src/utils/encodeArrayParameter.ts +2 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,34 @@
2
2
 
3
3
  <!-- MONOWEAVE:BELOW -->
4
4
 
5
+ ## [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)
6
+
7
+
8
+ ### Features
9
+
10
+ * **admin:** allow dynamic request headers ([#499](https://github.com/myparcelnl/js-pdk/issues/499)) ([35c3b02](https://github.com/myparcelnl/js-pdk/commit/35c3b02f7307043e5c6a7a3fa8cae545703b067c))
11
+ * **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))
12
+ * **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))
13
+
14
+
15
+
16
+
17
+ ## [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)
18
+
19
+
20
+ ### Features
21
+
22
+ * **admin:** wait for bulk label pdfs and show progress while printing ([#490](https://github.com/myparcelnl/js-pdk/issues/490)) ([c093d2d](https://github.com/myparcelnl/js-pdk/commit/c093d2d8fcaef29b5b2b6fbbce20570f76b631b9))
23
+
24
+
25
+ ### Bug Fixes
26
+
27
+ * **admin:** encode array parameters so proxies keep all ids ([#488](https://github.com/myparcelnl/js-pdk/issues/488)) ([acd1a2a](https://github.com/myparcelnl/js-pdk/commit/acd1a2ad5f8133f187516259bcecb85f5fb6f106))
28
+ * **admin:** stop removing all notifications when a mutation starts ([#489](https://github.com/myparcelnl/js-pdk/issues/489)) ([0a49a1d](https://github.com/myparcelnl/js-pdk/commit/0a49a1d4ee1c7de0793eac17c19417e102c71eee))
29
+
30
+
31
+
32
+
5
33
  ## [2.2.7](https://github.com/myparcelnl/js-pdk/compare/@myparcel-dev/pdk-admin@2.2.6...@myparcel-dev/pdk-admin@2.2.7) "@myparcel-dev/pdk-admin" (2026-09-25)
6
34
 
7
35
 
@@ -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>;
@@ -1,3 +1,4 @@
1
1
  import { type ActionContext } from '../executors';
2
2
  import { type ActionParameters, type PrintAction } from '../../types';
3
+ /** Resolves the label options, then shows the loading notification that openOrPrintPdf closes. */
3
4
  export declare const resolvePrintParameters: <A extends PrintAction>(context: ActionContext<A>) => Promise<ActionParameters<A>>;
@@ -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;
@@ -0,0 +1,2 @@
1
+ /** Turns a base64 pdf into an object url that a link can open or download. */
2
+ export declare const createPdfObjectUrl: (pdf: string) => string;
@@ -1 +1,4 @@
1
+ export * from './createPdfObjectUrl';
2
+ export * from './labelsNotification';
1
3
  export * from './openPdfInNewWindow';
4
+ export * from './pollLabelPdf';
@@ -0,0 +1,5 @@
1
+ export declare const LABELS_NOTIFICATION_ID = "print-labels";
2
+ export declare const showLabelsLoading: () => void;
3
+ export declare const showLabelsReady: (open: () => void) => void;
4
+ export declare const showLabelsFailed: () => void;
5
+ export declare const hideLabelsNotification: () => void;
@@ -0,0 +1,9 @@
1
+ type PollOptions = {
2
+ interval?: number;
3
+ timeout?: number;
4
+ };
5
+ /**
6
+ * Ask the backend for a labels pdf until the API has generated it. Resolves with the base64 pdf.
7
+ */
8
+ export declare const pollLabelPdf: (labelId: string, { interval, timeout }?: PollOptions) => Promise<string>;
9
+ export {};
@@ -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 {};
@@ -10,6 +10,11 @@ export declare const useNotificationStore: import("pinia").StoreDefinition<"noti
10
10
  timeout: boolean | number;
11
11
  title?: string | undefined;
12
12
  variant: import("@myparcel-dev/pdk-common").Variant;
13
+ loading?: boolean | undefined;
14
+ action?: {
15
+ label: string;
16
+ onClick: () => void;
17
+ } | undefined;
13
18
  }[]>;
14
19
  /**
15
20
  * Add a notification to the store.
@@ -29,6 +34,11 @@ export declare const useNotificationStore: import("pinia").StoreDefinition<"noti
29
34
  timeout: boolean | number;
30
35
  title?: string | undefined;
31
36
  variant: import("@myparcel-dev/pdk-common").Variant;
37
+ loading?: boolean | undefined;
38
+ action?: {
39
+ label: string;
40
+ onClick: () => void;
41
+ } | undefined;
32
42
  }[]>;
33
43
  /**
34
44
  * Add a notification to the store.
@@ -48,6 +58,11 @@ export declare const useNotificationStore: import("pinia").StoreDefinition<"noti
48
58
  timeout: boolean | number;
49
59
  title?: string | undefined;
50
60
  variant: import("@myparcel-dev/pdk-common").Variant;
61
+ loading?: boolean | undefined;
62
+ action?: {
63
+ label: string;
64
+ onClick: () => void;
65
+ } | undefined;
51
66
  }[]>;
52
67
  /**
53
68
  * Add a notification to the store.
@@ -6,4 +6,4 @@ export type BackendMutationEndpoints = BackendEndpoint.CreateWebhooks | BackendE
6
6
  /**
7
7
  * All backend endpoints that are queries.
8
8
  */
9
- export type BackendQueryEndpoints = BackendEndpoint.FetchContext | BackendEndpoint.FetchOrders | BackendEndpoint.FetchProducts | BackendEndpoint.FetchShipments | BackendEndpoint.FetchWebhooks | BackendEndpoint.ProxyCapabilities;
9
+ export type BackendQueryEndpoints = BackendEndpoint.FetchContext | BackendEndpoint.FetchLabelPdf | BackendEndpoint.FetchOrders | BackendEndpoint.FetchProducts | BackendEndpoint.FetchShipments | BackendEndpoint.FetchWebhooks | BackendEndpoint.ProxyCapabilities;
@@ -42,6 +42,9 @@ export interface EndpointMutationInputMap extends Record<BackendEndpoint, object
42
42
  [BackendEndpoint.FetchShipments]: OrderIdParameters & ShipmentIdParameters;
43
43
  [BackendEndpoint.UpdateShipments]: OrderIdParameters & ShipmentIdParameters;
44
44
  [BackendEndpoint.PrintShipments]: OrderIdParameters & ShipmentIdParameters & OptionalFormParameters & LabelParameters;
45
+ [BackendEndpoint.FetchLabelPdf]: {
46
+ labelId: string;
47
+ };
45
48
  [BackendEndpoint.FetchProducts]: ProductIdParameters;
46
49
  [BackendEndpoint.UpdatePluginSettings]: FormParameters;
47
50
  [BackendEndpoint.UpdateProductSettings]: ProductIdParameters & FormParameters;
@@ -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>;
@@ -22,6 +22,13 @@ export interface PdkNotification {
22
22
  timeout?: boolean | number;
23
23
  title?: string;
24
24
  variant: Variant;
25
+ /** Shows a spinner next to the content. */
26
+ loading?: boolean;
27
+ /** Shows a button that runs onClick. */
28
+ action?: {
29
+ label: string;
30
+ onClick(): void;
31
+ };
25
32
  }
26
33
  export type ResolvedNotification = PdkNotification & {
27
34
  id: NotificationId;
@@ -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'>;
@@ -4,10 +4,15 @@ import { type AdminContextObject } from './context.types';
4
4
  import { type WebhookDefinition } from './common.types';
5
5
  export type PdfUrlResponse = {
6
6
  url: string;
7
+ /** Hash of the `/pdfs/{hash}` link for the whole batch, not a label id. Poll it with fetchLabelPdf. */
8
+ labelId?: string;
7
9
  };
8
10
  export type PdfDataResponse = {
9
11
  data: string;
10
12
  };
13
+ export type PdfPendingResponse = {
14
+ pending: true;
15
+ };
11
16
  interface BasePrintDefinition extends PdkEndpointDefinition {
12
17
  formattedResponse: PdfUrlResponse | PdfDataResponse;
13
18
  parameters: {
@@ -119,6 +124,14 @@ interface PrintShipmentsDefinition extends BasePrintDefinition {
119
124
  interface PrintOrdersDefinition extends BasePrintDefinition {
120
125
  name: BackendEndpoint.PrintOrders;
121
126
  }
127
+ interface FetchLabelPdfDefinition extends PdkEndpointDefinition {
128
+ formattedResponse: PdfDataResponse | PdfPendingResponse;
129
+ name: BackendEndpoint.FetchLabelPdf;
130
+ parameters: {
131
+ labelId: string;
132
+ };
133
+ response: PdfDataResponse | PdfPendingResponse;
134
+ }
122
135
  interface FetchWebhooksDefinition extends PdkEndpointDefinition {
123
136
  name: BackendEndpoint.FetchWebhooks;
124
137
  parameters: never;
@@ -207,6 +220,6 @@ export type ProxyCapabilitiesCall = (options: {
207
220
  body: ProxyCapabilitiesBody;
208
221
  parameters?: ProxyCapabilitiesParameters;
209
222
  }) => Promise<ProxyCapabilitiesDefinition['response']>;
210
- export type BackendEndpointDefinition = CreateWebhooksDefinition | DebugDownloadLogsDefinition | DebugSwitchToAcceptanceApiDefinition | DebugSwitchToProductionApiDefinition | DeleteAccountDefinition | DeleteShipmentsDefinition | DeleteWebhooksDefinition | ExportOrdersDefinition | FetchContextDefinition | FetchOrdersDefinition | FetchProductsDefinition | FetchShipmentsDefinition | FetchWebhooksDefinition | PrintOrdersDefinition | PrintShipmentsDefinition | ProxyCapabilitiesDefinition | UpdateAccountDefinition | UpdateOrdersDefinition | UpdatePluginSettingsDefinition | UpdateProductSettingsDefinition | UpdateShipmentsDefinition;
223
+ export type BackendEndpointDefinition = CreateWebhooksDefinition | DebugDownloadLogsDefinition | DebugSwitchToAcceptanceApiDefinition | DebugSwitchToProductionApiDefinition | DeleteAccountDefinition | DeleteShipmentsDefinition | DeleteWebhooksDefinition | ExportOrdersDefinition | FetchContextDefinition | FetchLabelPdfDefinition | FetchOrdersDefinition | FetchProductsDefinition | FetchShipmentsDefinition | FetchWebhooksDefinition | PrintOrdersDefinition | PrintShipmentsDefinition | ProxyCapabilitiesDefinition | UpdateAccountDefinition | UpdateOrdersDefinition | UpdatePluginSettingsDefinition | UpdateProductSettingsDefinition | UpdateShipmentsDefinition;
211
224
  export type BackendEndpointOptions<N extends BackendEndpoint> = Omit<ExtractEndpointDefinition<N, BackendEndpointDefinition>, 'name' | 'response'>;
212
225
  export {};
@@ -1,2 +1,3 @@
1
1
  import { type OneOrMore } from '@myparcel-dev/ts-utils';
2
+ /** Joins values with `;` and URL-encodes the result, because the SDK appends parameters to the URL raw. */
2
3
  export declare const encodeArrayParameter: (parameter?: null | OneOrMore<string | number | undefined>) => string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myparcel-dev/pdk-admin",
3
- "version": "2.2.7",
3
+ "version": "2.4.0",
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.2.1",
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,119 @@
1
+ // @vitest-environment happy-dom
2
+
3
+ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
4
+ import {createPinia, setActivePinia} from 'pinia';
5
+ import {Variant} from '@myparcel-dev/pdk-common';
6
+ import {useNotificationStore} from '../../stores';
7
+ import {LABELS_NOTIFICATION_ID, showLabelsLoading} from '../../services/print/labelsNotification';
8
+ import {openOrPrintPdf} from './openOrPrintPdf';
9
+
10
+ const {fetchLabelPdf, openUrlInNewTab, downloadFileFromUrl} = vi.hoisted(() => ({
11
+ fetchLabelPdf: vi.fn(),
12
+ openUrlInNewTab: vi.fn(),
13
+ downloadFileFromUrl: vi.fn(),
14
+ }));
15
+
16
+ vi.mock('../../sdk', () => ({usePdkAdminApi: () => ({fetchLabelPdf})}));
17
+
18
+ vi.mock('../../utils', async (importOriginal) => {
19
+ const actual = await importOriginal<typeof import('../../utils')>();
20
+
21
+ return {...actual, openUrlInNewTab, downloadFileFromUrl};
22
+ });
23
+
24
+ vi.mock('../../composables', async (importOriginal) => {
25
+ const actual = await importOriginal<typeof import('../../composables')>();
26
+
27
+ return {...actual, useLanguage: () => ({translate: (key: string) => key, has: () => true})};
28
+ });
29
+
30
+ const labelsNotification = () => {
31
+ return useNotificationStore().notifications.find((notification) => notification.id === LABELS_NOTIFICATION_ID);
32
+ };
33
+
34
+ const print = (output: 'open' | 'download') => {
35
+ return openOrPrintPdf({
36
+ // @ts-expect-error only the fields openOrPrintPdf reads
37
+ response: {url: 'https://api/pdfs/label_hash', labelId: 'label_hash'},
38
+ // @ts-expect-error only the fields openOrPrintPdf reads
39
+ parameters: {orderIds: ['1', '2'], output},
40
+ });
41
+ };
42
+
43
+ describe('openOrPrintPdf with a label link', () => {
44
+ beforeEach(() => {
45
+ setActivePinia(createPinia());
46
+ vi.useFakeTimers();
47
+ fetchLabelPdf.mockReset();
48
+ openUrlInNewTab.mockReset();
49
+ downloadFileFromUrl.mockReset();
50
+ URL.createObjectURL = vi.fn(() => 'blob:labels');
51
+ URL.revokeObjectURL = vi.fn();
52
+ showLabelsLoading();
53
+ });
54
+
55
+ afterEach(() => {
56
+ vi.useRealTimers();
57
+ });
58
+
59
+ it('shows a button to open the labels once the pdf is ready', async () => {
60
+ fetchLabelPdf.mockResolvedValueOnce({pending: true}).mockResolvedValueOnce({data: 'cGRm'});
61
+
62
+ const promise = print('open');
63
+
64
+ expect(labelsNotification()?.loading).toBe(true);
65
+
66
+ await vi.advanceTimersByTimeAsync(5000);
67
+ await promise;
68
+
69
+ const notification = labelsNotification();
70
+
71
+ expect(notification?.loading).toBeFalsy();
72
+ expect(notification?.variant).toBe(Variant.Success);
73
+ expect(openUrlInNewTab).not.toHaveBeenCalled();
74
+
75
+ notification?.action?.onClick();
76
+
77
+ expect(openUrlInNewTab).toHaveBeenCalledWith('blob:labels');
78
+ expect(labelsNotification()).toBeUndefined();
79
+ });
80
+
81
+ it('downloads the pdf once it is ready when the output is download', async () => {
82
+ fetchLabelPdf.mockResolvedValueOnce({data: 'cGRm'});
83
+
84
+ await print('download');
85
+
86
+ expect(downloadFileFromUrl).toHaveBeenCalledWith('blob:labels', 'myparcel-labels.pdf');
87
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:labels');
88
+ expect(labelsNotification()).toBeUndefined();
89
+ });
90
+
91
+ it('shows an error when the pdf is not ready in time', async () => {
92
+ fetchLabelPdf.mockResolvedValue({pending: true});
93
+
94
+ const promise = print('open');
95
+
96
+ await vi.advanceTimersByTimeAsync(11 * 60 * 1000);
97
+ await promise;
98
+
99
+ const notification = labelsNotification();
100
+
101
+ expect(notification?.variant).toBe(Variant.Error);
102
+ expect(notification?.loading).toBeFalsy();
103
+ expect(notification?.action).toBeUndefined();
104
+ });
105
+ });
106
+
107
+ describe('openOrPrintPdf without a response', () => {
108
+ beforeEach(() => {
109
+ setActivePinia(createPinia());
110
+ showLabelsLoading();
111
+ });
112
+
113
+ it('removes the loading notification when the print request failed', async () => {
114
+ // @ts-expect-error the handler returns nothing when the request failed
115
+ await openOrPrintPdf({response: undefined, parameters: {orderIds: ['1']}});
116
+
117
+ expect(labelsNotification()).toBeUndefined();
118
+ });
119
+ });