1 # Order Adjustment Versioning Implementation Plan
2
3 ## Overview
4
5 This plan implements versioning for `order_shipping_method_adjustment` (similar to `order_line_item_adjustment`) and adds explicit deletion of current version adjustments when reverting an order to its previous version.
6
7 ## Current State Analysis
8
9 ### Order Line Item Adjustment Versioning
10
11 - **Model**: `packages/modules/order/src/models/line-item-adjustment.ts:7`
12
13 - Has `version: model.number().default(1)` field
14 - Belongs to `OrderLineItem` via `item` relationship
15
16 - **Migration**: `packages/modules/order/src/migrations/Migration20251016160403.ts`
17
18 - Added `version` column with default value 1
19 - Updates existing adjustments to match their associated `OrderItem` version
20
21 - **Version Creation Logic**: `packages/modules/order/src/utils/apply-order-changes.ts:99-111`
22 - When `version > order.version`, new adjustments are created with the new version number
23 - Adjustments are created via `lineItemAdjustmentsToCreate` array
24
25 ### Order Shipping Method Adjustment Current State
26
27 - **Model**: `packages/modules/order/src/models/shipping-method-adjustment.ts`
28 - **NO version field currently**
29 - Belongs to `OrderShippingMethod` via `shipping_method` relationship
30
31 ### Order Revert Implementation
32
33 - **Location**: `packages/modules/order/src/services/order-module-service.ts:3203-3330`
34 - **What Gets Soft-Deleted**:
35
36 - Order Changes (by `order_id` + `version`)
37 - Order Change Actions (by `order_id` + `version`)
38 - Order Summary (by `order_id` + `version`)
39 - Order Items (by `order_id` + `version`)
40 - Order Shipping (by `order_id` + `version`)
41 - Order Credit Lines (by `order_id` + `version`)
42 - Returns (by `order_id` + `order_version`)
43
44 - **What Is NOT Handled**:
45 - Line item adjustments (NOT deleted during revert)
46 - Shipping method adjustments (NOT deleted during revert)
47
48 ### Key Discoveries
49
50 1. **Cascade deletes don't apply**: The cascade delete on `OrderLineItem` only triggers when `OrderLineItem` itself is deleted, NOT when `OrderItem` is soft-deleted. Since revert soft-deletes `OrderItem` (the versioned entity), adjustments remain orphaned.
51
52 2. **Shipping method adjustments have no version awareness**: They are created but never versioned or cleaned up during order changes.
53
54 3. **The `compute-adjustments-for-preview` workflow only handles line item adjustments**: `packages/core/core-flows/src/order/workflows/compute-adjustments-for-preview.ts:134-153` - it doesn't create `SHIPPING_ADJUSTMENTS_REPLACE` actions.
55
56 ## Desired End State
57
58 1. `order_shipping_method_adjustment` table has a `version` column with default value 1
59 2. When order changes are confirmed, shipping method adjustments are created with the new version number
60 3. When reverting an order (`revertLastVersion`), both line item adjustments AND shipping method adjustments for the current version are soft-deleted
61 4. A `SHIPPING_ADJUSTMENTS_REPLACE` change action type exists, mirroring the `ITEM_ADJUSTMENTS_REPLACE` pattern
62 5. The `compute-adjustments-for-preview` workflow handles shipping method adjustments in addition to line item adjustments
63
64 ### Verification
65
66 - Migration applies cleanly
67 - Existing adjustments are updated with correct versions
68 - New adjustments are created with correct version during order change confirmation
69 - Reverting an order deletes adjustments for the current version only
70 - Previous version adjustments remain intact
71 - Shipping method adjustments are computed and previewed during order changes when `carry_over_promotions` is enabled
72
73 ## What We're NOT Doing
74
75 - Adding version field to GraphQL schema (keeping it internal like line item adjustment version)
76
77 ## Implementation Approach
78
79 The implementation follows the exact same pattern as the existing line item adjustment versioning:
80
81 1. Add `version` field to shipping method adjustment model
82 2. Create migration to add column and backfill existing data
83 3. Update `apply-order-changes.ts` to include shipping method adjustments with version
84 4. Update `revertLastChange_` to delete adjustments for the current version
85
86 ## Phase 1: Add Version Field to Shipping Method Adjustment Model
87
88 ### Overview
89
90 Add the `version` field to the `OrderShippingMethodAdjustment` model, matching the pattern used in `OrderLineItemAdjustment`.
91
92 ### Changes Required:
93
94 #### 1. Model Definition
95
96 **File**: `packages/modules/order/src/models/shipping-method-adjustment.ts`
97 **Changes**: Add `version` field
98
99 ```typescript
100 const _OrderShippingMethodAdjustment = model.define(
101 {
102 tableName: "order_shipping_method_adjustment",
103 name: "OrderShippingMethodAdjustment",
104 },
105 {
106 id: model.id({ prefix: "ordsmadj" }).primaryKey(),
107 version: model.number().default(1), // ADD THIS LINE
108 description: model.text().nullable(),
109 promotion_id: model.text().nullable(),
110 code: model.text().nullable(),
111 amount: model.bigNumber(),
112 provider_id: model.text().nullable(),
113 shipping_method: model.belongsTo<() => typeof OrderShippingMethod>(
114 () => OrderShippingMethod,
115 {
116 mappedBy: "adjustments",
117 }
118 ),
119 }
120 )
121 // ... rest unchanged
122 ```
123
124 ### Success Criteria:
125
126 #### Automated Verification:
127
128 - [x] TypeScript compilation passes: `yarn workspace @medusajs/order build`
129 - [x] Unit tests pass: `yarn workspace @medusajs/order test`
130
131 #### Manual Verification:
132
133 - [x] Model change appears correct in source
134
135 **Implementation Note**: After completing this phase and all automated verification passes, proceed to Phase 2 and Phase 3.
136
137 ---
138
139 ## Phase 2: Create Schema Migration
140
141 ### Overview
142
143 Create a schema migration to add the `version` column and indexes to the `order_shipping_method_adjustment` table.
144
145 ### Changes Required:
146
147 #### 1. Create Schema Migration
148
149 **Command**: Run migration creation script in the order module
150
151 ```bash
152 cd packages/modules/order
153 yarn migration:create
154 ```
155
156 This will create a new migration file based on the model changes from Phase 1.
157
158 ### Success Criteria:
159
160 #### Automated Verification:
161
162 - [x] Migration creates correctly: `cd packages/modules/order && yarn migration:create`
163
164 #### Manual Verification:
165
166 - [x] Verify the migration SQL is correct by reviewing the generated migration
167 - [x] Migration applies cleanly on test database
168
169 **Implementation Note**:
170
171 - First, ensure Phase 1 (model changes) is complete and compiled successfully
172 - Run `yarn migration:create` in the order module directory to create the schema migration
173 - The generator will create a migration file with a timestamp and the statements necessary to represent the model defined
174 - Do NOT add data backfill logic here - that will be handled in Phase 3 with a data migration script
175
176 ---
177
178 ## Phase 3: Create Data Migration Script
179
180 ### Overview
181
182 Create a data migration script to backfill existing `order_shipping_method_adjustment` records with the correct version based on their associated order shipping records.
183
184 ### Changes Required:
185
186 #### 1. Create Data Migration Script
187
188 **File**: `packages/medusa/src/migration-scripts/backfill-shipping-adjustment-versions.ts` (new file)
189 **Changes**: Create data migration script
190
191 ````typescript
192 import { MedusaContainer } from "@medusajs/framework/types"
193 import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
194
195 /**
196 * Data migration to backfill version field for existing order_shipping_method_adjustment records.
197 * Sets adjustment versions based on the latest order_shipping version for their associated shipping method.
198 */
199 ```typescript
200 import { MedusaContainer } from "@medusajs/framework/types"
201 import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
202
203 export default async function backfillShippingAdjustmentVersions({
204 container,
205 }: {
206 container: MedusaContainer
207 }) {
208 const knex = container.resolve(ContainerRegistrationKeys.PG_CONNECTION)
209 const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
210
211 // Execute the backfill query using knex
212 await knex.transaction((trx) => {
213 return trx.raw(`
214 WITH latest_order_shipping_version AS (
215 SELECT
216 os.shipping_method_id AS shipping_method_id,
217 MAX(os.version) AS version
218 FROM "order_shipping" os
219 GROUP BY os.shipping_method_id
220 )
221 UPDATE "order_shipping_method_adjustment" osma
222 SET version = losv.version
223 FROM latest_order_shipping_version losv
224 WHERE osma.shipping_method_id = losv.shipping_method_id
225 AND osma.version <> losv.version;
226 `)
227 }
228
229 logger.info("Successfully backfilled shipping method adjustment versions")
230 }
231 ````
232
233 ### Success Criteria:
234
235 #### Automated Verification:
236
237 - [x] TypeScript compilation passes: `yarn workspace @medusajs/medusa build`
238 - [x] Data migration can be executed without errors
239
240 #### Manual Verification:
241
242 - [x] Run the data migration on a test database with existing shipping method adjustments
243 - [x] Verify adjustments are updated with correct versions matching their associated order shipping records
244
245 **Implementation Note**:
246
247 - Data migration scripts are executed separately from schema migrations
248 - The script is guaranteed to be run only once by Medusa
249 - Test on a copy of production data before deploying
250 - The SQL query uses a CTE to find the latest order_shipping version for each shipping method, then updates adjustments accordingly
251
252 ---
253
254 ## Phase 4: Update Apply Order Changes to Handle Shipping Method Adjustment Versioning
255
256 ### Overview
257
258 Update the `applyChangesToOrder` function to create shipping method adjustments with the correct version, similar to how line item adjustments are handled.
259
260 ### Changes Required:
261
262 #### 1. Apply Order Changes Utility
263
264 **File**: `packages/modules/order/src/utils/apply-order-changes.ts`
265 **Changes**: Add `shippingMethodAdjustmentsToCreate` array and populate it with versioned adjustments
266
267 ```typescript
268 // Add to imports if needed
269 import {
270 CreateOrderLineItemAdjustmentDTO,
271 CreateOrderShippingMethodAdjustmentDTO, // ADD THIS
272 InferEntityType,
273 OrderChangeActionDTO,
274 OrderDTO,
275 } from "@medusajs/framework/types"
276
277 // Add new array declaration around line 36
278 const lineItemAdjustmentsToCreate: CreateOrderLineItemAdjustmentDTO[] = []
279 const shippingMethodAdjustmentsToCreate: CreateOrderShippingMethodAdjustmentDTO[] =
280 [] // ADD THIS
281
282 // Inside the shipping method handling block (around lines 138-170), add adjustment handling:
283 // After line 168 (after shippingMethodsToUpsert.push(sm)), add:
284 if (version > order.version) {
285 shippingMethod_.adjustments?.forEach((adjustment) => {
286 shippingMethodAdjustmentsToCreate.push({
287 shipping_method_id: associatedMethodId,
288 version,
289 amount: adjustment.amount,
290 description: adjustment.description,
291 promotion_id: adjustment.promotion_id,
292 code: adjustment.code,
293 })
294 })
295 }
296
297 // Update the return statement to include the new array:
298 return {
299 lineItemAdjustmentsToCreate,
300 shippingMethodAdjustmentsToCreate, // ADD THIS
301 itemsToUpsert,
302 creditLinesToUpsert,
303 shippingMethodsToUpsert,
304 summariesToUpsert,
305 orderToUpdate,
306 calculatedOrders,
307 }
308 ```
309
310 #### 2. Update Order Module Service
311
312 **File**: `packages/modules/order/src/services/order-module-service.ts`
313 **Changes**: Handle `shippingMethodAdjustmentsToCreate` in the confirm flow
314
315 Find where `lineItemAdjustmentsToCreate` is used (around line 3616-3623) and add similar handling for shipping method adjustments:
316
317 ```typescript
318 // Around line 3616-3623, add after the lineItemAdjustmentsToCreate block:
319 lineItemAdjustmentsToCreate.length
320 ? this.orderLineItemAdjustmentService_.create(
321 lineItemAdjustmentsToCreate,
322 sharedContext
323 )
324 : null,
325 shippingMethodAdjustmentsToCreate.length
326 ? this.orderShippingMethodAdjustmentService_.create(
327 shippingMethodAdjustmentsToCreate,
328 sharedContext
329 )
330 : null,
331 ```
332
333 Also update the destructuring where `applyChangesToOrder` is called to include `shippingMethodAdjustmentsToCreate`.
334
335 **Note**: The `includeTaxLinesAndAdjustmentsToPreview` function was also updated to:
336
337 - Accept `shippingMethodAdjustmentsToCreate` as a parameter
338 - Filter and assign virtual shipping method adjustments to the corresponding shipping methods in the preview
339 - This ensures shipping method adjustments appear in order change previews before being persisted
340
341 ### Success Criteria:
342
343 #### Automated Verification:
344
345 - [x] TypeScript compilation passes: `yarn workspace @medusajs/order build`
346 - [x] Unit tests pass: `yarn workspace @medusajs/order test`
347
348 #### Manual Verification:
349
350 - [x] Create an order with shipping method adjustments (promotions)
351 - [x] Make an order change (edit, exchange, etc.)
352 - [x] Verify new shipping method adjustments are created with the new version number
353
354 **Implementation Note**: After completing this phase and all automated verification passes, proceed to Phase 5.
355
356 ---
357
358 ## Phase 5: Update Revert to Delete Current Version Adjustments
359
360 ### Overview
361
362 Update the `revertLastChange_` method to explicitly delete both line item adjustments and shipping method adjustments for the current version being reverted.
363
364 ### Changes Required:
365
366 #### 1. Order Module Service - Revert Method
367
368 **File**: `packages/modules/order/src/services/order-module-service.ts`
369 **Changes**: Add adjustment deletion to `revertLastChange_` method (around line 3286, after Order Shipping deletion)
370
371 ```typescript
372 // Add after the Order Shipping block (around line 3286) and before Order Credit Lines:
373
374 // Line Item Adjustments
375 // First, get the item_ids from the orderItems we already queried
376 const itemIds = orderItems.map((orderItem) => orderItem.item_id)
377
378 if (itemIds.length) {
379 const lineItemAdjustments = await this.orderLineItemAdjustmentService_.list(
380 {
381 item_id: itemIds,
382 version: currentVersion,
383 },
384 { select: ["id"] },
385 sharedContext
386 )
387 const lineItemAdjustmentIds = lineItemAdjustments.map((adj) => adj.id)
388
389 if (lineItemAdjustmentIds.length) {
390 updatePromises.push(
391 this.orderLineItemAdjustmentService_.softDelete(
392 lineItemAdjustmentIds,
393 sharedContext
394 )
395 )
396 }
397 }
398
399 // Shipping Method Adjustments
400 // Get the shipping_method_ids from the orderShippings we already queried
401 const shippingMethodIds = orderShippings.map(
402 (orderShipping) => orderShipping.shipping_method_id
403 )
404
405 if (shippingMethodIds.length) {
406 const shippingMethodAdjustments =
407 await this.orderShippingMethodAdjustmentService_.list(
408 {
409 shipping_method_id: shippingMethodIds,
410 version: currentVersion,
411 },
412 { select: ["id"] },
413 sharedContext
414 )
415 const shippingMethodAdjustmentIds = shippingMethodAdjustments.map(
416 (adj) => adj.id
417 )
418
419 if (shippingMethodAdjustmentIds.length) {
420 updatePromises.push(
421 this.orderShippingMethodAdjustmentService_.softDelete(
422 shippingMethodAdjustmentIds,
423 sharedContext
424 )
425 )
426 }
427 }
428 ```
429
430 ### Success Criteria:
431
432 #### Automated Verification:
433
434 - [x] TypeScript compilation passes: `yarn workspace @medusajs/order build`
435 - [x] Unit tests pass: `yarn workspace @medusajs/order test`
436 - [x] Integration tests pass: `yarn test:integration:modules -- --testPathPattern=order`
437
438 #### Manual Verification:
439
440 - [x] Create an order with line item and shipping method adjustments
441 - [x] Make an order change to increment version
442 - [x] Revert the order
443 - [x] Verify adjustments for the reverted version are soft-deleted
444 - [x] Verify adjustments for previous versions remain intact
445
446 **Implementation Note**: The query uses `item_id` and `shipping_method_id` arrays extracted from the already-queried `orderItems` and `orderShippings`. This approach is efficient and leverages the existing queries in the revert method.
447
448 ---
449
450 ## Phase 6: Update Type Definitions
451
452 ### Overview
453
454 Update the TypeScript type definitions to include the `version` field in shipping method adjustment DTOs.
455
456 ### Changes Required:
457
458 #### 1. Create Order Shipping Method Adjustment DTO
459
460 **File**: `packages/core/types/src/order/mutations.ts`
461 **Changes**: Add `version` field to `CreateOrderShippingMethodAdjustmentDTO`
462
463 Around line 813-843, update the interface:
464
465 ```typescript
466 export interface CreateOrderShippingMethodAdjustmentDTO {
467 /**
468 * The associated shipping method's ID.
469 */
470 shipping_method_id: string
471
472 /**
473 * The code of the adjustment.
474 */
475 code: string
476
477 /**
478 * The amount of the adjustment.
479 */
480 amount: BigNumberInput
481
482 /**
483 * The description of the adjustment.
484 */
485 description?: string
486
487 /**
488 * The associated promotion's ID.
489 */
490 promotion_id?: string
491
492 /**
493 * The associated provider's ID.
494 */
495 provider_id?: string
496
497 /**
498 * The version of the adjustment.
499 */
500 version?: number // ADD THIS
501 }
502 ```
503
504 ### Success Criteria:
505
506 #### Automated Verification:
507
508 - [ ] TypeScript compilation passes: `yarn workspace @medusajs/types build`
509 - [ ] Dependent packages compile: `yarn build`
510
511 #### Manual Verification:
512
513 - [ ] Type definitions are correct and consistent with line item adjustment pattern
514
515 ---
516
517 ## Phase 7: Add Integration Tests
518
519 ### Overview
520
521 Add integration tests to verify the versioning and revert behavior for both line item and shipping method adjustments.
522
523 ### Changes Required:
524
525 #### 1. Integration Test File
526
527 **File**: `packages/modules/order/integration-tests/__tests__/order-adjustment-versioning.spec.ts`
528 **Changes**: Create new test file or add to existing `order-edit.spec.ts`
529
530 ```typescript
531 // Test cases to add:
532 describe("Order Adjustment Versioning", () => {
533 it("should create line item adjustments with version when order version increases", async () => {
534 // Create order with adjustments
535 // Confirm order change (increment version)
536 // Verify new adjustments have correct version
537 })
538
539 it("should create shipping method adjustments with version when order version increases", async () => {
540 // Create order with shipping method adjustments
541 // Confirm order change (increment version)
542 // Verify new shipping method adjustments have correct version
543 })
544
545 it("should delete current version line item adjustments on revert", async () => {
546 // Create order
547 // Confirm order change (create new version adjustments)
548 // Revert
549 // Verify current version adjustments are soft-deleted
550 // Verify previous version adjustments remain
551 })
552
553 it("should delete current version shipping method adjustments on revert", async () => {
554 // Create order with shipping
555 // Confirm order change (create new version adjustments)
556 // Revert
557 // Verify current version adjustments are soft-deleted
558 // Verify previous version adjustments remain
559 })
560 })
561 ```
562
563 ### Success Criteria:
564
565 #### Automated Verification:
566
567 - [ ] New integration tests pass: `yarn test:integration:modules -- --testPathPattern=order-adjustment-versioning`
568 - [ ] Existing integration tests still pass: `yarn test:integration:modules -- --testPathPattern=order`
569
570 #### Manual Verification:
571
572 - [ ] Tests cover the key scenarios outlined above
573 - [ ] Test assertions are comprehensive
574
575 ---
576
577 ## Phase 8: Add SHIPPING_ADJUSTMENTS_REPLACE Action Type and Update Workflow
578
579 ### Overview
580
581 Add the `SHIPPING_ADJUSTMENTS_REPLACE` change action type to handle shipping method adjustment replacement during order changes. This mirrors the existing `ITEM_ADJUSTMENTS_REPLACE` pattern and enables proper promotion recalculation for shipping methods when the `carry_over_promotions` flag is enabled.
582
583 ### Changes Required:
584
585 #### 1. Add to ChangeActionType Enum
586
587 **File**: `packages/core/utils/src/order/order-change-action.ts`
588 **Changes**: Add `SHIPPING_ADJUSTMENTS_REPLACE` to the enum
589
590 ```typescript
591 export enum ChangeActionType {
592 FULFILL_ITEM = "FULFILL_ITEM",
593 DELIVER_ITEM = "DELIVER_ITEM",
594 CANCEL_ITEM_FULFILLMENT = "CANCEL_ITEM_FULFILLMENT",
595 ITEM_ADD = "ITEM_ADD",
596 ITEM_REMOVE = "ITEM_REMOVE",
597 ITEM_UPDATE = "ITEM_UPDATE",
598 RECEIVE_DAMAGED_RETURN_ITEM = "RECEIVE_DAMAGED_RETURN_ITEM",
599 RECEIVE_RETURN_ITEM = "RECEIVE_RETURN_ITEM",
600 RETURN_ITEM = "RETURN_ITEM",
601 CANCEL_RETURN_ITEM = "CANCEL_RETURN_ITEM",
602 SHIPPING_ADD = "SHIPPING_ADD",
603 SHIPPING_REMOVE = "SHIPPING_REMOVE",
604 SHIPPING_UPDATE = "SHIPPING_UPDATE",
605 SHIP_ITEM = "SHIP_ITEM",
606 WRITE_OFF_ITEM = "WRITE_OFF_ITEM",
607 REINSTATE_ITEM = "REINSTATE_ITEM",
608 TRANSFER_CUSTOMER = "TRANSFER_CUSTOMER",
609 UPDATE_ORDER_PROPERTIES = "UPDATE_ORDER_PROPERTIES",
610 CREDIT_LINE_ADD = "CREDIT_LINE_ADD",
611 PROMOTION_ADD = "PROMOTION_ADD",
612 PROMOTION_REMOVE = "PROMOTION_REMOVE",
613 ITEM_ADJUSTMENTS_REPLACE = "ITEM_ADJUSTMENTS_REPLACE",
614 SHIPPING_ADJUSTMENTS_REPLACE = "SHIPPING_ADJUSTMENTS_REPLACE", // ADD THIS
615 }
616 ```
617
618 #### 2. Add to ChangeActionType Type Definition
619
620 **File**: `packages/core/types/src/order/common.ts`
621 **Changes**: Add `SHIPPING_ADJUSTMENTS_REPLACE` to the union type
622
623 Around line 33, update the type:
624
625 ```typescript
626 export type ChangeActionType =
627 | "CANCEL_RETURN_ITEM"
628 | "FULFILL_ITEM"
629 | "DELIVER_ITEM"
630 // ... other types ...
631 | "ITEM_ADJUSTMENTS_REPLACE"
632 | "SHIPPING_ADJUSTMENTS_REPLACE" // ADD THIS
633 ```
634
635 #### 3. Create Action Handler
636
637 **File**: `packages/modules/order/src/utils/actions/shipping-adjustments-replace.ts` (new file)
638 **Changes**: Create handler mirroring `item-adjustments-replace.ts`
639
640 ```typescript
641 import { ChangeActionType, MedusaError } from "@medusajs/framework/utils"
642 import { OrderChangeProcessing } from "../calculate-order-change"
643 import { setActionReference } from "../set-action-reference"
644
645 OrderChangeProcessing.registerActionType(
646 ChangeActionType.SHIPPING_ADJUSTMENTS_REPLACE,
647 {
648 operation({ action, currentOrder, options }) {
649 let existing = currentOrder.shipping_methods.find(
650 (method) => method.id === action.details.reference_id
651 )
652
653 if (!existing) {
654 return
655 }
656
657 existing.adjustments = action.details.adjustments ?? []
658
659 setActionReference(existing, action, options)
660 },
661 validate({ action }) {
662 const refId = action.details?.reference_id
663
664 if (!action.details.adjustments) {
665 throw new MedusaError(
666 MedusaError.Types.INVALID_DATA,
667 `Adjustments of shipping method ${refId} must exist.`
668 )
669 }
670 },
671 }
672 )
673 ```
674
675 #### 4. Export Action Handler
676
677 **File**: `packages/modules/order/src/utils/actions/index.ts`
678 **Changes**: Add export for new action handler
679
680 ```typescript
681 export * from "./cancel-item-fulfillment"
682 export * from "./cancel-return"
683 export * from "./change-shipping-address"
684 export * from "./credit-line-add"
685 export * from "./deliver-item"
686 export * from "./fulfill-item"
687 export * from "./item-add"
688 export * from "./item-adjustments-replace"
689 export * from "./item-remove"
690 export * from "./item-update"
691 export * from "./promotion-add"
692 export * from "./promotion-remove"
693 export * from "./receive-damaged-return-item"
694 export * from "./receive-return-item"
695 export * from "./reinstate-item"
696 export * from "./return-item"
697 export * from "./ship-item"
698 export * from "./shipping-add"
699 export * from "./shipping-adjustments-replace" // ADD THIS
700 export * from "./shipping-remove"
701 export * from "./shipping-update"
702 export * from "./transfer-customer"
703 export * from "./write-off-item"
704 ```
705
706 #### 5. Update compute-adjustments-for-preview Workflow
707
708 **File**: `packages/core/core-flows/src/order/workflows/compute-adjustments-for-preview.ts`
709 **Changes**: Update the workflow to also create `SHIPPING_ADJUSTMENTS_REPLACE` actions
710
711 ```typescript
712 import {
713 ComputeActionContext,
714 ComputeActionShippingLine,
715 OrderChangeDTO,
716 OrderDTO,
717 PromotionDTO,
718 } from "@medusajs/framework/types"
719 import { ChangeActionType } from "@medusajs/framework/utils"
720 import {
721 createWorkflow,
722 transform,
723 when,
724 WorkflowData,
725 } from "@medusajs/framework/workflows-sdk"
726 import {
727 getActionsToComputeFromPromotionsStep,
728 prepareAdjustmentsFromPromotionActionsStep,
729 } from "../../cart"
730 import { previewOrderChangeStep } from "../steps/preview-order-change"
731 import { createOrderChangeActionsWorkflow } from "./create-order-change-actions"
732 import {
733 deleteOrderChangeActionsStep,
734 listOrderChangeActionsByTypeStep,
735 } from "../steps"
736
737 // ... type definitions unchanged ...
738
739 export const computeAdjustmentsForPreviewWorkflow = createWorkflow(
740 computeAdjustmentsForPreviewWorkflowId,
741 function (input: WorkflowData<ComputeAdjustmentsForPreviewWorkflowInput>) {
742 const previewedOrder = previewOrderChangeStep(input.order.id)
743
744 when(
745 { order: input.order },
746 ({ order }) =>
747 !!order.promotions.length && !!input.orderChange.carry_over_promotions
748 ).then(() => {
749 const actionsToComputeContext = transform(
750 { previewedOrder, order: input.order },
751 ({ previewedOrder, order }) => {
752 return {
753 currency_code: order.currency_code,
754 items: previewedOrder.items.map((item) => ({
755 ...item,
756 product: { id: item.product_id },
757 })),
758 shipping_methods:
759 previewedOrder.shipping_methods as unknown as ComputeActionShippingLine[],
760 } as ComputeActionContext
761 }
762 )
763
764 const orderPromotions = transform({ order: input.order }, ({ order }) => {
765 return order.promotions
766 .map((p) => p.code)
767 .filter((p) => p !== undefined)
768 })
769
770 const actions = getActionsToComputeFromPromotionsStep({
771 computeActionContext: actionsToComputeContext,
772 promotionCodesToApply: orderPromotions,
773 options: {
774 skip_usage_limit_checks: true,
775 },
776 })
777
778 // UPDATE: Destructure both lineItemAdjustmentsToCreate AND shippingMethodAdjustmentsToCreate
779 const { lineItemAdjustmentsToCreate, shippingMethodAdjustmentsToCreate } =
780 prepareAdjustmentsFromPromotionActionsStep({ actions })
781
782 // UPDATE: Create actions for both item and shipping method adjustments
783 const orderChangeActionAdjustmentsInput = transform(
784 {
785 order: input.order,
786 previewedOrder,
787 orderChange: input.orderChange,
788 lineItemAdjustmentsToCreate,
789 shippingMethodAdjustmentsToCreate,
790 },
791 ({
792 order,
793 previewedOrder,
794 orderChange,
795 lineItemAdjustmentsToCreate,
796 shippingMethodAdjustmentsToCreate,
797 }) => {
798 // Create ITEM_ADJUSTMENTS_REPLACE actions for each item
799 const itemActions = previewedOrder.items.map((item) => {
800 const itemAdjustments = lineItemAdjustmentsToCreate.filter(
801 (adjustment) => adjustment.item_id === item.id
802 )
803
804 return {
805 order_change_id: orderChange.id,
806 order_id: order.id,
807 exchange_id: orderChange.exchange_id ?? undefined,
808 claim_id: orderChange.claim_id ?? undefined,
809 return_id: orderChange.return_id ?? undefined,
810 version: orderChange.version,
811 action: ChangeActionType.ITEM_ADJUSTMENTS_REPLACE,
812 details: {
813 reference_id: item.id,
814 adjustments: itemAdjustments,
815 },
816 }
817 })
818
819 // Create SHIPPING_ADJUSTMENTS_REPLACE actions for each shipping method
820 const shippingActions = previewedOrder.shipping_methods.map(
821 (shippingMethod) => {
822 const shippingAdjustments =
823 shippingMethodAdjustmentsToCreate.filter(
824 (adjustment) =>
825 adjustment.shipping_method_id === shippingMethod.id
826 )
827
828 return {
829 order_change_id: orderChange.id,
830 order_id: order.id,
831 exchange_id: orderChange.exchange_id ?? undefined,
832 claim_id: orderChange.claim_id ?? undefined,
833 return_id: orderChange.return_id ?? undefined,
834 version: orderChange.version,
835 action: ChangeActionType.SHIPPING_ADJUSTMENTS_REPLACE,
836 details: {
837 reference_id: shippingMethod.id,
838 adjustments: shippingAdjustments,
839 },
840 }
841 }
842 )
843
844 return [...itemActions, ...shippingActions]
845 }
846 )
847
848 createOrderChangeActionsWorkflow
849 .runAsStep({ input: orderChangeActionAdjustmentsInput })
850 .config({ name: "order-change-action-adjustments-input" })
851 })
852
853 // UPDATE: When carry_over_promotions is false, delete BOTH action types
854 when(
855 { order: previewedOrder },
856 ({ order }) => !order.order_change.carry_over_promotions
857 ).then(() => {
858 const itemActionIds = listOrderChangeActionsByTypeStep({
859 order_change_id: input.orderChange.id,
860 action_type: ChangeActionType.ITEM_ADJUSTMENTS_REPLACE,
861 })
862
863 deleteOrderChangeActionsStep({ ids: itemActionIds })
864 })
865
866 when(
867 { order: previewedOrder },
868 ({ order }) => !order.order_change.carry_over_promotions
869 ).then(() => {
870 const shippingActionIds = listOrderChangeActionsByTypeStep({
871 order_change_id: input.orderChange.id,
872 action_type: ChangeActionType.SHIPPING_ADJUSTMENTS_REPLACE,
873 })
874
875 deleteOrderChangeActionsStep({ ids: shippingActionIds })
876 })
877 }
878 )
879 ```
880
881 **Note**: The workflow now:
882
883 1. Destructures `shippingMethodAdjustmentsToCreate` from `prepareAdjustmentsFromPromotionActionsStep` (already computed but not used before)
884 2. Creates `SHIPPING_ADJUSTMENTS_REPLACE` actions for each shipping method in addition to item actions
885 3. Deletes both `ITEM_ADJUSTMENTS_REPLACE` and `SHIPPING_ADJUSTMENTS_REPLACE` actions when `carry_over_promotions` is disabled
886
887 ### Success Criteria:
888
889 #### Automated Verification:
890
891 - [x] TypeScript compilation passes: `yarn workspace @medusajs/utils build`
892 - [x] TypeScript compilation passes: `yarn workspace @medusajs/types build`
893 - [x] TypeScript compilation passes: `yarn workspace @medusajs/order build`
894 - [x] TypeScript compilation passes: `yarn workspace @medusajs/core-flows build`
895 - [x] Unit tests pass: `yarn workspace @medusajs/order test`
896 - [x] Integration tests pass: `yarn test:integration:http -- --testPathPattern=order-edit`
897
898 #### Manual Verification:
899
900 - [x] Create an order with both line item and shipping promotions
901 - [x] Start an order edit with `carry_over_promotions: true`
902 - [x] Add a new item to the order edit
903 - [x] Preview the order change and verify shipping method adjustments are included
904 - [x] Confirm the order change
905 - [x] Verify shipping method adjustments are persisted with correct version
906 - [x] Toggle `carry_over_promotions` to false and verify both adjustment types are removed from preview
907
908 **Implementation Note**:
909
910 - The `prepareAdjustmentsFromPromotionActionsStep` already computes `shippingMethodAdjustmentsToCreate` but it was not being used in the workflow
911 - The action handler (`shipping-adjustments-replace.ts`) mirrors `item-adjustments-replace.ts` exactly, just operating on `shipping_methods` instead of `items`
912 - The workflow update adds shipping method handling alongside the existing item handling, maintaining backwards compatibility
913
914 ---
915
916 ## Testing Strategy
917
918 ### Unit Tests
919
920 - Model field validation for `version` on shipping method adjustment
921 - Type checking for new DTO fields
922 - Action handler validation for `SHIPPING_ADJUSTMENTS_REPLACE`
923
924 ### Integration Tests
925
926 - Order creation with adjustments (both types)
927 - Order change confirmation creates versioned adjustments
928 - Order revert deletes current version adjustments
929 - Multiple version changes maintain correct adjustment history
930 - `SHIPPING_ADJUSTMENTS_REPLACE` action correctly replaces shipping method adjustments during order change processing
931 - `carry_over_promotions` flag correctly includes/excludes shipping method adjustments in preview
932
933 ### Manual Testing Steps
934
935 1. Create an order with a promotion that applies to both line items and shipping
936 2. Apply an order edit that triggers adjustment recalculation
937 3. Verify new adjustments are created with version 2
938 4. Revert the order edit
939 5. Verify version 2 adjustments are soft-deleted
940 6. Verify version 1 adjustments remain intact
941 7. Test `carry_over_promotions: true` - verify shipping method adjustments appear in order change preview
942 8. Test `carry_over_promotions: false` - verify shipping method adjustments are not carried over
943
944 ## Performance Considerations
945
946 - The revert operation now includes additional database queries for adjustments
947 - Database indexes on the `version` column have been added for both adjustment tables (see Phase 2) to optimize version-based queries
948 - The backfill migration may be slow on large datasets with many adjustments - monitor performance in production-like environments
949
950 ## Migration Notes
951
952 - The migration adds a non-nullable column with a default value, which is safe for production
953 - Existing adjustments will be backfilled with the correct version based on their associated order shipping records
954 - If an adjustment has no associated order shipping record (orphaned), it will retain version 1
955
956 ## References
957
958 - Line item adjustment versioning migration: `packages/modules/order/src/migrations/Migration20251016160403.ts`
959 - Line item adjustment model: `packages/modules/order/src/models/line-item-adjustment.ts`
960 - Order revert implementation: `packages/modules/order/src/services/order-module-service.ts:3203-3330`
961 - Apply order changes utility: `packages/modules/order/src/utils/apply-order-changes.ts`
962 - Item adjustments replace action handler: `packages/modules/order/src/utils/actions/item-adjustments-replace.ts`
963 - ChangeActionType enum: `packages/core/utils/src/order/order-change-action.ts`
964 - Compute adjustments for preview workflow: `packages/core/core-flows/src/order/workflows/compute-adjustments-for-preview.ts`
965 - Prepare adjustments from promotion actions step: `packages/core/core-flows/src/cart/steps/prepare-adjustments-from-promotion-actions.ts`