adserver-dashboard 1.0.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 (525) hide show
  1. package/.ci/staging.yml +191 -0
  2. package/.dockerignore +117 -0
  3. package/.env +40 -0
  4. package/.env.staging +38 -0
  5. package/.gitlab-ci.yml +16 -0
  6. package/DEMO_STATUS.md +579 -0
  7. package/Dockerfile +61 -0
  8. package/Influence-MW-AdServer-12-02-2026/client/index.html +17 -0
  9. package/Influence-MW-AdServer-12-02-2026/client/public/favicon.png +0 -0
  10. package/Influence-MW-AdServer-12-02-2026/client/src/App.tsx +91 -0
  11. package/Influence-MW-AdServer-12-02-2026/client/src/components/advanced-map-drawer.tsx +1131 -0
  12. package/Influence-MW-AdServer-12-02-2026/client/src/components/ai-recommendation-panel.tsx +379 -0
  13. package/Influence-MW-AdServer-12-02-2026/client/src/components/app-sidebar.tsx +183 -0
  14. package/Influence-MW-AdServer-12-02-2026/client/src/components/auto-optimize-button.tsx +184 -0
  15. package/Influence-MW-AdServer-12-02-2026/client/src/components/availability-drawer.tsx +385 -0
  16. package/Influence-MW-AdServer-12-02-2026/client/src/components/brand-insights-panel.tsx +87 -0
  17. package/Influence-MW-AdServer-12-02-2026/client/src/components/create-agency-drawer.tsx +198 -0
  18. package/Influence-MW-AdServer-12-02-2026/client/src/components/create-brand-drawer.tsx +275 -0
  19. package/Influence-MW-AdServer-12-02-2026/client/src/components/creative-assignment.tsx +526 -0
  20. package/Influence-MW-AdServer-12-02-2026/client/src/components/data-table-toolbar.tsx +148 -0
  21. package/Influence-MW-AdServer-12-02-2026/client/src/components/data-table.tsx +158 -0
  22. package/Influence-MW-AdServer-12-02-2026/client/src/components/filter-drawer.tsx +356 -0
  23. package/Influence-MW-AdServer-12-02-2026/client/src/components/form-insights-panel.tsx +82 -0
  24. package/Influence-MW-AdServer-12-02-2026/client/src/components/geography-selector.tsx +699 -0
  25. package/Influence-MW-AdServer-12-02-2026/client/src/components/header-user-menu.tsx +178 -0
  26. package/Influence-MW-AdServer-12-02-2026/client/src/components/history-drawer.tsx +313 -0
  27. package/Influence-MW-AdServer-12-02-2026/client/src/components/inventory-availability-section.tsx +176 -0
  28. package/Influence-MW-AdServer-12-02-2026/client/src/components/inventory-format-drawer.tsx +173 -0
  29. package/Influence-MW-AdServer-12-02-2026/client/src/components/inventory-selector.tsx +401 -0
  30. package/Influence-MW-AdServer-12-02-2026/client/src/components/manual-inventory-drawer.tsx +368 -0
  31. package/Influence-MW-AdServer-12-02-2026/client/src/components/mapbox-map.tsx +368 -0
  32. package/Influence-MW-AdServer-12-02-2026/client/src/components/market-insights-panel.tsx +202 -0
  33. package/Influence-MW-AdServer-12-02-2026/client/src/components/media-owner-drawer.tsx +217 -0
  34. package/Influence-MW-AdServer-12-02-2026/client/src/components/metric-card.tsx +58 -0
  35. package/Influence-MW-AdServer-12-02-2026/client/src/components/page-header.tsx +27 -0
  36. package/Influence-MW-AdServer-12-02-2026/client/src/components/player-status-indicator.tsx +137 -0
  37. package/Influence-MW-AdServer-12-02-2026/client/src/components/poi-targeting-drawer.tsx +298 -0
  38. package/Influence-MW-AdServer-12-02-2026/client/src/components/recommendation-score-badge.tsx +102 -0
  39. package/Influence-MW-AdServer-12-02-2026/client/src/components/recommended-inventories-panel.tsx +248 -0
  40. package/Influence-MW-AdServer-12-02-2026/client/src/components/searchable-combobox.tsx +134 -0
  41. package/Influence-MW-AdServer-12-02-2026/client/src/components/signal-visualizations.tsx +407 -0
  42. package/Influence-MW-AdServer-12-02-2026/client/src/components/status-badge.tsx +35 -0
  43. package/Influence-MW-AdServer-12-02-2026/client/src/components/theme-provider.tsx +73 -0
  44. package/Influence-MW-AdServer-12-02-2026/client/src/components/theme-toggle.tsx +37 -0
  45. package/Influence-MW-AdServer-12-02-2026/client/src/components/traffic-slider.tsx +75 -0
  46. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/accordion.tsx +56 -0
  47. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/alert-dialog.tsx +139 -0
  48. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/alert.tsx +59 -0
  49. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/aspect-ratio.tsx +5 -0
  50. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/avatar.tsx +51 -0
  51. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/badge.tsx +38 -0
  52. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/breadcrumb.tsx +115 -0
  53. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/button.tsx +62 -0
  54. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/calendar.tsx +68 -0
  55. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/card.tsx +85 -0
  56. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/carousel.tsx +260 -0
  57. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/chart.tsx +365 -0
  58. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/checkbox.tsx +28 -0
  59. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/collapsible.tsx +11 -0
  60. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/command.tsx +151 -0
  61. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/context-menu.tsx +198 -0
  62. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/dialog.tsx +122 -0
  63. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/drawer.tsx +118 -0
  64. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/dropdown-menu.tsx +198 -0
  65. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/form.tsx +178 -0
  66. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/hover-card.tsx +29 -0
  67. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/input-otp.tsx +69 -0
  68. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/input.tsx +23 -0
  69. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/label.tsx +24 -0
  70. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/menubar.tsx +256 -0
  71. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/navigation-menu.tsx +128 -0
  72. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/pagination.tsx +117 -0
  73. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/popover.tsx +29 -0
  74. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/progress.tsx +28 -0
  75. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/radio-group.tsx +42 -0
  76. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/resizable.tsx +45 -0
  77. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/scroll-area.tsx +46 -0
  78. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/select.tsx +160 -0
  79. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/separator.tsx +29 -0
  80. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/sheet.tsx +140 -0
  81. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/sidebar.tsx +727 -0
  82. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/skeleton.tsx +15 -0
  83. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/slider.tsx +26 -0
  84. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/switch.tsx +27 -0
  85. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/table.tsx +117 -0
  86. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/tabs.tsx +53 -0
  87. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/textarea.tsx +22 -0
  88. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/toast.tsx +127 -0
  89. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/toaster.tsx +33 -0
  90. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/toggle-group.tsx +61 -0
  91. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/toggle.tsx +43 -0
  92. package/Influence-MW-AdServer-12-02-2026/client/src/components/ui/tooltip.tsx +30 -0
  93. package/Influence-MW-AdServer-12-02-2026/client/src/components/vendor-stores-modal.tsx +336 -0
  94. package/Influence-MW-AdServer-12-02-2026/client/src/components/venue-type-drawer.tsx +359 -0
  95. package/Influence-MW-AdServer-12-02-2026/client/src/components/venue-type-selector.tsx +436 -0
  96. package/Influence-MW-AdServer-12-02-2026/client/src/hooks/use-mobile.tsx +19 -0
  97. package/Influence-MW-AdServer-12-02-2026/client/src/hooks/use-toast.ts +191 -0
  98. package/Influence-MW-AdServer-12-02-2026/client/src/index.css +244 -0
  99. package/Influence-MW-AdServer-12-02-2026/client/src/lib/queryClient.ts +57 -0
  100. package/Influence-MW-AdServer-12-02-2026/client/src/lib/utils.ts +39 -0
  101. package/Influence-MW-AdServer-12-02-2026/client/src/lib/venue-taxonomy.ts +532 -0
  102. package/Influence-MW-AdServer-12-02-2026/client/src/main.tsx +5 -0
  103. package/Influence-MW-AdServer-12-02-2026/client/src/pages/assign-creative.tsx +781 -0
  104. package/Influence-MW-AdServer-12-02-2026/client/src/pages/content-hub.tsx +995 -0
  105. package/Influence-MW-AdServer-12-02-2026/client/src/pages/custom-pois.tsx +431 -0
  106. package/Influence-MW-AdServer-12-02-2026/client/src/pages/dashboard.tsx +620 -0
  107. package/Influence-MW-AdServer-12-02-2026/client/src/pages/deal-detail.tsx +1062 -0
  108. package/Influence-MW-AdServer-12-02-2026/client/src/pages/deal-form.tsx +1570 -0
  109. package/Influence-MW-AdServer-12-02-2026/client/src/pages/deals.tsx +716 -0
  110. package/Influence-MW-AdServer-12-02-2026/client/src/pages/edit-creative-assignment.tsx +1051 -0
  111. package/Influence-MW-AdServer-12-02-2026/client/src/pages/geotargeting.tsx +675 -0
  112. package/Influence-MW-AdServer-12-02-2026/client/src/pages/integrations.tsx +425 -0
  113. package/Influence-MW-AdServer-12-02-2026/client/src/pages/line-item-creatives.tsx +622 -0
  114. package/Influence-MW-AdServer-12-02-2026/client/src/pages/line-item-form.tsx +3132 -0
  115. package/Influence-MW-AdServer-12-02-2026/client/src/pages/line-items.tsx +530 -0
  116. package/Influence-MW-AdServer-12-02-2026/client/src/pages/not-found.tsx +21 -0
  117. package/Influence-MW-AdServer-12-02-2026/client/src/pages/proof-of-play-upload.tsx +479 -0
  118. package/Influence-MW-AdServer-12-02-2026/client/src/pages/proof-of-play.tsx +880 -0
  119. package/Influence-MW-AdServer-12-02-2026/client/src/pages/reports.tsx +235 -0
  120. package/Influence-MW-AdServer-12-02-2026/client/src/pages/settings.tsx +652 -0
  121. package/Influence-MW-AdServer-12-02-2026/client/src/pages/signal-form.tsx +1117 -0
  122. package/Influence-MW-AdServer-12-02-2026/client/src/pages/signals.tsx +366 -0
  123. package/Influence-MW-AdServer-12-02-2026/client/src/pages/tags.tsx +332 -0
  124. package/Influence-MW-AdServer-12-02-2026/client/src/pages/venues.tsx +381 -0
  125. package/Influence-MW-AdServer-12-02-2026/client/src/types/mapbox-gl-draw.d.ts +37 -0
  126. package/Influence-MW-AdServer-12-02-2026/client/src/types/react-simple-maps.d.ts +57 -0
  127. package/Influence-MW-AdServer-12-02-2026/components.json +20 -0
  128. package/Influence-MW-AdServer-12-02-2026/docs/PRD.md +3373 -0
  129. package/Influence-MW-AdServer-12-02-2026/docs/influence-feature-mapping.csv +498 -0
  130. package/Influence-MW-AdServer-12-02-2026/drizzle.config.ts +14 -0
  131. package/Influence-MW-AdServer-12-02-2026/package-lock.json +9672 -0
  132. package/Influence-MW-AdServer-12-02-2026/package.json +118 -0
  133. package/Influence-MW-AdServer-12-02-2026/postcss.config.js +6 -0
  134. package/Influence-MW-AdServer-12-02-2026/replit.md +91 -0
  135. package/Influence-MW-AdServer-12-02-2026/script/build.ts +67 -0
  136. package/Influence-MW-AdServer-12-02-2026/scripts/create-miro-diagrams.cjs +318 -0
  137. package/Influence-MW-AdServer-12-02-2026/scripts/create-remaining-diagrams.cjs +270 -0
  138. package/Influence-MW-AdServer-12-02-2026/server/index.ts +103 -0
  139. package/Influence-MW-AdServer-12-02-2026/server/recommendation-service.ts +319 -0
  140. package/Influence-MW-AdServer-12-02-2026/server/routes.ts +1890 -0
  141. package/Influence-MW-AdServer-12-02-2026/server/static.ts +19 -0
  142. package/Influence-MW-AdServer-12-02-2026/server/storage.ts +2058 -0
  143. package/Influence-MW-AdServer-12-02-2026/server/vite.ts +58 -0
  144. package/Influence-MW-AdServer-12-02-2026/shared/schema.ts +1595 -0
  145. package/Influence-MW-AdServer-12-02-2026/tailwind.config.ts +107 -0
  146. package/Influence-MW-AdServer-12-02-2026/tsconfig.json +23 -0
  147. package/Influence-MW-AdServer-12-02-2026/vite.config.ts +40 -0
  148. package/LINE_ITEM_BUDGET_FIELD_MAPPING.md +178 -0
  149. package/PCM/.env.example +92 -0
  150. package/PCM/README.md +558 -0
  151. package/PCM/docs/TEST_CASES.md +422 -0
  152. package/PCM/index.js +106 -0
  153. package/PCM/package-lock.json +3282 -0
  154. package/PCM/package.json +32 -0
  155. package/PCM/replit.md +64 -0
  156. package/PCM/schema.sql +495 -0
  157. package/PCM/scripts/export-schema.js +183 -0
  158. package/PCM/scripts/seed-comprehensive.js +631 -0
  159. package/PCM/scripts/seed-production.js +477 -0
  160. package/PCM/src/config/db.js +56 -0
  161. package/PCM/src/config/swagger.js +5975 -0
  162. package/PCM/src/dto/EmailRequestDTO.js +166 -0
  163. package/PCM/src/middleware/errorHandler.js +52 -0
  164. package/PCM/src/middleware/logger.js +26 -0
  165. package/PCM/src/migrations/001_add_campaign_mode_fields.sql +36 -0
  166. package/PCM/src/migrations/002_create_deal_id_counters.sql +22 -0
  167. package/PCM/src/migrations/003_update_publishers_column.sql +15 -0
  168. package/PCM/src/migrations/004_add_direct_dealtype_and_advertiser.sql +5 -0
  169. package/PCM/src/migrations/005_add_programmatic_fields_and_update_enums.sql +31 -0
  170. package/PCM/src/migrations/006_add_line_item_programmatic_fields.sql +12 -0
  171. package/PCM/src/migrations/007_add_line_item_direct_fields.sql +15 -0
  172. package/PCM/src/migrations/008_add_inventory_fields.sql +45 -0
  173. package/PCM/src/migrations/009_move_inventory_fields_to_metadata.sql +32 -0
  174. package/PCM/src/migrations/010_add_draft_status_and_line_items_count.sql +23 -0
  175. package/PCM/src/migrations/011_add_planning_field.sql +21 -0
  176. package/PCM/src/migrations/012_fix_inventory_composite_pk.sql +17 -0
  177. package/PCM/src/migrations/013_make_external_id_optional.sql +3 -0
  178. package/PCM/src/migrations/014_create_change_history.sql +38 -0
  179. package/PCM/src/migrations/016_create_publisher_insertion_orders.sql +33 -0
  180. package/PCM/src/migrations/017_fix_line_item_id_fk_reference.sql +86 -0
  181. package/PCM/src/migrations/018_create_approval_tables.sql +44 -0
  182. package/PCM/src/migrations/019_add_encrypted_token_column.sql +2 -0
  183. package/PCM/src/migrations/020_add_rejection_reason_to_deals.sql +10 -0
  184. package/PCM/src/migrations/021_add_publisher_external_id_to_inventories.sql +12 -0
  185. package/PCM/src/migrations/022_add_line_item_extended_fields.sql +24 -0
  186. package/PCM/src/migrations/023_add_base_price_fields.sql +8 -0
  187. package/PCM/src/migrations/run-migrations.js +46 -0
  188. package/PCM/src/models/ApprovalOTP.js +51 -0
  189. package/PCM/src/models/ApprovalToken.js +79 -0
  190. package/PCM/src/models/ChangeHistory.js +107 -0
  191. package/PCM/src/models/Deal.js +186 -0
  192. package/PCM/src/models/DealIdCounter.js +28 -0
  193. package/PCM/src/models/LineItem.js +227 -0
  194. package/PCM/src/models/LineItemCreative.js +89 -0
  195. package/PCM/src/models/LineItemInventory.js +115 -0
  196. package/PCM/src/models/PublisherInsertionOrder.js +93 -0
  197. package/PCM/src/models/TransactionHistory.js +34 -0
  198. package/PCM/src/models/associations.js +81 -0
  199. package/PCM/src/routes/approval.js +321 -0
  200. package/PCM/src/routes/creatives.js +437 -0
  201. package/PCM/src/routes/deals.js +1638 -0
  202. package/PCM/src/routes/digitalSignage.js +242 -0
  203. package/PCM/src/routes/insertionOrders.js +380 -0
  204. package/PCM/src/routes/lineItems.js +926 -0
  205. package/PCM/src/routes/system.js +384 -0
  206. package/PCM/src/services/ApprovalService.js +885 -0
  207. package/PCM/src/services/CampaignImportConverter.js +631 -0
  208. package/PCM/src/services/CampaignModeService.js +273 -0
  209. package/PCM/src/services/CampaignStatusService.js +395 -0
  210. package/PCM/src/services/ChangeHistoryService.js +316 -0
  211. package/PCM/src/services/DealIdService.js +94 -0
  212. package/PCM/src/services/DealResponseFormatter.js +90 -0
  213. package/PCM/src/services/EmailNotificationService.js +315 -0
  214. package/PCM/src/services/LineItemResponseFormatter.js +122 -0
  215. package/PCM/src/services/LineItemStatusService.js +380 -0
  216. package/PCM/src/tests/comprehensiveTestRunner.js +360 -0
  217. package/PCM/src/tests/comprehensiveTests.js +1277 -0
  218. package/PCM/src/tests/dealTypeUnitTests.js +1058 -0
  219. package/PCM/src/tests/testRunner.js +248 -0
  220. package/PCM/src/utils/caseConverter.js +92 -0
  221. package/PCM/src/utils/dealCalculations.js +206 -0
  222. package/PCM/src/utils/lineItemPayloadNormalizer.js +41 -0
  223. package/PCM/src/utils/payloadNormalizer.js +34 -0
  224. package/PCM/src/utils/sourceNormalizer.js +56 -0
  225. package/PCM/src/validators/creativeValidator.js +27 -0
  226. package/PCM/src/validators/dealValidator.js +203 -0
  227. package/PCM/src/validators/lineItemValidator.js +489 -0
  228. package/PCM/tests/approval-flows.test.js +238 -0
  229. package/PCM/tests/approval-workflow.test.js +291 -0
  230. package/PCM/tests/campaign-import-converter.test.js +543 -0
  231. package/PCM/tests/campaign-import-e2e.test.js +520 -0
  232. package/PCM/tests/campaign-status.test.js +539 -0
  233. package/PCM/tests/direct-publisher-split-reimport.test.js +460 -0
  234. package/PCM/tests/e2e/digital-signage.test.js +145 -0
  235. package/PCM/tests/e2e/search-filter-pagination.test.js +399 -0
  236. package/PCM/tests/e2e-comprehensive.test.js +3446 -0
  237. package/PCM/tests/edge-cases.test.js +340 -0
  238. package/PCM/tests/line-item-status.test.js +340 -0
  239. package/PCM/tests/seller-account-external-ids.test.js +877 -0
  240. package/PCM/tests/source-validation.test.js +324 -0
  241. package/PRD.md +3373 -0
  242. package/README.md +186 -0
  243. package/client/index.html +35 -0
  244. package/client/public/DEMO_STATUS.md +579 -0
  245. package/client/public/img/MW-logo-trans_1754045676555.png +0 -0
  246. package/client/public/locales/ar/approval.json +144 -0
  247. package/client/public/locales/ar/buyer.json +61 -0
  248. package/client/public/locales/ar/campaigns.json +1 -0
  249. package/client/public/locales/ar/common.json +218 -0
  250. package/client/public/locales/ar/contentHub.json +266 -0
  251. package/client/public/locales/ar/creatives.json +79 -0
  252. package/client/public/locales/ar/dashboard.json +57 -0
  253. package/client/public/locales/ar/deals.json +886 -0
  254. package/client/public/locales/ar/dsp.json +131 -0
  255. package/client/public/locales/ar/inventory.json +201 -0
  256. package/client/public/locales/ar/lineItems.json +553 -0
  257. package/client/public/locales/ar/navigation.json +48 -0
  258. package/client/public/locales/ar/wizard.json +1 -0
  259. package/client/public/locales/en/approval.json +144 -0
  260. package/client/public/locales/en/buyer.json +65 -0
  261. package/client/public/locales/en/campaigns.json +1 -0
  262. package/client/public/locales/en/common.json +218 -0
  263. package/client/public/locales/en/contentHub.json +266 -0
  264. package/client/public/locales/en/creatives.json +79 -0
  265. package/client/public/locales/en/dashboard.json +57 -0
  266. package/client/public/locales/en/deals.json +886 -0
  267. package/client/public/locales/en/dsp.json +131 -0
  268. package/client/public/locales/en/inventory.json +201 -0
  269. package/client/public/locales/en/lineItems.json +659 -0
  270. package/client/public/locales/en/navigation.json +48 -0
  271. package/client/public/locales/en/wizard.json +1 -0
  272. package/client/public/locales/ja/approval.json +144 -0
  273. package/client/public/locales/ja/buyer.json +61 -0
  274. package/client/public/locales/ja/campaigns.json +1 -0
  275. package/client/public/locales/ja/common.json +218 -0
  276. package/client/public/locales/ja/contentHub.json +266 -0
  277. package/client/public/locales/ja/creatives.json +79 -0
  278. package/client/public/locales/ja/dashboard.json +57 -0
  279. package/client/public/locales/ja/deals.json +886 -0
  280. package/client/public/locales/ja/dsp.json +131 -0
  281. package/client/public/locales/ja/inventory.json +201 -0
  282. package/client/public/locales/ja/lineItems.json +553 -0
  283. package/client/public/locales/ja/navigation.json +48 -0
  284. package/client/public/locales/ja/wizard.json +1 -0
  285. package/client/public/locales/zh/approval.json +144 -0
  286. package/client/public/locales/zh/buyer.json +61 -0
  287. package/client/public/locales/zh/campaigns.json +1 -0
  288. package/client/public/locales/zh/common.json +218 -0
  289. package/client/public/locales/zh/contentHub.json +266 -0
  290. package/client/public/locales/zh/creatives.json +79 -0
  291. package/client/public/locales/zh/dashboard.json +57 -0
  292. package/client/public/locales/zh/deals.json +886 -0
  293. package/client/public/locales/zh/dsp.json +131 -0
  294. package/client/public/locales/zh/inventory.json +201 -0
  295. package/client/public/locales/zh/lineItems.json +553 -0
  296. package/client/public/locales/zh/navigation.json +48 -0
  297. package/client/public/locales/zh/wizard.json +1 -0
  298. package/client/public/manifest.json +36 -0
  299. package/client/src/App.tsx +464 -0
  300. package/client/src/components/app-sidebar.tsx +312 -0
  301. package/client/src/components/approval/approval-decision-form.test.tsx +294 -0
  302. package/client/src/components/approval/approval-decision-form.tsx +326 -0
  303. package/client/src/components/approval/approval-sheet.tsx +631 -0
  304. package/client/src/components/approval/line-item-details-sheet.tsx +371 -0
  305. package/client/src/components/approval/otp-verification.test.tsx +337 -0
  306. package/client/src/components/approval/otp-verification.tsx +180 -0
  307. package/client/src/components/content-hub/bulk-transcode-dialog.tsx +379 -0
  308. package/client/src/components/content-hub/content-hub-manager-v2.tsx +574 -0
  309. package/client/src/components/content-hub/content-hub-manager.tsx +330 -0
  310. package/client/src/components/content-hub/creative-card.tsx +456 -0
  311. package/client/src/components/content-hub/creative-detail-sheet.tsx +685 -0
  312. package/client/src/components/content-hub/creative-filters.tsx +457 -0
  313. package/client/src/components/content-hub/creative-grid.tsx +329 -0
  314. package/client/src/components/content-hub/creative-selector.tsx +415 -0
  315. package/client/src/components/content-hub/creative-upload.tsx +547 -0
  316. package/client/src/components/content-hub/folder-dialogs.tsx +445 -0
  317. package/client/src/components/content-hub/folder-list.tsx +280 -0
  318. package/client/src/components/content-hub/review-dialogs.tsx +268 -0
  319. package/client/src/components/content-hub/transcode-dialog.tsx +226 -0
  320. package/client/src/components/creative-library/creative-details-view.tsx +446 -0
  321. package/client/src/components/creative-library/creative-filters-panel.tsx +203 -0
  322. package/client/src/components/creative-library/creative-list.tsx +360 -0
  323. package/client/src/components/creative-library/creative-status-badge.tsx +71 -0
  324. package/client/src/components/creative-library/folder-card.tsx +78 -0
  325. package/client/src/components/creative-library/index.ts +27 -0
  326. package/client/src/components/creative-library/new-creative-card.tsx +211 -0
  327. package/client/src/components/creative-library/upload-creative-dialog.tsx +261 -0
  328. package/client/src/components/dashboard-overview.tsx +109 -0
  329. package/client/src/components/deals/approval-history-panel.test.tsx +240 -0
  330. package/client/src/components/deals/approval-history-panel.tsx +156 -0
  331. package/client/src/components/deals/deal-status-badge.tsx +92 -0
  332. package/client/src/components/deals/import-from-planner-dialog.tsx +399 -0
  333. package/client/src/components/deals/market-insights-panel.tsx +237 -0
  334. package/client/src/components/deals/reopen-deal-sheet.tsx +191 -0
  335. package/client/src/components/deals/request-approval-sheet.test.tsx +323 -0
  336. package/client/src/components/deals/request-approval-sheet.tsx +136 -0
  337. package/client/src/components/deals/resend-approval-sheet.tsx +201 -0
  338. package/client/src/components/direct-campaigns/campaign-card.tsx +283 -0
  339. package/client/src/components/direct-campaigns/deal-filter-panel.tsx +325 -0
  340. package/client/src/components/inventory/advanced-filters-panel.tsx +273 -0
  341. package/client/src/components/inventory/csv-upload-modal.tsx +639 -0
  342. package/client/src/components/inventory/inventory-availability-view.tsx +486 -0
  343. package/client/src/components/inventory/inventory-details-sheet.tsx +376 -0
  344. package/client/src/components/inventory/inventory-map-view.tsx +596 -0
  345. package/client/src/components/inventory/inventory-settings-menu.tsx +52 -0
  346. package/client/src/components/language-switcher.tsx +53 -0
  347. package/client/src/components/line-items/campaign-forecast-panel.tsx +138 -0
  348. package/client/src/components/line-items/form-insights.tsx +89 -0
  349. package/client/src/components/line-items/geofencing/LocationCsvUploadDrawer.tsx +100 -0
  350. package/client/src/components/line-items/geofencing/POIDropdown.tsx +379 -0
  351. package/client/src/components/line-items/geofencing/SelectedLocationsSidebar.tsx +436 -0
  352. package/client/src/components/line-items/geofencing/ViewFileLocationDrawer.tsx +199 -0
  353. package/client/src/components/line-items/geofencing/components/ExistingFilesTab.tsx +268 -0
  354. package/client/src/components/line-items/geofencing/components/TemplateDownloadSection.tsx +59 -0
  355. package/client/src/components/line-items/geofencing/components/UploadTab.tsx +215 -0
  356. package/client/src/components/line-items/geofencing-map.tsx +1270 -0
  357. package/client/src/components/line-items/inventory-availability-section.tsx +178 -0
  358. package/client/src/components/line-items/line-item-schedule-manager.tsx +313 -0
  359. package/client/src/components/line-items/manual-inventory-drawer.tsx +346 -0
  360. package/client/src/components/line-items/planner-inventory-card.tsx +495 -0
  361. package/client/src/components/line-items/planner-schedule-grid.tsx +495 -0
  362. package/client/src/components/line-items/schedule-rule-editor.tsx +649 -0
  363. package/client/src/components/line-items/schedule-rule-types.ts +122 -0
  364. package/client/src/components/line-items/steps/creatives-step.tsx +681 -0
  365. package/client/src/components/line-items/steps/inventory-schedule-step.tsx +1596 -0
  366. package/client/src/components/line-items/steps/inventory-step.tsx +1533 -0
  367. package/client/src/components/line-items/steps/line-item-details-step.tsx +916 -0
  368. package/client/src/components/line-items/steps/schedule-step.tsx +273 -0
  369. package/client/src/components/line-items/steps/summary-step.tsx +680 -0
  370. package/client/src/components/line-items/steps/targeting-step.tsx +1708 -0
  371. package/client/src/components/product-switcher.tsx +105 -0
  372. package/client/src/components/protected-route.tsx +49 -0
  373. package/client/src/components/skip-link.tsx +22 -0
  374. package/client/src/components/stat-card.tsx +53 -0
  375. package/client/src/components/status-badge.tsx +96 -0
  376. package/client/src/components/ui/hierarchical-venue-selector.tsx +389 -0
  377. package/client/src/components/ui/toaster.tsx +111 -0
  378. package/client/src/contexts/auth-context.tsx +181 -0
  379. package/client/src/contexts/sidebar-state.tsx +50 -0
  380. package/client/src/contexts/theme-context.tsx +66 -0
  381. package/client/src/data/campaign-data.json +107 -0
  382. package/client/src/data/countries.json +22 -0
  383. package/client/src/hooks/use-approval.ts +366 -0
  384. package/client/src/hooks/use-keyboard-shortcuts.ts +74 -0
  385. package/client/src/hooks/use-media-query.ts +46 -0
  386. package/client/src/hooks/use-mobile.tsx +19 -0
  387. package/client/src/hooks/use-page-title.ts +21 -0
  388. package/client/src/hooks/use-toast.ts +195 -0
  389. package/client/src/index.css +694 -0
  390. package/client/src/lib/__tests__/accessibility.test.ts +104 -0
  391. package/client/src/lib/__tests__/date-utils.test.ts +199 -0
  392. package/client/src/lib/__tests__/dsp-buyer-api.test.ts +127 -0
  393. package/client/src/lib/__tests__/dsp-buyer-integration.test.ts +247 -0
  394. package/client/src/lib/__tests__/storage-utils.test.ts +167 -0
  395. package/client/src/lib/__tests__/utils.test.ts +57 -0
  396. package/client/src/lib/accessibility.ts +141 -0
  397. package/client/src/lib/api-config.ts +9 -0
  398. package/client/src/lib/auth-service.ts +209 -0
  399. package/client/src/lib/campaign-creative-api.ts +82 -0
  400. package/client/src/lib/company-api.ts +61 -0
  401. package/client/src/lib/content-hub-api.ts +407 -0
  402. package/client/src/lib/creative-mapper.ts +61 -0
  403. package/client/src/lib/date-utils.ts +119 -0
  404. package/client/src/lib/deal-helpers.ts +220 -0
  405. package/client/src/lib/dsp-buyer-api.ts +196 -0
  406. package/client/src/lib/geo-import-api.ts +151 -0
  407. package/client/src/lib/google-poi-api.ts +305 -0
  408. package/client/src/lib/i18n/__tests__/formatting.test.ts +202 -0
  409. package/client/src/lib/i18n/formatting.ts +130 -0
  410. package/client/src/lib/i18n/index.ts +8 -0
  411. package/client/src/lib/i18n-compat.ts +76 -0
  412. package/client/src/lib/influence-deals-api.ts +896 -0
  413. package/client/src/lib/inventory-api.ts +399 -0
  414. package/client/src/lib/oauth-service.ts +678 -0
  415. package/client/src/lib/poi-types.ts +75 -0
  416. package/client/src/lib/queryClient.ts +144 -0
  417. package/client/src/lib/recommendation-api.ts +380 -0
  418. package/client/src/lib/storage-utils.ts +104 -0
  419. package/client/src/lib/tolgee.ts +85 -0
  420. package/client/src/lib/utils.ts +0 -0
  421. package/client/src/main.tsx +67 -0
  422. package/client/src/mapbox-draw-modes.d.ts +32 -0
  423. package/client/src/pages/all-folders.tsx +203 -0
  424. package/client/src/pages/auth-callback.tsx +115 -0
  425. package/client/src/pages/buyer-form.tsx +339 -0
  426. package/client/src/pages/buyer-list.tsx +622 -0
  427. package/client/src/pages/content-hub.tsx +1358 -0
  428. package/client/src/pages/create-deal.tsx +2093 -0
  429. package/client/src/pages/creative-assignment-page.tsx +548 -0
  430. package/client/src/pages/creatives.tsx +5 -0
  431. package/client/src/pages/custom-pois.tsx +425 -0
  432. package/client/src/pages/dashboard.tsx +615 -0
  433. package/client/src/pages/deal-history.tsx +434 -0
  434. package/client/src/pages/deal-line-items.tsx +1703 -0
  435. package/client/src/pages/demo-status.tsx +113 -0
  436. package/client/src/pages/direct-campaign-details.tsx +361 -0
  437. package/client/src/pages/direct-campaigns-new.tsx +824 -0
  438. package/client/src/pages/dsp-form.tsx +803 -0
  439. package/client/src/pages/dsp-list.tsx +239 -0
  440. package/client/src/pages/folder-content.tsx +336 -0
  441. package/client/src/pages/integrations.tsx +429 -0
  442. package/client/src/pages/line-item-creatives.tsx +789 -0
  443. package/client/src/pages/line-item-detail-page.tsx +684 -0
  444. package/client/src/pages/line-item-form-page.tsx +3261 -0
  445. package/client/src/pages/line-item-wizard.tsx +1207 -0
  446. package/client/src/pages/login.tsx +154 -0
  447. package/client/src/pages/not-found.tsx +23 -0
  448. package/client/src/pages/proof-of-play.tsx +397 -0
  449. package/client/src/pages/public-approval.tsx +551 -0
  450. package/client/src/pages/reports.tsx +231 -0
  451. package/client/src/pages/settings.tsx +760 -0
  452. package/client/src/pages/signals.tsx +389 -0
  453. package/client/src/pages/tags.tsx +318 -0
  454. package/client/src/pages/test-results.tsx +328 -0
  455. package/client/src/store/hooks.ts +5 -0
  456. package/client/src/store/index.ts +15 -0
  457. package/client/src/store/mapMarkerLocationsSlice.ts +241 -0
  458. package/client/src/styles/design-tokens.css +324 -0
  459. package/client/src/test/setup.ts +261 -0
  460. package/client/src/test/test-utils.tsx +40 -0
  461. package/client/src/types/approval.ts +221 -0
  462. package/client/src/types/content-hub.ts +209 -0
  463. package/client/src/types/geofencing.ts +67 -0
  464. package/client/src/types/transcoding.ts +140 -0
  465. package/client/src/vite-env.d.ts +18 -0
  466. package/components.json +20 -0
  467. package/creative-api.json +1 -0
  468. package/docs/AI_REFERENCE.md +459 -0
  469. package/docs/MWDesign-Prompt.md +132 -0
  470. package/docs/MWDesign-System.md +344 -0
  471. package/docs/test-plan.md +277 -0
  472. package/e2e/AUTONOMOUS-TESTING.md +406 -0
  473. package/e2e/README.md +219 -0
  474. package/e2e/autonomous-flow.spec.ts +308 -0
  475. package/e2e/debug-sso.spec.ts +163 -0
  476. package/e2e/direct-campaigns.spec.ts +219 -0
  477. package/e2e/explore-sso.spec.ts +149 -0
  478. package/e2e/fixtures/auth.ts +26 -0
  479. package/e2e/fixtures/enhanced-test.ts +331 -0
  480. package/e2e/pagination.spec.ts +280 -0
  481. package/e2e/view-toggle.spec.ts +312 -0
  482. package/generated-icon.png +0 -0
  483. package/i18next-scanner.config.cjs +46 -0
  484. package/package.json +141 -0
  485. package/playwright.config.ts +93 -0
  486. package/postcss.config.js +6 -0
  487. package/replit.md +196 -0
  488. package/screenshot-after-login.png +0 -0
  489. package/screenshot-contenthub-grid.png +0 -0
  490. package/screenshot-contenthub-list-fixed.png +0 -0
  491. package/screenshot-contenthub-list.png +0 -0
  492. package/screenshot-create-deal.png +0 -0
  493. package/screenshot-dashboard.png +0 -0
  494. package/screenshot-deals.png +0 -0
  495. package/screenshot-login-filled.png +0 -0
  496. package/screenshot-login.png +0 -0
  497. package/screenshot.mjs +24 -0
  498. package/scripts/deploy-stg.sh +185 -0
  499. package/shared/direct-io-schema.ts +383 -0
  500. package/shared/schema.ts +439 -0
  501. package/shared/screen-types.ts +149 -0
  502. package/springdocDefault.json +1 -0
  503. package/swagger-ui-bundle.js +2 -0
  504. package/swagger-ui-init.js +10316 -0
  505. package/tailwind.config.ts +282 -0
  506. package/terraform/README.md +306 -0
  507. package/terraform/cloudfront.tf +289 -0
  508. package/terraform/ecs.tf +727 -0
  509. package/terraform/environments/dev.tfvars +59 -0
  510. package/terraform/environments/production.tfvars +60 -0
  511. package/terraform/main.tf +47 -0
  512. package/terraform/outputs.tf +145 -0
  513. package/terraform/s3.tf +192 -0
  514. package/terraform/variables.tf +226 -0
  515. package/terraform/waf.tf +165 -0
  516. package/terraform-frontend/.terraform.lock.hcl +25 -0
  517. package/terraform-frontend/README.md +85 -0
  518. package/terraform-frontend/cloudfront.tf +125 -0
  519. package/terraform-frontend/main.tf +31 -0
  520. package/terraform-frontend/outputs.tf +24 -0
  521. package/terraform-frontend/terraform.tfvars +12 -0
  522. package/terraform-frontend/variables.tf +53 -0
  523. package/tsconfig.json +23 -0
  524. package/vite.config.ts +226 -0
  525. package/vitest.config.ts +56 -0
@@ -0,0 +1,885 @@
1
+ import crypto from 'crypto';
2
+ import ApprovalToken from '../models/ApprovalToken.js';
3
+ import ApprovalOTP from '../models/ApprovalOTP.js';
4
+ import Deal from '../models/Deal.js';
5
+ import LineItem from '../models/LineItem.js';
6
+ import LineItemCreative from '../models/LineItemCreative.js';
7
+ import ChangeHistory from '../models/ChangeHistory.js';
8
+ import CampaignStatusService, { TRANSITION_OWNERS } from './CampaignStatusService.js';
9
+ import LineItemStatusService from './LineItemStatusService.js';
10
+ import emailService from './EmailNotificationService.js';
11
+ import sequelize from '../config/db.js';
12
+
13
+ const TOKEN_EXPIRY_DAYS = parseInt(process.env.APPROVAL_TOKEN_EXPIRY_DAYS || '30');
14
+ const OTP_EXPIRY_MINUTES = parseInt(process.env.OTP_EXPIRY_MINUTES || '10');
15
+ const MAX_OTP_ATTEMPTS = parseInt(process.env.MAX_OTP_ATTEMPTS || '5');
16
+ const MAX_OTP_REQUESTS = parseInt(process.env.MAX_OTP_REQUESTS || '10');
17
+ const OTP_COOLDOWN_SECONDS = parseInt(process.env.OTP_COOLDOWN_SECONDS || '60');
18
+ const APPROVAL_BASE_URL = process.env.APPROVAL_BASE_URL || 'http://localhost:5000/approve';
19
+ const DEV_OTP_CODE = process.env.DEV_OTP_CODE;
20
+
21
+ export class ApprovalService {
22
+ generateSecureToken() {
23
+ return crypto.randomBytes(32).toString('hex');
24
+ }
25
+
26
+ hashToken(token) {
27
+ return crypto.createHash('sha256').update(token).digest('hex');
28
+ }
29
+
30
+ generateOTP() {
31
+ if (DEV_OTP_CODE) {
32
+ return DEV_OTP_CODE;
33
+ }
34
+ return String(Math.floor(100000 + Math.random() * 900000));
35
+ }
36
+
37
+ hashOTP(otp) {
38
+ return crypto.createHash('sha256').update(otp).digest('hex');
39
+ }
40
+
41
+ encryptToken(token) {
42
+ const secret = process.env.APPROVAL_SECRET_KEY;
43
+ if (!secret) {
44
+ throw new Error('APPROVAL_SECRET_KEY environment variable is required');
45
+ }
46
+ const iv = crypto.randomBytes(16);
47
+ const key = crypto.scryptSync(secret, 'approval-salt-v1', 32);
48
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
49
+ let encrypted = cipher.update(token, 'utf8', 'hex');
50
+ encrypted += cipher.final('hex');
51
+ const authTag = cipher.getAuthTag().toString('hex');
52
+ return `${iv.toString('hex')}:${authTag}:${encrypted}`;
53
+ }
54
+
55
+ decryptToken(encryptedToken) {
56
+ try {
57
+ const secret = process.env.APPROVAL_SECRET_KEY;
58
+ if (!secret) return null;
59
+
60
+ const parts = encryptedToken.split(':');
61
+ if (parts.length !== 3) return null;
62
+
63
+ const [ivHex, authTagHex, encrypted] = parts;
64
+ const iv = Buffer.from(ivHex, 'hex');
65
+ const authTag = Buffer.from(authTagHex, 'hex');
66
+ const key = crypto.scryptSync(secret, 'approval-salt-v1', 32);
67
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
68
+ decipher.setAuthTag(authTag);
69
+ let decrypted = decipher.update(encrypted, 'hex', 'utf8');
70
+ decrypted += decipher.final('utf8');
71
+ return decrypted;
72
+ } catch (error) {
73
+ return null;
74
+ }
75
+ }
76
+
77
+ async initiateApprovalWorkflow(dealId, approvalEmails, requestId = null, options = {}) {
78
+ const { frontendUrl = null } = options;
79
+ const deal = await Deal.findOne({ where: { deal_id: dealId } });
80
+ if (!deal) {
81
+ throw new Error(`Deal not found: ${dealId}`);
82
+ }
83
+
84
+ if (!approvalEmails || approvalEmails.length === 0) {
85
+ return await this.autoApprove(dealId, requestId);
86
+ }
87
+
88
+ const validation = CampaignStatusService.validateTransition(
89
+ { status: deal.status, source: deal.source, mode: deal.mode },
90
+ 'PENDING',
91
+ { owner: TRANSITION_OWNERS.USER, source: deal.source, workflow: deal.mode }
92
+ );
93
+
94
+ if (!validation.valid) {
95
+ throw new Error(`Cannot transition to PENDING: ${validation.errors[0]?.message || 'Invalid transition'}`);
96
+ }
97
+
98
+ const transaction = await sequelize.transaction();
99
+
100
+ try {
101
+ const tokens = [];
102
+ const expiresAt = new Date();
103
+ expiresAt.setDate(expiresAt.getDate() + TOKEN_EXPIRY_DAYS);
104
+
105
+ for (const email of approvalEmails) {
106
+ const rawToken = this.generateSecureToken();
107
+ const hashedToken = this.hashToken(rawToken);
108
+ const encryptedToken = this.encryptToken(rawToken);
109
+
110
+ const approvalToken = await ApprovalToken.create({
111
+ deal_id: dealId,
112
+ approver_email: email.toLowerCase().trim(),
113
+ token: hashedToken,
114
+ encrypted_token: encryptedToken,
115
+ status: 'PENDING',
116
+ expires_at: expiresAt,
117
+ request_id: requestId
118
+ }, { transaction });
119
+
120
+ const approvalUrl = frontendUrl
121
+ ? `${frontendUrl}?token=${encodeURIComponent(encryptedToken)}`
122
+ : emailService.buildApprovalLink(encryptedToken);
123
+
124
+ const lineItemCount = deal.line_items_count || 0;
125
+ const budgetAmount = deal.budget_setup?.budgetAmount || deal.budget_setup?.budget_amount || 0;
126
+ const currency = deal.currency || deal.budget_setup?.currency || 'USD';
127
+
128
+ emailService.sendApprovalRequestEmailAsync({
129
+ approverEmail: email,
130
+ dealId,
131
+ dealName: deal.name,
132
+ budget: budgetAmount,
133
+ currency,
134
+ noLineItems: lineItemCount,
135
+ publisherName: '',
136
+ approvalLink: approvalUrl,
137
+ user: {},
138
+ logoUrl: null
139
+ }, async (historyData) => {
140
+ await this._recordApprovalHistory(dealId, historyData.action, {
141
+ approverEmail: historyData.approverEmail,
142
+ success: historyData.success,
143
+ error: historyData.error,
144
+ endpoint: historyData.endpoint,
145
+ requestPayload: historyData.requestPayload,
146
+ responseDetails: historyData.responseDetails,
147
+ timestamp: historyData.timestamp
148
+ }, requestId);
149
+ });
150
+
151
+ tokens.push({
152
+ id: approvalToken.id,
153
+ email,
154
+ status: 'PENDING'
155
+ });
156
+ }
157
+
158
+ await Deal.update(
159
+ { status: 'PENDING', version: deal.version + 1 },
160
+ { where: { deal_id: dealId }, transaction }
161
+ );
162
+
163
+ const cascadeResult = await this._cascadeStatusToLineItems(dealId, 'PENDING', deal.source, transaction);
164
+
165
+ await this._recordApprovalHistory(dealId, 'APPROVAL_REQUESTED', {
166
+ approverEmails: approvalEmails,
167
+ expiresAt,
168
+ cascadedLineItems: cascadeResult.cascaded.length,
169
+ skippedLineItems: cascadeResult.skipped.length
170
+ }, requestId, transaction);
171
+
172
+ await transaction.commit();
173
+
174
+ return {
175
+ success: true,
176
+ dealId,
177
+ status: 'PENDING',
178
+ approverCount: approvalEmails.length,
179
+ tokens: tokens.map(t => ({ email: t.email, status: t.status })),
180
+ cascadedLineItems: cascadeResult.cascaded.length > 0 ? cascadeResult.cascaded : undefined,
181
+ skippedLineItems: cascadeResult.skipped.length > 0 ? cascadeResult.skipped : undefined
182
+ };
183
+ } catch (error) {
184
+ await transaction.rollback();
185
+ throw error;
186
+ }
187
+ }
188
+
189
+ async autoApprove(dealId, requestId = null) {
190
+ const deal = await Deal.findOne({ where: { deal_id: dealId } });
191
+ if (!deal) {
192
+ throw new Error(`Deal not found: ${dealId}`);
193
+ }
194
+
195
+ const validation = CampaignStatusService.validateTransition(
196
+ { status: deal.status, source: deal.source, mode: deal.mode },
197
+ 'APPROVED',
198
+ { owner: TRANSITION_OWNERS.USER, source: deal.source, workflow: deal.mode }
199
+ );
200
+
201
+ if (!validation.valid) {
202
+ throw new Error(`Cannot transition to APPROVED: ${validation.errors[0]?.message || 'Invalid transition'}`);
203
+ }
204
+
205
+ const transaction = await sequelize.transaction();
206
+
207
+ try {
208
+ await Deal.update(
209
+ { status: 'APPROVED', version: deal.version + 1 },
210
+ { where: { deal_id: dealId }, transaction }
211
+ );
212
+
213
+ const cascadeResult = await this._cascadeStatusToLineItems(dealId, 'APPROVED', deal.source, transaction);
214
+
215
+ await this._recordApprovalHistory(dealId, 'AUTO_APPROVED', {
216
+ reason: 'No approval emails configured - basic validation passed',
217
+ cascadedLineItems: cascadeResult.cascaded.length,
218
+ skippedLineItems: cascadeResult.skipped.length
219
+ }, requestId, transaction);
220
+
221
+ await transaction.commit();
222
+
223
+ return {
224
+ success: true,
225
+ dealId,
226
+ status: 'APPROVED',
227
+ approvalType: 'AUTO',
228
+ message: 'Campaign auto-approved (no approval emails configured)',
229
+ cascadedLineItems: cascadeResult.cascaded.length > 0 ? cascadeResult.cascaded : undefined,
230
+ skippedLineItems: cascadeResult.skipped.length > 0 ? cascadeResult.skipped : undefined
231
+ };
232
+ } catch (error) {
233
+ await transaction.rollback();
234
+ throw error;
235
+ }
236
+ }
237
+
238
+ async resendApprovalEmails(dealId, requestId = null, options = {}) {
239
+ const { frontendUrl = null, emails: specificEmails = null } = options;
240
+ const deal = await Deal.findOne({ where: { deal_id: dealId } });
241
+ if (!deal) {
242
+ throw new Error(`Deal not found: ${dealId}`);
243
+ }
244
+
245
+ if (deal.mode !== 'DIRECT') {
246
+ const err = new Error('Resend approval is only available for DIRECT campaigns');
247
+ err.code = 'INVALID_MODE';
248
+ err.statusCode = 400;
249
+ throw err;
250
+ }
251
+
252
+ if (deal.status !== 'PENDING') {
253
+ const err = new Error(`Cannot resend approval emails. Deal must be in PENDING status (current: ${deal.status})`);
254
+ err.code = 'INVALID_STATUS';
255
+ err.statusCode = 400;
256
+ throw err;
257
+ }
258
+
259
+ const pendingTokens = await ApprovalToken.findAll({
260
+ where: {
261
+ deal_id: dealId,
262
+ status: 'PENDING',
263
+ decision_at: null
264
+ }
265
+ });
266
+
267
+ if (pendingTokens.length === 0) {
268
+ const err = new Error('No pending approval tokens found for this deal');
269
+ err.code = 'NO_PENDING_TOKENS';
270
+ err.statusCode = 400;
271
+ throw err;
272
+ }
273
+
274
+ const emailsToResend = specificEmails
275
+ ? pendingTokens.filter(t => specificEmails.map(e => e.toLowerCase().trim()).includes(t.approver_email))
276
+ : pendingTokens;
277
+
278
+ if (emailsToResend.length === 0) {
279
+ const err = new Error('No matching pending approval tokens found for the specified emails');
280
+ err.code = 'NO_MATCHING_TOKENS';
281
+ err.statusCode = 400;
282
+ throw err;
283
+ }
284
+
285
+ const resentEmails = [];
286
+ const lineItemCount = deal.line_items_count || 0;
287
+ const budgetAmount = deal.budget_setup?.budgetAmount || deal.budget_setup?.budget_amount || 0;
288
+ const currency = deal.currency || deal.budget_setup?.currency || 'USD';
289
+
290
+ for (const token of emailsToResend) {
291
+ const approvalUrl = frontendUrl
292
+ ? `${frontendUrl}?token=${encodeURIComponent(token.encrypted_token)}`
293
+ : emailService.buildApprovalLink(token.encrypted_token);
294
+
295
+ emailService.sendApprovalRequestEmailAsync({
296
+ approverEmail: token.approver_email,
297
+ dealId,
298
+ dealName: deal.name,
299
+ budget: budgetAmount,
300
+ currency,
301
+ noLineItems: lineItemCount,
302
+ publisherName: '',
303
+ approvalLink: approvalUrl,
304
+ user: {},
305
+ logoUrl: null,
306
+ isResend: true
307
+ }, async (historyData) => {
308
+ await this._recordApprovalHistory(dealId, historyData.action, {
309
+ approverEmail: historyData.approverEmail,
310
+ success: historyData.success,
311
+ error: historyData.error,
312
+ endpoint: historyData.endpoint,
313
+ requestPayload: historyData.requestPayload,
314
+ responseDetails: historyData.responseDetails,
315
+ timestamp: historyData.timestamp,
316
+ isResend: true
317
+ }, requestId);
318
+ });
319
+
320
+ resentEmails.push({
321
+ email: token.approver_email,
322
+ status: 'RESENT',
323
+ expiresAt: token.expires_at
324
+ });
325
+ }
326
+
327
+ await this._recordApprovalHistory(dealId, 'APPROVAL_RESENT', {
328
+ resentEmails: resentEmails.map(e => e.email),
329
+ totalPendingTokens: pendingTokens.length,
330
+ resentCount: resentEmails.length
331
+ }, requestId);
332
+
333
+ return {
334
+ success: true,
335
+ dealId,
336
+ resentCount: resentEmails.length,
337
+ totalPendingApprovers: pendingTokens.length,
338
+ resentEmails: resentEmails.map(e => ({ email: e.email, expiresAt: e.expiresAt }))
339
+ };
340
+ }
341
+
342
+ async getApprovalTokenByEncrypted(encryptedToken) {
343
+ const rawToken = this.decryptToken(encryptedToken);
344
+ if (!rawToken) {
345
+ return null;
346
+ }
347
+
348
+ const hashedToken = this.hashToken(rawToken);
349
+ return ApprovalToken.findOne({
350
+ where: { token: hashedToken },
351
+ include: [{
352
+ model: Deal,
353
+ as: 'deal'
354
+ }]
355
+ });
356
+ }
357
+
358
+ async getCampaignDetailsForApproval(encryptedToken) {
359
+ const approvalToken = await this.getApprovalTokenByEncrypted(encryptedToken);
360
+
361
+ if (!approvalToken) {
362
+ return { error: 'INVALID_TOKEN', message: 'Invalid or expired approval token' };
363
+ }
364
+
365
+ if (new Date() > new Date(approvalToken.expires_at)) {
366
+ return { error: 'TOKEN_EXPIRED', message: 'Approval token has expired' };
367
+ }
368
+
369
+ if (approvalToken.status !== 'PENDING') {
370
+ const deal = approvalToken.deal;
371
+ return {
372
+ error: 'ALREADY_DECIDED',
373
+ message: `Approval already submitted: ${approvalToken.status}`,
374
+ decision: approvalToken.status,
375
+ decisionAt: approvalToken.decision_at,
376
+ rejectionReason: deal?.rejection_reason || approvalToken.rejection_reason,
377
+ dealStatus: deal?.status
378
+ };
379
+ }
380
+
381
+ const deal = approvalToken.deal;
382
+ const lineItems = await LineItem.findAll({
383
+ where: { deal_id: deal.deal_id },
384
+ include: [{
385
+ model: LineItemCreative,
386
+ as: 'creatives'
387
+ }]
388
+ });
389
+
390
+ const allApprovals = await ApprovalToken.findAll({
391
+ where: { deal_id: deal.deal_id },
392
+ attributes: ['approver_email', 'status', 'decision_at']
393
+ });
394
+
395
+ return {
396
+ success: true,
397
+ approverEmail: approvalToken.approver_email,
398
+ otpVerified: approvalToken.otp_verified,
399
+ campaign: {
400
+ dealId: deal.deal_id,
401
+ name: deal.name,
402
+ brand: deal.brand,
403
+ mode: deal.mode,
404
+ status: deal.status,
405
+ rejectionReason: deal.rejection_reason,
406
+ marketSelection: deal.market_selection,
407
+ budgetSetup: deal.budget_setup,
408
+ campaignGoal: deal.campaign_goal,
409
+ targeting: deal.targeting,
410
+ flightDates: {
411
+ startDate: deal.start_date,
412
+ endDate: deal.end_date
413
+ }
414
+ },
415
+ lineItems: lineItems.map(li => ({
416
+ externalId: li.external_id,
417
+ name: li.name,
418
+ publisher: li.publisher,
419
+ resolutions: li.resolutions,
420
+ duration: li.duration,
421
+ totalInventories: li.total_inventories,
422
+ creatives: (li.creatives || []).map(c => ({
423
+ creativeId: c.creative_id,
424
+ creativeUri: c.creative_uri,
425
+ creativeType: c.creative_type,
426
+ mimeType: c.mime_type,
427
+ resolution: c.resolution,
428
+ status: c.status
429
+ }))
430
+ })),
431
+ approvalStatus: {
432
+ total: allApprovals.length,
433
+ pending: allApprovals.filter(a => a.status === 'PENDING').length,
434
+ approved: allApprovals.filter(a => a.status === 'APPROVED').length,
435
+ rejected: allApprovals.filter(a => a.status === 'REJECTED').length
436
+ }
437
+ };
438
+ }
439
+
440
+ async getLineItemsForApproval(encryptedToken) {
441
+ const approvalToken = await this.getApprovalTokenByEncrypted(encryptedToken);
442
+
443
+ if (!approvalToken) {
444
+ return { error: 'INVALID_TOKEN', message: 'Invalid or expired approval token' };
445
+ }
446
+
447
+ if (new Date() > new Date(approvalToken.expires_at)) {
448
+ return { error: 'TOKEN_EXPIRED', message: 'Approval token has expired' };
449
+ }
450
+
451
+ const deal = approvalToken.deal;
452
+ const lineItems = await LineItem.findAll({
453
+ where: { deal_id: deal.deal_id },
454
+ include: [{
455
+ model: LineItemCreative,
456
+ as: 'creatives'
457
+ }]
458
+ });
459
+
460
+ return {
461
+ success: true,
462
+ dealId: deal.deal_id,
463
+ dealName: deal.name,
464
+ lineItems: lineItems.map(li => ({
465
+ id: li.id,
466
+ externalId: li.external_id,
467
+ name: li.name,
468
+ publisher: li.publisher,
469
+ resolutions: li.resolutions,
470
+ duration: li.duration,
471
+ creativeType: li.creative_type,
472
+ schedule: li.schedule,
473
+ pacing: li.pacing,
474
+ totalInventories: li.total_inventories,
475
+ planning: li.planning,
476
+ creatives: (li.creatives || []).map(c => ({
477
+ creativeId: c.creative_id,
478
+ creativeUri: c.creative_uri,
479
+ creativeType: c.creative_type,
480
+ mimeType: c.mime_type,
481
+ resolution: c.resolution,
482
+ duration: c.duration,
483
+ status: c.status
484
+ }))
485
+ })),
486
+ pagination: {
487
+ total: lineItems.length
488
+ }
489
+ };
490
+ }
491
+
492
+ async getInventoriesForApproval(encryptedToken, lineItemId = null) {
493
+ const approvalToken = await this.getApprovalTokenByEncrypted(encryptedToken);
494
+
495
+ if (!approvalToken) {
496
+ return { error: 'INVALID_TOKEN', message: 'Invalid or expired approval token' };
497
+ }
498
+
499
+ if (new Date() > new Date(approvalToken.expires_at)) {
500
+ return { error: 'TOKEN_EXPIRED', message: 'Approval token has expired' };
501
+ }
502
+
503
+ const deal = approvalToken.deal;
504
+ const { default: LineItemInventory } = await import('../models/LineItemInventory.js');
505
+
506
+ const whereClause = { deal_id: deal.deal_id };
507
+ if (lineItemId) {
508
+ const lineItem = await LineItem.findOne({
509
+ where: { deal_id: deal.deal_id, external_id: lineItemId }
510
+ });
511
+ if (!lineItem) {
512
+ const lineItemById = await LineItem.findOne({
513
+ where: { deal_id: deal.deal_id, id: lineItemId }
514
+ });
515
+ if (lineItemById) {
516
+ whereClause.line_item_id = lineItemById.id;
517
+ } else {
518
+ return { error: 'LINE_ITEM_NOT_FOUND', message: 'Line item not found' };
519
+ }
520
+ } else {
521
+ whereClause.line_item_id = lineItem.id;
522
+ }
523
+ }
524
+
525
+ const inventories = await LineItemInventory.findAll({ where: whereClause });
526
+
527
+ return {
528
+ success: true,
529
+ dealId: deal.deal_id,
530
+ dealName: deal.name,
531
+ lineItemId: lineItemId || null,
532
+ inventories: inventories.map(inv => ({
533
+ id: inv.id,
534
+ name: inv.name,
535
+ referenceId: inv.reference_id,
536
+ deviceId: inv.device_id,
537
+ publisher: {
538
+ id: inv.publisher_id,
539
+ name: inv.publisher_name,
540
+ domain: inv.publisher_domain
541
+ },
542
+ size: inv.size,
543
+ venueType: inv.venue_type,
544
+ metadata: inv.metadata,
545
+ planning: inv.planning
546
+ })),
547
+ pagination: {
548
+ total: inventories.length
549
+ }
550
+ };
551
+ }
552
+
553
+ async requestOTP(encryptedToken) {
554
+ const approvalToken = await this.getApprovalTokenByEncrypted(encryptedToken);
555
+
556
+ if (!approvalToken) {
557
+ return { error: 'INVALID_TOKEN', message: 'Invalid approval token' };
558
+ }
559
+
560
+ if (new Date() > new Date(approvalToken.expires_at)) {
561
+ return { error: 'TOKEN_EXPIRED', message: 'Approval token has expired' };
562
+ }
563
+
564
+ if (approvalToken.status !== 'PENDING') {
565
+ return { error: 'ALREADY_DECIDED', message: 'Approval already submitted' };
566
+ }
567
+
568
+ const totalOTPRequests = await ApprovalOTP.count({
569
+ where: { approval_token_id: approvalToken.id }
570
+ });
571
+
572
+ if (totalOTPRequests >= MAX_OTP_REQUESTS) {
573
+ return { error: 'MAX_OTP_REQUESTS', message: 'Maximum OTP requests exceeded for this approval.' };
574
+ }
575
+
576
+ const recentOTP = await ApprovalOTP.findOne({
577
+ where: { approval_token_id: approvalToken.id },
578
+ order: [['created_at', 'DESC']]
579
+ });
580
+
581
+ if (recentOTP) {
582
+ const cooldownEnd = new Date(recentOTP.created_at);
583
+ cooldownEnd.setSeconds(cooldownEnd.getSeconds() + OTP_COOLDOWN_SECONDS);
584
+ if (new Date() < cooldownEnd) {
585
+ const waitSeconds = Math.ceil((cooldownEnd - new Date()) / 1000);
586
+ return { error: 'OTP_COOLDOWN', message: `Please wait ${waitSeconds} seconds before requesting a new OTP.` };
587
+ }
588
+ }
589
+
590
+ const otpCode = this.generateOTP();
591
+ const hashedOTP = this.hashOTP(otpCode);
592
+ const expiresAt = new Date();
593
+ expiresAt.setMinutes(expiresAt.getMinutes() + OTP_EXPIRY_MINUTES);
594
+
595
+ await ApprovalOTP.update(
596
+ { verified: true },
597
+ { where: { approval_token_id: approvalToken.id, verified: false } }
598
+ );
599
+
600
+ await ApprovalOTP.create({
601
+ approval_token_id: approvalToken.id,
602
+ otp_code: hashedOTP,
603
+ expires_at: expiresAt
604
+ });
605
+
606
+ const dealId = approvalToken.deal_id;
607
+
608
+ emailService.sendOTPEmailAsync({
609
+ approverEmail: approvalToken.approver_email,
610
+ otpCode,
611
+ mediaownerName: '',
612
+ user: {},
613
+ logoUrl: null
614
+ }, async (historyData) => {
615
+ await this._recordApprovalHistory(dealId, historyData.action, {
616
+ approverEmail: historyData.approverEmail,
617
+ success: historyData.success,
618
+ error: historyData.error,
619
+ endpoint: historyData.endpoint,
620
+ requestPayload: historyData.requestPayload,
621
+ responseDetails: historyData.responseDetails,
622
+ timestamp: historyData.timestamp
623
+ });
624
+ });
625
+
626
+ return {
627
+ success: true,
628
+ message: 'OTP sent to your email',
629
+ expiresInMinutes: OTP_EXPIRY_MINUTES
630
+ };
631
+ }
632
+
633
+ async verifyOTP(encryptedToken, otpCode) {
634
+ const approvalToken = await this.getApprovalTokenByEncrypted(encryptedToken);
635
+
636
+ if (!approvalToken) {
637
+ return { error: 'INVALID_TOKEN', message: 'Invalid approval token' };
638
+ }
639
+
640
+ const otp = await ApprovalOTP.findOne({
641
+ where: {
642
+ approval_token_id: approvalToken.id,
643
+ verified: false
644
+ },
645
+ order: [['created_at', 'DESC']]
646
+ });
647
+
648
+ if (!otp) {
649
+ return { error: 'NO_OTP', message: 'No active OTP found. Please request a new one.' };
650
+ }
651
+
652
+ if (otp.attempts >= MAX_OTP_ATTEMPTS) {
653
+ return { error: 'MAX_ATTEMPTS', message: 'Maximum OTP attempts exceeded. Please request a new OTP.' };
654
+ }
655
+
656
+ if (new Date() > new Date(otp.expires_at)) {
657
+ return { error: 'OTP_EXPIRED', message: 'OTP has expired. Please request a new one.' };
658
+ }
659
+
660
+ const hashedInput = this.hashOTP(otpCode);
661
+ if (otp.otp_code !== hashedInput) {
662
+ await otp.update({ attempts: otp.attempts + 1 });
663
+ const remaining = MAX_OTP_ATTEMPTS - otp.attempts - 1;
664
+ return {
665
+ error: 'INVALID_OTP',
666
+ message: `Invalid OTP. ${remaining} attempts remaining.`,
667
+ attemptsRemaining: remaining
668
+ };
669
+ }
670
+
671
+ await otp.update({ verified: true });
672
+ await approvalToken.update({ otp_verified: true });
673
+
674
+ return { success: true, message: 'OTP verified successfully' };
675
+ }
676
+
677
+ async submitApprovalDecision(encryptedToken, decision, rejectionReason = null, requestId = null) {
678
+ const approvalToken = await this.getApprovalTokenByEncrypted(encryptedToken);
679
+
680
+ if (!approvalToken) {
681
+ return { error: 'INVALID_TOKEN', message: 'Invalid approval token' };
682
+ }
683
+
684
+ if (!approvalToken.otp_verified) {
685
+ return { error: 'OTP_NOT_VERIFIED', message: 'Please verify OTP before submitting decision' };
686
+ }
687
+
688
+ if (approvalToken.status !== 'PENDING') {
689
+ return { error: 'ALREADY_DECIDED', message: 'Decision already submitted' };
690
+ }
691
+
692
+ if (!['APPROVED', 'REJECTED'].includes(decision)) {
693
+ return { error: 'INVALID_DECISION', message: 'Decision must be APPROVED or REJECTED' };
694
+ }
695
+
696
+ if (decision === 'REJECTED' && !rejectionReason) {
697
+ return { error: 'REJECTION_REASON_REQUIRED', message: 'Rejection reason is required' };
698
+ }
699
+
700
+ const transaction = await sequelize.transaction();
701
+
702
+ try {
703
+ await approvalToken.update({
704
+ status: decision,
705
+ rejection_reason: rejectionReason,
706
+ decision_at: new Date()
707
+ }, { transaction });
708
+
709
+ const allApprovals = await ApprovalToken.findAll({
710
+ where: { deal_id: approvalToken.deal_id },
711
+ transaction
712
+ });
713
+
714
+ const pending = allApprovals.filter(a => a.id !== approvalToken.id && a.status === 'PENDING');
715
+ const rejected = allApprovals.filter(a => a.status === 'REJECTED' || (a.id === approvalToken.id && decision === 'REJECTED'));
716
+ const approved = allApprovals.filter(a => a.status === 'APPROVED' || (a.id === approvalToken.id && decision === 'APPROVED'));
717
+
718
+ let newDealStatus = null;
719
+
720
+ if (rejected.length > 0) {
721
+ newDealStatus = 'REJECTED';
722
+ } else if (pending.length === 0 && approved.length === allApprovals.length) {
723
+ newDealStatus = 'APPROVED';
724
+ }
725
+
726
+ let cascadeResult = { cascaded: [], skipped: [] };
727
+ const deal = await Deal.findOne({ where: { deal_id: approvalToken.deal_id }, transaction });
728
+
729
+ if (newDealStatus) {
730
+ const updateData = { status: newDealStatus };
731
+ if (newDealStatus === 'REJECTED' && rejectionReason) {
732
+ updateData.rejection_reason = rejectionReason;
733
+ }
734
+ await Deal.update(
735
+ updateData,
736
+ { where: { deal_id: approvalToken.deal_id }, transaction }
737
+ );
738
+
739
+ cascadeResult = await this._cascadeStatusToLineItems(
740
+ approvalToken.deal_id,
741
+ newDealStatus,
742
+ deal?.source,
743
+ transaction
744
+ );
745
+ }
746
+
747
+ await this._recordApprovalHistory(approvalToken.deal_id, `APPROVAL_${decision}`, {
748
+ approverEmail: approvalToken.approver_email,
749
+ decision,
750
+ rejectionReason,
751
+ newDealStatus,
752
+ cascadedLineItems: cascadeResult.cascaded.length,
753
+ skippedLineItems: cascadeResult.skipped.length
754
+ }, requestId, transaction);
755
+
756
+ await transaction.commit();
757
+
758
+ if (newDealStatus && deal?.seller?.email) {
759
+ const historyCallback = async (details) => {
760
+ await this._recordApprovalHistory(approvalToken.deal_id, details.action, {
761
+ ...details,
762
+ approverEmail: approvalToken.approver_email
763
+ }, requestId);
764
+ };
765
+
766
+ emailService.sendDecisionEmailAsync({
767
+ sellerEmail: deal.seller.email,
768
+ dealId: approvalToken.deal_id,
769
+ dealName: deal.name,
770
+ budget: deal.budget_setup?.budgetAmount || deal.budget_setup?.budget_amount || deal.net_cost || 0,
771
+ currency: deal.currency || deal.budget_setup?.currency || 'USD',
772
+ noLineItems: deal.line_items_count || 0,
773
+ decision: newDealStatus,
774
+ approverEmail: approvalToken.approver_email
775
+ }, historyCallback);
776
+ }
777
+
778
+ return {
779
+ success: true,
780
+ decision,
781
+ dealStatus: newDealStatus || 'PENDING',
782
+ approvalStatus: {
783
+ total: allApprovals.length,
784
+ pending: pending.length,
785
+ approved: approved.length,
786
+ rejected: rejected.length
787
+ },
788
+ cascadedLineItems: cascadeResult.cascaded.length > 0 ? cascadeResult.cascaded : undefined,
789
+ skippedLineItems: cascadeResult.skipped.length > 0 ? cascadeResult.skipped : undefined
790
+ };
791
+ } catch (error) {
792
+ await transaction.rollback();
793
+ throw error;
794
+ }
795
+ }
796
+
797
+ async getApprovalHistory(dealId) {
798
+ const approvals = await ApprovalToken.findAll({
799
+ where: { deal_id: dealId },
800
+ attributes: ['approver_email', 'status', 'rejection_reason', 'decision_at', 'created_at'],
801
+ order: [['created_at', 'ASC']]
802
+ });
803
+
804
+ return approvals.map(a => ({
805
+ approverEmail: a.approver_email,
806
+ status: a.status,
807
+ rejectionReason: a.rejection_reason,
808
+ decisionAt: a.decision_at,
809
+ requestedAt: a.created_at
810
+ }));
811
+ }
812
+
813
+ async _recordApprovalHistory(dealId, action, details, requestId, transaction) {
814
+ const deal = await Deal.findOne({ where: { deal_id: dealId }, transaction });
815
+ if (!deal) return;
816
+
817
+ await ChangeHistory.create({
818
+ entity_type: 'DEAL',
819
+ entity_id: deal.id,
820
+ deal_id: dealId,
821
+ action: 'UPDATE',
822
+ changed_by: details.approverEmail || 'SYSTEM',
823
+ metadata: {
824
+ approvalAction: action,
825
+ ...details
826
+ },
827
+ request_id: requestId
828
+ }, { transaction });
829
+ }
830
+
831
+ async _cascadeStatusToLineItems(dealId, newStatus, sourceType, transaction) {
832
+ const cascadeStatus = LineItemStatusService.getCascadeStatus(newStatus);
833
+ if (!cascadeStatus || !LineItemStatusService.shouldCascadeStatus(newStatus)) {
834
+ return { cascaded: [], skipped: [] };
835
+ }
836
+
837
+ const lineItems = await LineItem.findAll({
838
+ where: { deal_id: dealId },
839
+ transaction
840
+ });
841
+
842
+ const cascaded = [];
843
+ const skipped = [];
844
+
845
+ for (const li of lineItems) {
846
+ if (li.status === cascadeStatus) continue;
847
+ if (li.status === 'ARCHIVED') {
848
+ skipped.push({
849
+ lineItemId: li.id,
850
+ externalId: li.external_id,
851
+ reason: 'Archived line items are not updated by cascade'
852
+ });
853
+ continue;
854
+ }
855
+
856
+ const validation = LineItemStatusService.validateTransition(
857
+ { status: li.status, source: sourceType },
858
+ cascadeStatus,
859
+ { owner: TRANSITION_OWNERS.ADMIN, source: sourceType, campaignStatus: newStatus }
860
+ );
861
+
862
+ if (!validation.valid) {
863
+ skipped.push({
864
+ lineItemId: li.id,
865
+ externalId: li.external_id,
866
+ reason: validation.errors[0]?.message || 'Invalid transition'
867
+ });
868
+ continue;
869
+ }
870
+
871
+ const previousStatus = li.status;
872
+ await li.update({ status: cascadeStatus }, { transaction });
873
+ cascaded.push({
874
+ lineItemId: li.id,
875
+ externalId: li.external_id,
876
+ previousStatus,
877
+ currentStatus: cascadeStatus
878
+ });
879
+ }
880
+
881
+ return { cascaded, skipped };
882
+ }
883
+ }
884
+
885
+ export default new ApprovalService();