trueppm-api 0.4.0__py3-none-any.whl

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 (799) hide show
  1. trueppm_api/__init__.py +27 -0
  2. trueppm_api/apps/access/__init__.py +0 -0
  3. trueppm_api/apps/access/apps.py +19 -0
  4. trueppm_api/apps/access/groups.py +518 -0
  5. trueppm_api/apps/access/management/__init__.py +0 -0
  6. trueppm_api/apps/access/management/commands/__init__.py +0 -0
  7. trueppm_api/apps/access/management/commands/create_admin.py +346 -0
  8. trueppm_api/apps/access/management/commands/migrate_locked.py +96 -0
  9. trueppm_api/apps/access/management/commands/revoke_api_tokens.py +483 -0
  10. trueppm_api/apps/access/migrations/0001_initial.py +61 -0
  11. trueppm_api/apps/access/migrations/0001_squashed_0012_programmembership_role_title.py +184 -0
  12. trueppm_api/apps/access/migrations/0002_alter_projectmembership_id.py +29 -0
  13. trueppm_api/apps/access/migrations/0003_projectmembership_soft_delete.py +24 -0
  14. trueppm_api/apps/access/migrations/0004_alter_projectmembership_role.py +34 -0
  15. trueppm_api/apps/access/migrations/0005_program_entity_and_membership.py +76 -0
  16. trueppm_api/apps/access/migrations/0006_role_ordinal_spacing.py +113 -0
  17. trueppm_api/apps/access/migrations/0007_projectmembership_joined_at_and_more.py +35 -0
  18. trueppm_api/apps/access/migrations/0008_projectmembership_source_group.py +25 -0
  19. trueppm_api/apps/access/migrations/0009_projectmembership_pm_proj_serverver_idx.py +20 -0
  20. trueppm_api/apps/access/migrations/0010_programmembership_joined_at_and_more.py +38 -0
  21. trueppm_api/apps/access/migrations/0011_alter_programmembership_unique_together_and_more.py +36 -0
  22. trueppm_api/apps/access/migrations/0012_programmembership_role_title.py +17 -0
  23. trueppm_api/apps/access/migrations/0013_squashed_0019_release_0_4.py +302 -0
  24. trueppm_api/apps/access/migrations/0013_userdefinedmentiongroup.py +82 -0
  25. trueppm_api/apps/access/migrations/0014_programmembership_progm_serverver_idx.py +19 -0
  26. trueppm_api/apps/access/migrations/0015_programuserdefinedmentiongroup.py +86 -0
  27. trueppm_api/apps/access/migrations/0016_externalstakeholder.py +67 -0
  28. trueppm_api/apps/access/migrations/0017_viewer_ordinal_one.py +143 -0
  29. trueppm_api/apps/access/migrations/0018_programmembership_sync_seq_and_more.py +52 -0
  30. trueppm_api/apps/access/migrations/0019_programmembership_reinstated_at_and_more.py +22 -0
  31. trueppm_api/apps/access/migrations/__init__.py +0 -0
  32. trueppm_api/apps/access/minter_role.py +38 -0
  33. trueppm_api/apps/access/models.py +588 -0
  34. trueppm_api/apps/access/permissions.py +3263 -0
  35. trueppm_api/apps/access/serializers.py +1007 -0
  36. trueppm_api/apps/access/services.py +878 -0
  37. trueppm_api/apps/access/signals.py +171 -0
  38. trueppm_api/apps/access/tasks.py +50 -0
  39. trueppm_api/apps/access/throttles.py +96 -0
  40. trueppm_api/apps/access/urls.py +191 -0
  41. trueppm_api/apps/access/views.py +1965 -0
  42. trueppm_api/apps/agents/__init__.py +6 -0
  43. trueppm_api/apps/agents/apps.py +11 -0
  44. trueppm_api/apps/agents/canonical.py +73 -0
  45. trueppm_api/apps/agents/deferred.py +108 -0
  46. trueppm_api/apps/agents/management/__init__.py +0 -0
  47. trueppm_api/apps/agents/management/commands/__init__.py +0 -0
  48. trueppm_api/apps/agents/management/commands/audit_prune.py +137 -0
  49. trueppm_api/apps/agents/management/commands/audit_verify.py +101 -0
  50. trueppm_api/apps/agents/middleware.py +44 -0
  51. trueppm_api/apps/agents/migrations/0001_initial.py +231 -0
  52. trueppm_api/apps/agents/migrations/0001_squashed_0003_release_0_4.py +344 -0
  53. trueppm_api/apps/agents/migrations/0002_agentactioncheckpoint.py +71 -0
  54. trueppm_api/apps/agents/migrations/0003_agentactionrefusaldetail.py +58 -0
  55. trueppm_api/apps/agents/migrations/__init__.py +0 -0
  56. trueppm_api/apps/agents/models.py +371 -0
  57. trueppm_api/apps/agents/refusal.py +103 -0
  58. trueppm_api/apps/agents/serializers.py +85 -0
  59. trueppm_api/apps/agents/services.py +397 -0
  60. trueppm_api/apps/agents/signals.py +30 -0
  61. trueppm_api/apps/agents/urls.py +15 -0
  62. trueppm_api/apps/agents/views.py +109 -0
  63. trueppm_api/apps/csvimport/__init__.py +12 -0
  64. trueppm_api/apps/csvimport/apps.py +11 -0
  65. trueppm_api/apps/csvimport/mapping.py +363 -0
  66. trueppm_api/apps/csvimport/migrations/0001_initial.py +74 -0
  67. trueppm_api/apps/csvimport/migrations/0001_squashed_0003_release_0_4.py +90 -0
  68. trueppm_api/apps/csvimport/migrations/0002_schedule_outline_batch_operations.py +37 -0
  69. trueppm_api/apps/csvimport/migrations/0003_csvimportrequest_date_order_and_more.py +26 -0
  70. trueppm_api/apps/csvimport/migrations/__init__.py +0 -0
  71. trueppm_api/apps/csvimport/models.py +111 -0
  72. trueppm_api/apps/csvimport/parser.py +1825 -0
  73. trueppm_api/apps/csvimport/services.py +48 -0
  74. trueppm_api/apps/csvimport/tasks.py +459 -0
  75. trueppm_api/apps/csvimport/template.py +37 -0
  76. trueppm_api/apps/csvimport/urls.py +50 -0
  77. trueppm_api/apps/csvimport/views.py +793 -0
  78. trueppm_api/apps/history/__init__.py +0 -0
  79. trueppm_api/apps/history/apps.py +12 -0
  80. trueppm_api/apps/history/changelog.py +359 -0
  81. trueppm_api/apps/history/diff_policy.py +178 -0
  82. trueppm_api/apps/history/serializers.py +104 -0
  83. trueppm_api/apps/history/signals.py +82 -0
  84. trueppm_api/apps/history/tasks.py +105 -0
  85. trueppm_api/apps/history/urls.py +38 -0
  86. trueppm_api/apps/history/views.py +443 -0
  87. trueppm_api/apps/idempotency/__init__.py +0 -0
  88. trueppm_api/apps/idempotency/apps.py +11 -0
  89. trueppm_api/apps/idempotency/migrations/0001_initial.py +71 -0
  90. trueppm_api/apps/idempotency/migrations/__init__.py +0 -0
  91. trueppm_api/apps/idempotency/mixins.py +226 -0
  92. trueppm_api/apps/idempotency/models.py +75 -0
  93. trueppm_api/apps/idempotency/tasks.py +61 -0
  94. trueppm_api/apps/integrations/__init__.py +13 -0
  95. trueppm_api/apps/integrations/apps.py +59 -0
  96. trueppm_api/apps/integrations/connections.py +806 -0
  97. trueppm_api/apps/integrations/encryption.py +92 -0
  98. trueppm_api/apps/integrations/external_sources.py +863 -0
  99. trueppm_api/apps/integrations/git_automation_services.py +231 -0
  100. trueppm_api/apps/integrations/git_webhook_auth.py +243 -0
  101. trueppm_api/apps/integrations/http.py +597 -0
  102. trueppm_api/apps/integrations/me_work.py +218 -0
  103. trueppm_api/apps/integrations/migrations/0001_initial.py +64 -0
  104. trueppm_api/apps/integrations/migrations/0001_squashed_0006_tasklink_description_tasklink_preview_type_and_more.py +187 -0
  105. trueppm_api/apps/integrations/migrations/0002_tasklink.py +67 -0
  106. trueppm_api/apps/integrations/migrations/0003_tasklink_tasklink_serverver_idx.py +17 -0
  107. trueppm_api/apps/integrations/migrations/0004_tasklink_custom_title_tasklink_labels.py +25 -0
  108. trueppm_api/apps/integrations/migrations/0005_boardautomation.py +56 -0
  109. trueppm_api/apps/integrations/migrations/0006_tasklink_description_tasklink_preview_type_and_more.py +40 -0
  110. trueppm_api/apps/integrations/migrations/0007_squashed_0014_release_0_4.py +225 -0
  111. trueppm_api/apps/integrations/migrations/0007_tasklink_created_at.py +23 -0
  112. trueppm_api/apps/integrations/migrations/0008_integrationcredential_config_externalworkitem.py +66 -0
  113. trueppm_api/apps/integrations/migrations/0009_externalsyncrequest_and_more.py +96 -0
  114. trueppm_api/apps/integrations/migrations/0010_externalworkitem_due_date.py +17 -0
  115. trueppm_api/apps/integrations/migrations/0011_tasklink_sync_seq_tasklink_tasklink_syncseq_idx.py +22 -0
  116. trueppm_api/apps/integrations/migrations/0012_boardautomation_last_delivery_at_and_more.py +42 -0
  117. trueppm_api/apps/integrations/migrations/0013_externalsyncrequest_attempt_count_and_more.py +26 -0
  118. trueppm_api/apps/integrations/migrations/0014_tasklink_created_by.py +27 -0
  119. trueppm_api/apps/integrations/migrations/__init__.py +0 -0
  120. trueppm_api/apps/integrations/models.py +635 -0
  121. trueppm_api/apps/integrations/notification_channels.py +57 -0
  122. trueppm_api/apps/integrations/opengraph.py +229 -0
  123. trueppm_api/apps/integrations/outgoing.py +201 -0
  124. trueppm_api/apps/integrations/providers.py +528 -0
  125. trueppm_api/apps/integrations/registry.py +345 -0
  126. trueppm_api/apps/integrations/serializers.py +453 -0
  127. trueppm_api/apps/integrations/services.py +171 -0
  128. trueppm_api/apps/integrations/tasks.py +734 -0
  129. trueppm_api/apps/integrations/throttles.py +165 -0
  130. trueppm_api/apps/integrations/urls.py +77 -0
  131. trueppm_api/apps/integrations/views.py +1158 -0
  132. trueppm_api/apps/jiraimport/__init__.py +8 -0
  133. trueppm_api/apps/jiraimport/apps.py +11 -0
  134. trueppm_api/apps/jiraimport/migrations/0001_initial.py +72 -0
  135. trueppm_api/apps/jiraimport/migrations/__init__.py +0 -0
  136. trueppm_api/apps/jiraimport/models.py +70 -0
  137. trueppm_api/apps/jiraimport/parser.py +350 -0
  138. trueppm_api/apps/jiraimport/services.py +46 -0
  139. trueppm_api/apps/jiraimport/tasks.py +280 -0
  140. trueppm_api/apps/jiraimport/urls.py +15 -0
  141. trueppm_api/apps/jiraimport/views.py +153 -0
  142. trueppm_api/apps/msproject/__init__.py +0 -0
  143. trueppm_api/apps/msproject/apps.py +11 -0
  144. trueppm_api/apps/msproject/dataclasses.py +153 -0
  145. trueppm_api/apps/msproject/exporter.py +551 -0
  146. trueppm_api/apps/msproject/extended_attributes.py +77 -0
  147. trueppm_api/apps/msproject/importer.py +1095 -0
  148. trueppm_api/apps/msproject/migrations/0001_import_request.py +77 -0
  149. trueppm_api/apps/msproject/migrations/0001_squashed_0002_importrequest_creates_project.py +80 -0
  150. trueppm_api/apps/msproject/migrations/0002_importrequest_creates_project.py +15 -0
  151. trueppm_api/apps/msproject/migrations/__init__.py +0 -0
  152. trueppm_api/apps/msproject/models.py +81 -0
  153. trueppm_api/apps/msproject/parser.py +1276 -0
  154. trueppm_api/apps/msproject/serializers.py +136 -0
  155. trueppm_api/apps/msproject/services.py +58 -0
  156. trueppm_api/apps/msproject/tasks.py +439 -0
  157. trueppm_api/apps/msproject/urls.py +39 -0
  158. trueppm_api/apps/msproject/views.py +531 -0
  159. trueppm_api/apps/notifications/__init__.py +7 -0
  160. trueppm_api/apps/notifications/apps.py +15 -0
  161. trueppm_api/apps/notifications/backfill.py +79 -0
  162. trueppm_api/apps/notifications/categories.py +112 -0
  163. trueppm_api/apps/notifications/delivery_limits.py +258 -0
  164. trueppm_api/apps/notifications/digests.py +462 -0
  165. trueppm_api/apps/notifications/email_backend.py +350 -0
  166. trueppm_api/apps/notifications/email_health.py +128 -0
  167. trueppm_api/apps/notifications/migrations/0001_initial.py +207 -0
  168. trueppm_api/apps/notifications/migrations/0001_squashed_0006_notification_task.py +299 -0
  169. trueppm_api/apps/notifications/migrations/0002_project_notification_preference.py +67 -0
  170. trueppm_api/apps/notifications/migrations/0003_projectnotificationpreference_paused.py +17 -0
  171. trueppm_api/apps/notifications/migrations/0004_clean_unknown_matrix_keys.py +30 -0
  172. trueppm_api/apps/notifications/migrations/0005_notification_body_notification_event_type_and_more.py +27 -0
  173. trueppm_api/apps/notifications/migrations/0006_notification_task.py +25 -0
  174. trueppm_api/apps/notifications/migrations/0007_squashed_0011_release_0_4.py +204 -0
  175. trueppm_api/apps/notifications/migrations/0007_workspaceemailsettings.py +80 -0
  176. trueppm_api/apps/notifications/migrations/0008_notification_snoozed_until.py +17 -0
  177. trueppm_api/apps/notifications/migrations/0009_usernotificationsettings.py +43 -0
  178. trueppm_api/apps/notifications/migrations/0010_projectnotificationpreference_schema_version.py +20 -0
  179. trueppm_api/apps/notifications/migrations/0011_usernotificationsettings_digest_hour_and_more.py +96 -0
  180. trueppm_api/apps/notifications/migrations/__init__.py +0 -0
  181. trueppm_api/apps/notifications/models.py +1148 -0
  182. trueppm_api/apps/notifications/receivers.py +155 -0
  183. trueppm_api/apps/notifications/schema_migrations.py +56 -0
  184. trueppm_api/apps/notifications/serializers.py +1094 -0
  185. trueppm_api/apps/notifications/services.py +1489 -0
  186. trueppm_api/apps/notifications/tasks.py +762 -0
  187. trueppm_api/apps/notifications/throttles.py +98 -0
  188. trueppm_api/apps/notifications/urls.py +97 -0
  189. trueppm_api/apps/notifications/views.py +919 -0
  190. trueppm_api/apps/observability/__init__.py +0 -0
  191. trueppm_api/apps/observability/apps.py +31 -0
  192. trueppm_api/apps/observability/logging.py +213 -0
  193. trueppm_api/apps/observability/migrations/0001_initial.py +35 -0
  194. trueppm_api/apps/observability/migrations/0001_squashed_0003_alter_purgerun_trigger.py +154 -0
  195. trueppm_api/apps/observability/migrations/0002_purgerun_retentionpolicy_retentionschedule.py +131 -0
  196. trueppm_api/apps/observability/migrations/0003_alter_purgerun_trigger.py +21 -0
  197. trueppm_api/apps/observability/migrations/0004_alter_retentionpolicy_key.py +28 -0
  198. trueppm_api/apps/observability/migrations/__init__.py +0 -0
  199. trueppm_api/apps/observability/models.py +141 -0
  200. trueppm_api/apps/observability/otel/__init__.py +45 -0
  201. trueppm_api/apps/observability/otel/attributes.py +247 -0
  202. trueppm_api/apps/observability/otel/export_health.py +533 -0
  203. trueppm_api/apps/observability/otel/instrumentation.py +351 -0
  204. trueppm_api/apps/observability/otel/metrics.py +566 -0
  205. trueppm_api/apps/observability/otel/provider.py +511 -0
  206. trueppm_api/apps/observability/otel/request_attributes.py +204 -0
  207. trueppm_api/apps/observability/purge_registry.py +124 -0
  208. trueppm_api/apps/observability/retention.py +139 -0
  209. trueppm_api/apps/observability/selectors.py +993 -0
  210. trueppm_api/apps/observability/serializers.py +142 -0
  211. trueppm_api/apps/observability/services.py +407 -0
  212. trueppm_api/apps/observability/tasks.py +266 -0
  213. trueppm_api/apps/observability/urls.py +27 -0
  214. trueppm_api/apps/observability/views.py +537 -0
  215. trueppm_api/apps/profiles/__init__.py +0 -0
  216. trueppm_api/apps/profiles/apps.py +15 -0
  217. trueppm_api/apps/profiles/constants.py +54 -0
  218. trueppm_api/apps/profiles/migrations/0001_initial.py +55 -0
  219. trueppm_api/apps/profiles/migrations/0001_squashed_0004_userprofile_role_context.py +125 -0
  220. trueppm_api/apps/profiles/migrations/0002_userprofile_hidden_views.py +17 -0
  221. trueppm_api/apps/profiles/migrations/0003_projectvisit.py +63 -0
  222. trueppm_api/apps/profiles/migrations/0004_userprofile_role_context.py +26 -0
  223. trueppm_api/apps/profiles/migrations/0005_squashed_0009_release_0_4.py +128 -0
  224. trueppm_api/apps/profiles/migrations/0005_userprofile_schedule_in_deliver.py +20 -0
  225. trueppm_api/apps/profiles/migrations/0006_userprofile_date_format_userprofile_timezone.py +36 -0
  226. trueppm_api/apps/profiles/migrations/0007_userpin.py +91 -0
  227. trueppm_api/apps/profiles/migrations/0008_remove_userprofile_schedule_in_deliver.py +71 -0
  228. trueppm_api/apps/profiles/migrations/0009_auth_user_email_upper_idx.py +81 -0
  229. trueppm_api/apps/profiles/migrations/__init__.py +0 -0
  230. trueppm_api/apps/profiles/models.py +276 -0
  231. trueppm_api/apps/profiles/serializers.py +199 -0
  232. trueppm_api/apps/profiles/services.py +541 -0
  233. trueppm_api/apps/profiles/views.py +124 -0
  234. trueppm_api/apps/projects/__init__.py +0 -0
  235. trueppm_api/apps/projects/actual_date_rules.py +163 -0
  236. trueppm_api/apps/projects/amend.py +133 -0
  237. trueppm_api/apps/projects/apps.py +38 -0
  238. trueppm_api/apps/projects/asset_feed.py +459 -0
  239. trueppm_api/apps/projects/asset_views.py +317 -0
  240. trueppm_api/apps/projects/attachment_policy.py +278 -0
  241. trueppm_api/apps/projects/authentication.py +458 -0
  242. trueppm_api/apps/projects/backfill.py +459 -0
  243. trueppm_api/apps/projects/backlog_services.py +324 -0
  244. trueppm_api/apps/projects/backlog_views.py +302 -0
  245. trueppm_api/apps/projects/batch_operation_views.py +264 -0
  246. trueppm_api/apps/projects/blocker_services.py +510 -0
  247. trueppm_api/apps/projects/board_activity.py +462 -0
  248. trueppm_api/apps/projects/board_activity_views.py +186 -0
  249. trueppm_api/apps/projects/board_lanes.py +134 -0
  250. trueppm_api/apps/projects/bulk_settings.py +194 -0
  251. trueppm_api/apps/projects/bundled_templates.py +215 -0
  252. trueppm_api/apps/projects/calendar_settings.py +180 -0
  253. trueppm_api/apps/projects/ceremony_views.py +244 -0
  254. trueppm_api/apps/projects/commit_moment.py +212 -0
  255. trueppm_api/apps/projects/config_notice.py +1330 -0
  256. trueppm_api/apps/projects/custom_field_values.py +266 -0
  257. trueppm_api/apps/projects/decisions_services.py +132 -0
  258. trueppm_api/apps/projects/decisions_views.py +97 -0
  259. trueppm_api/apps/projects/estimation_scale.py +126 -0
  260. trueppm_api/apps/projects/export_bundle.py +423 -0
  261. trueppm_api/apps/projects/fixtures/seeds/atlas-platform-launch.json +4278 -0
  262. trueppm_api/apps/projects/fixtures/seeds/aurora-mobile-app.json +2001 -0
  263. trueppm_api/apps/projects/fixtures/seeds/bayside-civic-center.json +1827 -0
  264. trueppm_api/apps/projects/fixtures/seeds/ga-launch.json +1909 -0
  265. trueppm_api/apps/projects/fixtures/seeds/helios-crm-replacement.json +1410 -0
  266. trueppm_api/apps/projects/guardrail_policy_source.py +269 -0
  267. trueppm_api/apps/projects/inbound_sync.py +555 -0
  268. trueppm_api/apps/projects/iteration_label.py +85 -0
  269. trueppm_api/apps/projects/key_views.py +468 -0
  270. trueppm_api/apps/projects/keys.py +205 -0
  271. trueppm_api/apps/projects/lifecycle.py +191 -0
  272. trueppm_api/apps/projects/management/__init__.py +0 -0
  273. trueppm_api/apps/projects/management/commands/__init__.py +0 -0
  274. trueppm_api/apps/projects/management/commands/backfill_in_progress_status.py +92 -0
  275. trueppm_api/apps/projects/management/commands/create_demo_share_link.py +368 -0
  276. trueppm_api/apps/projects/management/commands/export_program.py +50 -0
  277. trueppm_api/apps/projects/management/commands/import_seed.py +165 -0
  278. trueppm_api/apps/projects/management/commands/load_sample_project.py +514 -0
  279. trueppm_api/apps/projects/management/commands/seed_capacity.py +406 -0
  280. trueppm_api/apps/projects/management/commands/seed_integration_fixtures.py +192 -0
  281. trueppm_api/apps/projects/management/commands/shift_sample_dates.py +120 -0
  282. trueppm_api/apps/projects/mcp_settings.py +305 -0
  283. trueppm_api/apps/projects/methodology.py +178 -0
  284. trueppm_api/apps/projects/migration_helpers.py +75 -0
  285. trueppm_api/apps/projects/migrations/0001_initial.py +208 -0
  286. trueppm_api/apps/projects/migrations/0001_squashed_0094_project_decisions_policy.py +5659 -0
  287. trueppm_api/apps/projects/migrations/0002_alter_uuid_pk_serialize_false.py +57 -0
  288. trueppm_api/apps/projects/migrations/0003_rename_task_project_index.py +25 -0
  289. trueppm_api/apps/projects/migrations/0004_soft_delete_and_dependency_versioned.py +70 -0
  290. trueppm_api/apps/projects/migrations/0005_task_assignee.py +33 -0
  291. trueppm_api/apps/projects/migrations/0006_task_utilization_index.py +31 -0
  292. trueppm_api/apps/projects/migrations/0007_task_is_milestone.py +28 -0
  293. trueppm_api/apps/projects/migrations/0008_baseline.py +119 -0
  294. trueppm_api/apps/projects/migrations/0009_historicaldependency_historicalproject_and_more.py +210 -0
  295. trueppm_api/apps/projects/migrations/0010_risk.py +229 -0
  296. trueppm_api/apps/projects/migrations/0011_task_status.py +27 -0
  297. trueppm_api/apps/projects/migrations/0012_task_status.py +27 -0
  298. trueppm_api/apps/projects/migrations/0013_task_planned_start.py +24 -0
  299. trueppm_api/apps/projects/migrations/0014_short_hex_ids.py +74 -0
  300. trueppm_api/apps/projects/migrations/0015_backfill_short_ids.py +48 -0
  301. trueppm_api/apps/projects/migrations/0016_task_actual_dates.py +42 -0
  302. trueppm_api/apps/projects/migrations/0017_boardcolumnconfig.py +43 -0
  303. trueppm_api/apps/projects/migrations/0018_estimation_governance.py +62 -0
  304. trueppm_api/apps/projects/migrations/0019_backfill_wbs_paths.py +28 -0
  305. trueppm_api/apps/projects/migrations/0020_task_status_5col.py +65 -0
  306. trueppm_api/apps/projects/migrations/0021_boardsavedview.py +64 -0
  307. trueppm_api/apps/projects/migrations/0022_task_status_changed_at_priority_rank.py +35 -0
  308. trueppm_api/apps/projects/migrations/0023_risk_framework_fields.py +96 -0
  309. trueppm_api/apps/projects/migrations/0024_riskcomment.py +52 -0
  310. trueppm_api/apps/projects/migrations/0025_sprint.py +352 -0
  311. trueppm_api/apps/projects/migrations/0026_project_methodology.py +30 -0
  312. trueppm_api/apps/projects/migrations/0027_sprint_retro.py +89 -0
  313. trueppm_api/apps/projects/migrations/0028_normalize_notes_field.py +42 -0
  314. trueppm_api/apps/projects/migrations/0029_complete_implies_full_progress.py +38 -0
  315. trueppm_api/apps/projects/migrations/0030_review_implies_full_progress.py +37 -0
  316. trueppm_api/apps/projects/migrations/0031_task_remaining_points.py +22 -0
  317. trueppm_api/apps/projects/migrations/0032_task_is_subtask_and_sprint_scope_change.py +90 -0
  318. trueppm_api/apps/projects/migrations/0033_task_my_work_index.py +38 -0
  319. trueppm_api/apps/projects/migrations/0034_inbound_task_sync.py +313 -0
  320. trueppm_api/apps/projects/migrations/0035_retro_versioned_and_suggested_assignee.py +173 -0
  321. trueppm_api/apps/projects/migrations/0036_program_entity_and_membership.py +157 -0
  322. trueppm_api/apps/projects/migrations/0037_sprint_capacity_points.py +20 -0
  323. trueppm_api/apps/projects/migrations/0038_taskcomment_commentreaction_commentacknowledgement_and_more.py +233 -0
  324. trueppm_api/apps/projects/migrations/0039_apitoken_and_more.py +88 -0
  325. trueppm_api/apps/projects/migrations/0040_program_general_fields.py +119 -0
  326. trueppm_api/apps/projects/migrations/0041_ceremony_template_and_phase_gate_config.py +210 -0
  327. trueppm_api/apps/projects/migrations/0041_project_general_fields.py +106 -0
  328. trueppm_api/apps/projects/migrations/0042_merge_20260522_0410.py +12 -0
  329. trueppm_api/apps/projects/migrations/0042_program_rollup_config.py +95 -0
  330. trueppm_api/apps/projects/migrations/0042_workflow_color_and_custom_fields.py +94 -0
  331. trueppm_api/apps/projects/migrations/0043_merge_20260522_1118.py +10 -0
  332. trueppm_api/apps/projects/migrations/0044_merge_20260522_rollup.py +10 -0
  333. trueppm_api/apps/projects/migrations/0044_project_archive_program_close.py +119 -0
  334. trueppm_api/apps/projects/migrations/0045_program_risk_policy.py +78 -0
  335. trueppm_api/apps/projects/migrations/0046_merge_20260523_2248.py +12 -0
  336. trueppm_api/apps/projects/migrations/0047_apitokenauditentry_program_and_more.py +55 -0
  337. trueppm_api/apps/projects/migrations/0048_historicalprogram_color_program_color.py +32 -0
  338. trueppm_api/apps/projects/migrations/0049_backlog_item.py +112 -0
  339. trueppm_api/apps/projects/migrations/0050_backlog_item_trgm_search.py +26 -0
  340. trueppm_api/apps/projects/migrations/0051_alter_calendar_working_days_alter_dependency_lag_and_more.py +144 -0
  341. trueppm_api/apps/projects/migrations/0052_recurring_tasks.py +278 -0
  342. trueppm_api/apps/projects/migrations/0053_dependency_dep_pred_serverver_idx_and_more.py +56 -0
  343. trueppm_api/apps/projects/migrations/0054_sprintscopechange_goal_impact_and_more.py +117 -0
  344. trueppm_api/apps/projects/migrations/0055_historicaltask_sprint_pending_and_more.py +51 -0
  345. trueppm_api/apps/projects/migrations/0056_historicalproject_prioritization_model_and_more.py +276 -0
  346. trueppm_api/apps/projects/migrations/0057_historicalsprint_binding_committed_snapshot_and_more.py +58 -0
  347. trueppm_api/apps/projects/migrations/0058_historicaltask_delivery_mode_and_more.py +72 -0
  348. trueppm_api/apps/projects/migrations/0059_forecastsnapshot.py +80 -0
  349. trueppm_api/apps/projects/migrations/0060_historicalprojectsignalprivacypolicy_and_more.py +90 -0
  350. trueppm_api/apps/projects/migrations/0061_baselinetask_story_points.py +17 -0
  351. trueppm_api/apps/projects/migrations/0062_project_is_sample.py +22 -0
  352. trueppm_api/apps/projects/migrations/0063_historicalsprint_wip_limit_sprint_wip_limit.py +22 -0
  353. trueppm_api/apps/projects/migrations/0064_sprinttaskoutcome.py +97 -0
  354. trueppm_api/apps/projects/migrations/0065_historicalsprint_goal_outcome_sprint_goal_outcome.py +32 -0
  355. trueppm_api/apps/projects/migrations/0066_historicalproject_lead_project_lead.py +38 -0
  356. trueppm_api/apps/projects/migrations/0067_sprint_exclude_from_velocity.py +22 -0
  357. trueppm_api/apps/projects/migrations/0068_project_recalculated_at.py +23 -0
  358. trueppm_api/apps/projects/migrations/0069_iteration_label.py +22 -0
  359. trueppm_api/apps/projects/migrations/0070_historicalprogram_iteration_label_and_more.py +32 -0
  360. trueppm_api/apps/projects/migrations/0071_backfill_iteration_label_inherit.py +35 -0
  361. trueppm_api/apps/projects/migrations/0072_pulseresponse_retroboarditem.py +129 -0
  362. trueppm_api/apps/projects/migrations/0073_sprinttaskoutcome_demo_ready.py +17 -0
  363. trueppm_api/apps/projects/migrations/0074_historicaltask_blocked_reason_task_blocked_reason.py +30 -0
  364. trueppm_api/apps/projects/migrations/0075_risk_decimal_short_id.py +42 -0
  365. trueppm_api/apps/projects/migrations/0076_sprinttaskoutcome_review_polish.py +45 -0
  366. trueppm_api/apps/projects/migrations/0077_task_blocker_fields.py +111 -0
  367. trueppm_api/apps/projects/migrations/0078_alter_risktask_unique_together_and_more.py +22 -0
  368. trueppm_api/apps/projects/migrations/0079_historicalproject_status_date_project_status_date.py +22 -0
  369. trueppm_api/apps/projects/migrations/0080_alter_historicaltask_type_alter_task_type.py +46 -0
  370. trueppm_api/apps/projects/migrations/0081_historicalprogram_allow_guests_and_more.py +52 -0
  371. trueppm_api/apps/projects/migrations/0082_project_last_sync_version.py +90 -0
  372. trueppm_api/apps/projects/migrations/0083_historicalprogram_mc_history_attribution_audience_and_more.py +108 -0
  373. trueppm_api/apps/projects/migrations/0084_tasknote.py +71 -0
  374. trueppm_api/apps/projects/migrations/0085_sprint_ix_sprint_velocity.py +33 -0
  375. trueppm_api/apps/projects/migrations/0086_board_card_search_trgm.py +33 -0
  376. trueppm_api/apps/projects/migrations/0087_historicalprogram_task_duration_change_percent_policy_and_more.py +155 -0
  377. trueppm_api/apps/projects/migrations/0088_historicalprogram_allowed_attachment_types_and_more.py +61 -0
  378. trueppm_api/apps/projects/migrations/0089_signalceilingraiseproposal_signalceilingraisevote_and_more.py +157 -0
  379. trueppm_api/apps/projects/migrations/0090_historicaltask_proj_histdate_index.py +59 -0
  380. trueppm_api/apps/projects/migrations/0091_project_board_cadence.py +39 -0
  381. trueppm_api/apps/projects/migrations/0092_program_target_date.py +22 -0
  382. trueppm_api/apps/projects/migrations/0093_cross_project_dependency_consent.py +58 -0
  383. trueppm_api/apps/projects/migrations/0094_project_decisions_policy.py +90 -0
  384. trueppm_api/apps/projects/migrations/0095_poker_session_vote.py +127 -0
  385. trueppm_api/apps/projects/migrations/0095_squashed_0097_release_0_3.py +225 -0
  386. trueppm_api/apps/projects/migrations/0096_crossprojectslipconflict.py +91 -0
  387. trueppm_api/apps/projects/migrations/0097_backlogitem_backlogitem_tags_gin_and_more.py +32 -0
  388. trueppm_api/apps/projects/migrations/0098_historicalproject_show_baselines_and_more.py +52 -0
  389. trueppm_api/apps/projects/migrations/0099_apitoken_scopes.py +48 -0
  390. trueppm_api/apps/projects/migrations/0100_task_dep_serverver_idx_concurrent.py +75 -0
  391. trueppm_api/apps/projects/migrations/0101_dependency_deleted_at_task_deleted_at.py +22 -0
  392. trueppm_api/apps/projects/migrations/0102_project_deleted_at_project_proj_isdel_deletedat_idx.py +25 -0
  393. trueppm_api/apps/projects/migrations/0103_taskdurationchangeevent_task_dur_evt_sprint_idx.py +18 -0
  394. trueppm_api/apps/projects/migrations/0104_historicalproject_stale_task_threshold_days_and_more.py +32 -0
  395. trueppm_api/apps/projects/migrations/0104_trash_restore_1113.py +38 -0
  396. trueppm_api/apps/projects/migrations/0105_historical_changelog_indexes.py +76 -0
  397. trueppm_api/apps/projects/migrations/0106_boardsavedview_schema_version.py +20 -0
  398. trueppm_api/apps/projects/migrations/0106_squashed_0158_release_0_4.py +2357 -0
  399. trueppm_api/apps/projects/migrations/0107_task_activity_event.py +70 -0
  400. trueppm_api/apps/projects/migrations/0108_remove_apitoken_api_token_scope_xor_and_more.py +117 -0
  401. trueppm_api/apps/projects/migrations/0109_projectexportjob.py +82 -0
  402. trueppm_api/apps/projects/migrations/0110_sharelink.py +123 -0
  403. trueppm_api/apps/projects/migrations/0111_projectcalendarlayer.py +67 -0
  404. trueppm_api/apps/projects/migrations/0112_sharelink_expires_at_alter_sharelink_content_kind.py +31 -0
  405. trueppm_api/apps/projects/migrations/0113_alter_historicaltask_percent_complete_and_more.py +35 -0
  406. trueppm_api/apps/projects/migrations/0114_historicalproject_default_member_role_and_more.py +28 -0
  407. trueppm_api/apps/projects/migrations/0115_historicalproject_end_date_shift_threshold_days_and_more.py +22 -0
  408. trueppm_api/apps/projects/migrations/0116_alter_taskactivityevent_event_type.py +28 -0
  409. trueppm_api/apps/projects/migrations/0117_label_tasklabel_label_tasks_and_more.py +126 -0
  410. trueppm_api/apps/projects/migrations/0118_programexportjob.py +82 -0
  411. trueppm_api/apps/projects/migrations/0119_historicalprogram_calendar_program_calendar.py +36 -0
  412. trueppm_api/apps/projects/migrations/0120_alter_backlogitem_item_type.py +29 -0
  413. trueppm_api/apps/projects/migrations/0121_task_three_point_estimate_ordered.py +64 -0
  414. trueppm_api/apps/projects/migrations/0122_task_relation.py +173 -0
  415. trueppm_api/apps/projects/migrations/0123_remove_historicalproject_agile_features_and_more.py +20 -0
  416. trueppm_api/apps/projects/migrations/0124_dependency_is_driving.py +17 -0
  417. trueppm_api/apps/projects/migrations/0125_historicalprogram_estimation_scale_and_more.py +68 -0
  418. trueppm_api/apps/projects/migrations/0126_projectcustomfield_show_on_card_taskcustomfieldvalue.py +80 -0
  419. trueppm_api/apps/projects/migrations/0127_historicalprogram_mcp_enabled_and_more.py +32 -0
  420. trueppm_api/apps/projects/migrations/0128_acceptancecriterion_sync_seq_apitoken_sync_seq_and_more.py +192 -0
  421. trueppm_api/apps/projects/migrations/0129_sharelink_show_milestone_dates.py +20 -0
  422. trueppm_api/apps/projects/migrations/0130_programimportjob.py +85 -0
  423. trueppm_api/apps/projects/migrations/0131_historicalprogram_sprint_picker_ready_only_default_and_more.py +32 -0
  424. trueppm_api/apps/projects/migrations/0132_task_scheduled_start.py +17 -0
  425. trueppm_api/apps/projects/migrations/0133_project_status_date_floor_armed_at.py +17 -0
  426. trueppm_api/apps/projects/migrations/0134_task_edited_at_task_seeded_at_task_source_id_and_more.py +65 -0
  427. trueppm_api/apps/projects/migrations/0135_projecttemplate_templateapplication_and_more.py +175 -0
  428. trueppm_api/apps/projects/migrations/0136_schedule_outline_batch_operations.py +118 -0
  429. trueppm_api/apps/projects/migrations/0137_collapse_dual_scope_api_tokens.py +54 -0
  430. trueppm_api/apps/projects/migrations/0138_apitokenauditentry_api_token_audit_owner_idx.py +18 -0
  431. trueppm_api/apps/projects/migrations/0139_historicaltask_duration_unit_task_duration_unit.py +32 -0
  432. trueppm_api/apps/projects/migrations/0140_historicaltask_auto_container_and_more.py +113 -0
  433. trueppm_api/apps/projects/migrations/0141_historicalproject_draft_started_at_and_more.py +44 -0
  434. trueppm_api/apps/projects/migrations/0142_baseline_calendar_hours_per_day_and_more.py +31 -0
  435. trueppm_api/apps/projects/migrations/0143_sprintcloserequest_failure_reason_and_more.py +42 -0
  436. trueppm_api/apps/projects/migrations/0144_projecttemplate_source_project_and_more.py +35 -0
  437. trueppm_api/apps/projects/migrations/0145_seed_bundled_templates.py +65 -0
  438. trueppm_api/apps/projects/migrations/0146_historicaltask_board_lane_task_board_lane.py +32 -0
  439. trueppm_api/apps/projects/migrations/0147_structuraloperation.py +128 -0
  440. trueppm_api/apps/projects/migrations/0148_task_unique_task_wbs_path_per_project_live.py +76 -0
  441. trueppm_api/apps/projects/migrations/0149_drop_workshops_tables.py +42 -0
  442. trueppm_api/apps/projects/migrations/0150_clear_uncommitted_cpm_output.py +130 -0
  443. trueppm_api/apps/projects/migrations/0151_config_notice_request.py +70 -0
  444. trueppm_api/apps/projects/migrations/0152_aggregate_task_wbs_name_idx.py +20 -0
  445. trueppm_api/apps/projects/migrations/0153_program_sample_anchor_date.py +22 -0
  446. trueppm_api/apps/projects/migrations/0154_object_keys.py +184 -0
  447. trueppm_api/apps/projects/migrations/0155_task_milestone_at_day_end.py +20 -0
  448. trueppm_api/apps/projects/migrations/0156_program_import_job_replaced_project_ids.py +17 -0
  449. trueppm_api/apps/projects/migrations/0157_forecastsnapshot_cpm_finish_at_day_start.py +17 -0
  450. trueppm_api/apps/projects/migrations/0158_baselinetask_finish_at_day_start.py +17 -0
  451. trueppm_api/apps/projects/migrations/__init__.py +0 -0
  452. trueppm_api/apps/projects/models.py +9209 -0
  453. trueppm_api/apps/projects/poker_services.py +154 -0
  454. trueppm_api/apps/projects/poker_views.py +398 -0
  455. trueppm_api/apps/projects/product_backlog_services.py +450 -0
  456. trueppm_api/apps/projects/program_label_services.py +94 -0
  457. trueppm_api/apps/projects/program_label_views.py +189 -0
  458. trueppm_api/apps/projects/program_rollup.py +903 -0
  459. trueppm_api/apps/projects/program_schedule.py +767 -0
  460. trueppm_api/apps/projects/program_views.py +3445 -0
  461. trueppm_api/apps/projects/project_templates.py +422 -0
  462. trueppm_api/apps/projects/receivers.py +234 -0
  463. trueppm_api/apps/projects/refusal_codes.py +140 -0
  464. trueppm_api/apps/projects/reorder_services.py +145 -0
  465. trueppm_api/apps/projects/restructure_hooks.py +54 -0
  466. trueppm_api/apps/projects/retro_board_services.py +368 -0
  467. trueppm_api/apps/projects/retro_services.py +285 -0
  468. trueppm_api/apps/projects/risk_import.py +396 -0
  469. trueppm_api/apps/projects/row_identity.py +113 -0
  470. trueppm_api/apps/projects/schema_migrations.py +228 -0
  471. trueppm_api/apps/projects/schemas/seed_v1.json +492 -0
  472. trueppm_api/apps/projects/schemas/seed_v2.json +891 -0
  473. trueppm_api/apps/projects/seed/__init__.py +61 -0
  474. trueppm_api/apps/projects/seed/demo_landing_overlay.py +532 -0
  475. trueppm_api/apps/projects/seed/exporter.py +1717 -0
  476. trueppm_api/apps/projects/seed/forecast_backfill.py +247 -0
  477. trueppm_api/apps/projects/seed/importer.py +2764 -0
  478. trueppm_api/apps/projects/seed/reanchor.py +551 -0
  479. trueppm_api/apps/projects/seed/reldates.py +126 -0
  480. trueppm_api/apps/projects/seed/replace.py +128 -0
  481. trueppm_api/apps/projects/seed/replay.py +1695 -0
  482. trueppm_api/apps/projects/seed/replay_ctx.py +41 -0
  483. trueppm_api/apps/projects/seed/samples.py +427 -0
  484. trueppm_api/apps/projects/seed/validation.py +1169 -0
  485. trueppm_api/apps/projects/serializers.py +12904 -0
  486. trueppm_api/apps/projects/services.py +7525 -0
  487. trueppm_api/apps/projects/share_serializers.py +142 -0
  488. trueppm_api/apps/projects/share_services.py +373 -0
  489. trueppm_api/apps/projects/share_views.py +395 -0
  490. trueppm_api/apps/projects/sharing_settings.py +187 -0
  491. trueppm_api/apps/projects/signal_privacy_services.py +910 -0
  492. trueppm_api/apps/projects/signal_privacy_views.py +485 -0
  493. trueppm_api/apps/projects/signals.py +132 -0
  494. trueppm_api/apps/projects/slip_conflict.py +288 -0
  495. trueppm_api/apps/projects/sprint_cadence.py +453 -0
  496. trueppm_api/apps/projects/sprint_picker_settings.py +132 -0
  497. trueppm_api/apps/projects/standup.py +304 -0
  498. trueppm_api/apps/projects/standup_views.py +99 -0
  499. trueppm_api/apps/projects/structural_operation_services.py +727 -0
  500. trueppm_api/apps/projects/structural_operation_views.py +311 -0
  501. trueppm_api/apps/projects/surface_visibility.py +126 -0
  502. trueppm_api/apps/projects/task_batch_services.py +379 -0
  503. trueppm_api/apps/projects/task_bulk.py +1244 -0
  504. trueppm_api/apps/projects/task_classification.py +561 -0
  505. trueppm_api/apps/projects/task_classification_defaults.py +95 -0
  506. trueppm_api/apps/projects/task_duration_settings.py +142 -0
  507. trueppm_api/apps/projects/task_grouping.py +754 -0
  508. trueppm_api/apps/projects/tasks.py +1979 -0
  509. trueppm_api/apps/projects/template_divergence.py +168 -0
  510. trueppm_api/apps/projects/template_services.py +160 -0
  511. trueppm_api/apps/projects/template_tasks.py +261 -0
  512. trueppm_api/apps/projects/template_views.py +829 -0
  513. trueppm_api/apps/projects/throttles.py +311 -0
  514. trueppm_api/apps/projects/urls.py +1016 -0
  515. trueppm_api/apps/projects/utilization.py +909 -0
  516. trueppm_api/apps/projects/views.py +21225 -0
  517. trueppm_api/apps/projects/wbs_paths.py +119 -0
  518. trueppm_api/apps/resources/__init__.py +0 -0
  519. trueppm_api/apps/resources/apps.py +8 -0
  520. trueppm_api/apps/resources/capacity.py +121 -0
  521. trueppm_api/apps/resources/migrations/0001_initial.py +68 -0
  522. trueppm_api/apps/resources/migrations/0001_squashed_0013_alter_projectresource_unique_together_and_more.py +281 -0
  523. trueppm_api/apps/resources/migrations/0002_alter_uuid_pk_serialize_false.py +36 -0
  524. trueppm_api/apps/resources/migrations/0003_resource_soft_delete.py +30 -0
  525. trueppm_api/apps/resources/migrations/0004_add_taskresource_resource_index.py +25 -0
  526. trueppm_api/apps/resources/migrations/0005_resource_job_role.py +20 -0
  527. trueppm_api/apps/resources/migrations/0006_skill.py +34 -0
  528. trueppm_api/apps/resources/migrations/0007_resource_skill.py +63 -0
  529. trueppm_api/apps/resources/migrations/0008_project_resource.py +63 -0
  530. trueppm_api/apps/resources/migrations/0009_task_skill_requirement.py +60 -0
  531. trueppm_api/apps/resources/migrations/0010_alter_resourceskill_options_and_more.py +20 -0
  532. trueppm_api/apps/resources/migrations/0011_alter_projectresource_notes.py +17 -0
  533. trueppm_api/apps/resources/migrations/0012_add_resource_user_fk.py +26 -0
  534. trueppm_api/apps/resources/migrations/0013_alter_projectresource_unique_together_and_more.py +53 -0
  535. trueppm_api/apps/resources/migrations/0014_projectresource_sync_seq_resource_sync_seq_and_more.py +37 -0
  536. trueppm_api/apps/resources/migrations/0014_squashed_0015_release_0_4.py +47 -0
  537. trueppm_api/apps/resources/migrations/0015_projectresource_deactivated_with_resource.py +17 -0
  538. trueppm_api/apps/resources/migrations/__init__.py +0 -0
  539. trueppm_api/apps/resources/models.py +298 -0
  540. trueppm_api/apps/resources/serializers.py +426 -0
  541. trueppm_api/apps/resources/services.py +465 -0
  542. trueppm_api/apps/resources/urls.py +28 -0
  543. trueppm_api/apps/resources/views.py +1752 -0
  544. trueppm_api/apps/scheduling/__init__.py +0 -0
  545. trueppm_api/apps/scheduling/apps.py +153 -0
  546. trueppm_api/apps/scheduling/calendars.py +144 -0
  547. trueppm_api/apps/scheduling/deadletter.py +91 -0
  548. trueppm_api/apps/scheduling/finish_reading.py +198 -0
  549. trueppm_api/apps/scheduling/forecast_history_settings.py +215 -0
  550. trueppm_api/apps/scheduling/forecast_staleness.py +313 -0
  551. trueppm_api/apps/scheduling/graph_guard.py +263 -0
  552. trueppm_api/apps/scheduling/management/__init__.py +0 -0
  553. trueppm_api/apps/scheduling/management/commands/__init__.py +0 -0
  554. trueppm_api/apps/scheduling/management/commands/prune_forecast_snapshots.py +53 -0
  555. trueppm_api/apps/scheduling/mc_admission.py +181 -0
  556. trueppm_api/apps/scheduling/migrations/0001_failed_task.py +62 -0
  557. trueppm_api/apps/scheduling/migrations/0001_squashed_0007_projectforecastsnapshot.py +309 -0
  558. trueppm_api/apps/scheduling/migrations/0002_schedulerequest.py +78 -0
  559. trueppm_api/apps/scheduling/migrations/0003_add_schedule_request_reason.py +27 -0
  560. trueppm_api/apps/scheduling/migrations/0004_velocity_suggestion.py +94 -0
  561. trueppm_api/apps/scheduling/migrations/0005_montecarlorun.py +61 -0
  562. trueppm_api/apps/scheduling/migrations/0006_montecarlorun_distribution.py +17 -0
  563. trueppm_api/apps/scheduling/migrations/0007_projectforecastsnapshot.py +65 -0
  564. trueppm_api/apps/scheduling/migrations/0008_alter_schedulerequest_reason.py +28 -0
  565. trueppm_api/apps/scheduling/migrations/0008_folded_schedulerequest_reason.py +34 -0
  566. trueppm_api/apps/scheduling/migrations/0009_alter_schedulerequest_reason.py +29 -0
  567. trueppm_api/apps/scheduling/migrations/0010_failedtask_resolution_note_failedtask_resolved_at_and_more.py +43 -0
  568. trueppm_api/apps/scheduling/migrations/0010_squashed_0016_release_0_4.py +106 -0
  569. trueppm_api/apps/scheduling/migrations/0011_failedtask_project.py +26 -0
  570. trueppm_api/apps/scheduling/migrations/0012_montecarlorun_diagnostic.py +17 -0
  571. trueppm_api/apps/scheduling/migrations/0013_montecarlorun_status_date.py +17 -0
  572. trueppm_api/apps/scheduling/migrations/0014_montecarlorun_plan_version.py +17 -0
  573. trueppm_api/apps/scheduling/migrations/0015_projectforecastsnapshot_cpm_finish_at_day_start.py +17 -0
  574. trueppm_api/apps/scheduling/migrations/0016_montecarlorun_finish_readings.py +32 -0
  575. trueppm_api/apps/scheduling/migrations/__init__.py +0 -0
  576. trueppm_api/apps/scheduling/models.py +542 -0
  577. trueppm_api/apps/scheduling/receivers.py +160 -0
  578. trueppm_api/apps/scheduling/risk_premium.py +334 -0
  579. trueppm_api/apps/scheduling/serializers.py +723 -0
  580. trueppm_api/apps/scheduling/services.py +1251 -0
  581. trueppm_api/apps/scheduling/signals.py +56 -0
  582. trueppm_api/apps/scheduling/tasks.py +2248 -0
  583. trueppm_api/apps/scheduling/telemetry.py +80 -0
  584. trueppm_api/apps/scheduling/units.py +35 -0
  585. trueppm_api/apps/scheduling/urls.py +57 -0
  586. trueppm_api/apps/scheduling/views.py +2908 -0
  587. trueppm_api/apps/sso/__init__.py +0 -0
  588. trueppm_api/apps/sso/apps.py +19 -0
  589. trueppm_api/apps/sso/extensions.py +130 -0
  590. trueppm_api/apps/sso/management/__init__.py +0 -0
  591. trueppm_api/apps/sso/management/commands/__init__.py +0 -0
  592. trueppm_api/apps/sso/management/commands/seed_sso_keycloak.py +172 -0
  593. trueppm_api/apps/sso/migrations/0001_initial.py +119 -0
  594. trueppm_api/apps/sso/migrations/0002_remove_oidcprovider_workspace_ssoproviderpolicy_and_more.py +169 -0
  595. trueppm_api/apps/sso/migrations/__init__.py +0 -0
  596. trueppm_api/apps/sso/models.py +148 -0
  597. trueppm_api/apps/sso/serializers.py +446 -0
  598. trueppm_api/apps/sso/services.py +1473 -0
  599. trueppm_api/apps/sso/urls.py +47 -0
  600. trueppm_api/apps/sso/views.py +935 -0
  601. trueppm_api/apps/sync/__init__.py +0 -0
  602. trueppm_api/apps/sync/apps.py +15 -0
  603. trueppm_api/apps/sync/backfill.py +208 -0
  604. trueppm_api/apps/sync/broadcast.py +369 -0
  605. trueppm_api/apps/sync/conflict.py +262 -0
  606. trueppm_api/apps/sync/consumers.py +548 -0
  607. trueppm_api/apps/sync/migrations/0001_initial.py +59 -0
  608. trueppm_api/apps/sync/migrations/0001_squashed_0002_remove_syncbatch_syncbatch_project_client_batch_uniq_and_more.py +77 -0
  609. trueppm_api/apps/sync/migrations/0002_remove_syncbatch_syncbatch_project_client_batch_uniq_and_more.py +41 -0
  610. trueppm_api/apps/sync/migrations/0003_boardevent.py +46 -0
  611. trueppm_api/apps/sync/migrations/0003_squashed_0005_release_0_4.py +77 -0
  612. trueppm_api/apps/sync/migrations/0004_seed_sync_seq.py +24 -0
  613. trueppm_api/apps/sync/migrations/0005_program_sync_sequence.py +35 -0
  614. trueppm_api/apps/sync/migrations/0006_boardevent_per_project_seq.py +77 -0
  615. trueppm_api/apps/sync/migrations/__init__.py +0 -0
  616. trueppm_api/apps/sync/models.py +272 -0
  617. trueppm_api/apps/sync/pagination.py +231 -0
  618. trueppm_api/apps/sync/sequence.py +488 -0
  619. trueppm_api/apps/sync/serializers.py +688 -0
  620. trueppm_api/apps/sync/tasks.py +260 -0
  621. trueppm_api/apps/sync/throttles.py +175 -0
  622. trueppm_api/apps/sync/upload.py +556 -0
  623. trueppm_api/apps/sync/urls.py +17 -0
  624. trueppm_api/apps/sync/views.py +957 -0
  625. trueppm_api/apps/sync/ws_auth.py +193 -0
  626. trueppm_api/apps/taskruns/__init__.py +0 -0
  627. trueppm_api/apps/taskruns/apps.py +11 -0
  628. trueppm_api/apps/taskruns/migrations/0001_initial.py +92 -0
  629. trueppm_api/apps/taskruns/migrations/__init__.py +0 -0
  630. trueppm_api/apps/taskruns/models.py +68 -0
  631. trueppm_api/apps/taskruns/serializers.py +92 -0
  632. trueppm_api/apps/taskruns/tasks.py +60 -0
  633. trueppm_api/apps/taskruns/tracker.py +286 -0
  634. trueppm_api/apps/taskruns/urls.py +46 -0
  635. trueppm_api/apps/taskruns/views.py +195 -0
  636. trueppm_api/apps/teams/__init__.py +8 -0
  637. trueppm_api/apps/teams/apps.py +16 -0
  638. trueppm_api/apps/teams/migrations/0001_initial.py +139 -0
  639. trueppm_api/apps/teams/migrations/0001_squashed_0002_default_teams.py +159 -0
  640. trueppm_api/apps/teams/migrations/0002_default_teams.py +62 -0
  641. trueppm_api/apps/teams/migrations/0003_team_sync_seq_teammembership_sync_seq.py +22 -0
  642. trueppm_api/apps/teams/migrations/0004_backfill_default_teams_on_upgrade.py +49 -0
  643. trueppm_api/apps/teams/migrations/__init__.py +0 -0
  644. trueppm_api/apps/teams/models.py +145 -0
  645. trueppm_api/apps/teams/permissions.py +149 -0
  646. trueppm_api/apps/teams/serializers.py +95 -0
  647. trueppm_api/apps/teams/services.py +440 -0
  648. trueppm_api/apps/teams/signals.py +61 -0
  649. trueppm_api/apps/teams/urls.py +34 -0
  650. trueppm_api/apps/teams/views.py +201 -0
  651. trueppm_api/apps/timetracking/__init__.py +0 -0
  652. trueppm_api/apps/timetracking/apps.py +9 -0
  653. trueppm_api/apps/timetracking/migrations/0001_initial.py +117 -0
  654. trueppm_api/apps/timetracking/migrations/0001_squashed_0004_release_0_4.py +167 -0
  655. trueppm_api/apps/timetracking/migrations/0002_timesheetsubmission.py +46 -0
  656. trueppm_api/apps/timetracking/migrations/0003_timeentry_deleted_at_timeentry_deleted_by.py +31 -0
  657. trueppm_api/apps/timetracking/migrations/0004_timeentry_sync_seq_and_more.py +24 -0
  658. trueppm_api/apps/timetracking/migrations/__init__.py +0 -0
  659. trueppm_api/apps/timetracking/models.py +178 -0
  660. trueppm_api/apps/timetracking/serializers.py +175 -0
  661. trueppm_api/apps/timetracking/services.py +211 -0
  662. trueppm_api/apps/timetracking/urls.py +47 -0
  663. trueppm_api/apps/timetracking/views.py +597 -0
  664. trueppm_api/apps/webhooks/__init__.py +0 -0
  665. trueppm_api/apps/webhooks/apps.py +8 -0
  666. trueppm_api/apps/webhooks/backfill.py +90 -0
  667. trueppm_api/apps/webhooks/dispatch.py +279 -0
  668. trueppm_api/apps/webhooks/migrations/0001_initial.py +146 -0
  669. trueppm_api/apps/webhooks/migrations/0001_squashed_0007_sprint_lifecycle_events.py +249 -0
  670. trueppm_api/apps/webhooks/migrations/0002_alter_webhook_events.py +32 -0
  671. trueppm_api/apps/webhooks/migrations/0003_delivery_status_created_idx.py +17 -0
  672. trueppm_api/apps/webhooks/migrations/0004_webhook_program_alter_webhook_project_and_more.py +64 -0
  673. trueppm_api/apps/webhooks/migrations/0005_webhook_delivery_sequence_numbers.py +30 -0
  674. trueppm_api/apps/webhooks/migrations/0006_webhook_format_alter_webhook_events_and_more.py +61 -0
  675. trueppm_api/apps/webhooks/migrations/0007_sprint_lifecycle_events.py +63 -0
  676. trueppm_api/apps/webhooks/migrations/0008_risk_baseline_comment_events.py +73 -0
  677. trueppm_api/apps/webhooks/migrations/0009_encrypt_webhook_secret_and_failure_counters.py +100 -0
  678. trueppm_api/apps/webhooks/migrations/0010_alter_webhook_disabled_at.py +21 -0
  679. trueppm_api/apps/webhooks/migrations/0011_webhookeditor.py +48 -0
  680. trueppm_api/apps/webhooks/migrations/0012_alter_webhook_disabled_at.py +21 -0
  681. trueppm_api/apps/webhooks/migrations/__init__.py +0 -0
  682. trueppm_api/apps/webhooks/models.py +437 -0
  683. trueppm_api/apps/webhooks/serializers.py +326 -0
  684. trueppm_api/apps/webhooks/tasks.py +680 -0
  685. trueppm_api/apps/webhooks/urls.py +22 -0
  686. trueppm_api/apps/webhooks/views.py +533 -0
  687. trueppm_api/apps/workflow_engine/__init__.py +0 -0
  688. trueppm_api/apps/workflow_engine/apps.py +23 -0
  689. trueppm_api/apps/workflow_engine/migrations/0001_initial.py +230 -0
  690. trueppm_api/apps/workflow_engine/migrations/0001_squashed_0002_remove_workflowhistoryevent_workflow_history_lookup_idx.py +234 -0
  691. trueppm_api/apps/workflow_engine/migrations/0002_remove_workflowhistoryevent_workflow_history_lookup_idx.py +16 -0
  692. trueppm_api/apps/workflow_engine/migrations/0003_workflowoutboxrow_workflow_outbox_recovery_idx.py +21 -0
  693. trueppm_api/apps/workflow_engine/migrations/__init__.py +0 -0
  694. trueppm_api/apps/workflow_engine/models.py +265 -0
  695. trueppm_api/apps/workflow_engine/tasks.py +371 -0
  696. trueppm_api/apps/workspace/__init__.py +0 -0
  697. trueppm_api/apps/workspace/apps.py +10 -0
  698. trueppm_api/apps/workspace/backfill.py +111 -0
  699. trueppm_api/apps/workspace/export.py +254 -0
  700. trueppm_api/apps/workspace/migrations/0001_initial.py +326 -0
  701. trueppm_api/apps/workspace/migrations/0001_squashed_0014_workspacemembership_availability_effective_from_and_more.py +829 -0
  702. trueppm_api/apps/workspace/migrations/0002_remove_workspace_fiscal_year_start_and_more.py +85 -0
  703. trueppm_api/apps/workspace/migrations/0003_workspaceexportjob.py +73 -0
  704. trueppm_api/apps/workspace/migrations/0004_alter_workspaceinvite_status.py +27 -0
  705. trueppm_api/apps/workspace/migrations/0005_workspace_iteration_label_and_more.py +26 -0
  706. trueppm_api/apps/workspace/migrations/0006_alter_groupmembership_unique_together_and_more.py +45 -0
  707. trueppm_api/apps/workspace/migrations/0007_workspace_public_sharing_override_policy.py +21 -0
  708. trueppm_api/apps/workspace/migrations/0008_workspace_mc_history_attribution_audience_and_more.py +44 -0
  709. trueppm_api/apps/workspace/migrations/0009_workspace_methodology_and_more.py +186 -0
  710. trueppm_api/apps/workspace/migrations/0010_workspace_logo.py +38 -0
  711. trueppm_api/apps/workspace/migrations/0011_historicalworkspace_task_duration_change_percent_override_policy_and_more.py +56 -0
  712. trueppm_api/apps/workspace/migrations/0012_historicalworkspace_allowed_attachment_types_and_more.py +64 -0
  713. trueppm_api/apps/workspace/migrations/0013_auditevent.py +70 -0
  714. trueppm_api/apps/workspace/migrations/0014_workspacemembership_availability_effective_from_and_more.py +39 -0
  715. trueppm_api/apps/workspace/migrations/0015_squashed_0027_release_0_4.py +199 -0
  716. trueppm_api/apps/workspace/migrations/0015_trash_restore_1113.py +34 -0
  717. trueppm_api/apps/workspace/migrations/0016_historicalworkspace_calendar_and_more.py +55 -0
  718. trueppm_api/apps/workspace/migrations/0017_historicalworkspace_estimation_scale_and_more.py +38 -0
  719. trueppm_api/apps/workspace/migrations/0018_historicalworkspace_feedback_enabled_and_more.py +32 -0
  720. trueppm_api/apps/workspace/migrations/0019_historicalworkspace_mcp_enabled_and_more.py +22 -0
  721. trueppm_api/apps/workspace/migrations/0020_viewer_ordinal_one.py +34 -0
  722. trueppm_api/apps/workspace/migrations/0021_group_sync_seq_groupmembership_sync_seq_and_more.py +27 -0
  723. trueppm_api/apps/workspace/migrations/0022_historicalworkspace_sprint_picker_ready_only_default_and_more.py +22 -0
  724. trueppm_api/apps/workspace/migrations/0023_alter_auditevent_event_type.py +32 -0
  725. trueppm_api/apps/workspace/migrations/0024_alter_auditevent_event_type.py +33 -0
  726. trueppm_api/apps/workspace/migrations/0025_alter_auditevent_event_type.py +36 -0
  727. trueppm_api/apps/workspace/migrations/0026_alter_auditevent_event_type.py +37 -0
  728. trueppm_api/apps/workspace/migrations/0027_alter_auditevent_event_type.py +42 -0
  729. trueppm_api/apps/workspace/migrations/__init__.py +0 -0
  730. trueppm_api/apps/workspace/models.py +857 -0
  731. trueppm_api/apps/workspace/permissions.py +187 -0
  732. trueppm_api/apps/workspace/serializers.py +590 -0
  733. trueppm_api/apps/workspace/services.py +967 -0
  734. trueppm_api/apps/workspace/signals.py +37 -0
  735. trueppm_api/apps/workspace/tasks.py +616 -0
  736. trueppm_api/apps/workspace/urls.py +113 -0
  737. trueppm_api/apps/workspace/views.py +1581 -0
  738. trueppm_api/asgi.py +49 -0
  739. trueppm_api/celery.py +40 -0
  740. trueppm_api/core/__init__.py +0 -0
  741. trueppm_api/core/admin_site.py +206 -0
  742. trueppm_api/core/auth_views.py +934 -0
  743. trueppm_api/core/constant_time.py +51 -0
  744. trueppm_api/core/csp.py +54 -0
  745. trueppm_api/core/db.py +87 -0
  746. trueppm_api/core/db_session.py +37 -0
  747. trueppm_api/core/demo_read_only.py +314 -0
  748. trueppm_api/core/exception_handlers.py +157 -0
  749. trueppm_api/core/export_downloads.py +56 -0
  750. trueppm_api/core/extension_providers.py +56 -0
  751. trueppm_api/core/extension_signals.py +147 -0
  752. trueppm_api/core/idempotent.py +260 -0
  753. trueppm_api/core/metadata.py +42 -0
  754. trueppm_api/core/middleware.py +51 -0
  755. trueppm_api/core/openapi.py +1221 -0
  756. trueppm_api/core/password_reset.py +513 -0
  757. trueppm_api/core/protect_conflict.py +100 -0
  758. trueppm_api/core/ratelimit.py +148 -0
  759. trueppm_api/core/redis_throttle.py +82 -0
  760. trueppm_api/core/refresh_cookie_policy.py +156 -0
  761. trueppm_api/core/request_body.py +86 -0
  762. trueppm_api/core/security_checks.py +1034 -0
  763. trueppm_api/core/storage_config.py +105 -0
  764. trueppm_api/core/text_decode.py +168 -0
  765. trueppm_api/core/throttling.py +514 -0
  766. trueppm_api/core/valkey.py +214 -0
  767. trueppm_api/core/valkey_cache.py +66 -0
  768. trueppm_api/core/valkey_checks.py +104 -0
  769. trueppm_api/core/valkey_config.py +39 -0
  770. trueppm_api/core/worker_broker_wait.py +149 -0
  771. trueppm_api/core/worker_heartbeat.py +134 -0
  772. trueppm_api/core/worker_selfheal.py +205 -0
  773. trueppm_api/fields.py +36 -0
  774. trueppm_api/permissions.py +30 -0
  775. trueppm_api/py.typed +0 -0
  776. trueppm_api/routing.py +11 -0
  777. trueppm_api/settings/__init__.py +0 -0
  778. trueppm_api/settings/base.py +2605 -0
  779. trueppm_api/settings/dev.py +296 -0
  780. trueppm_api/settings/prod.py +265 -0
  781. trueppm_api/urls.py +217 -0
  782. trueppm_api/workflows/__init__.py +38 -0
  783. trueppm_api/workflows/backends/__init__.py +6 -0
  784. trueppm_api/workflows/backends/default.py +297 -0
  785. trueppm_api/workflows/consumers/__init__.py +11 -0
  786. trueppm_api/workflows/consumers/requeue_failed_task.py +65 -0
  787. trueppm_api/workflows/interface.py +148 -0
  788. trueppm_api/workflows/registry.py +106 -0
  789. trueppm_api/workflows/services.py +90 -0
  790. trueppm_api/wsgi.py +11 -0
  791. trueppm_api-0.4.0.dist-info/METADATA +273 -0
  792. trueppm_api-0.4.0.dist-info/RECORD +799 -0
  793. trueppm_api-0.4.0.dist-info/WHEEL +4 -0
  794. trueppm_api-0.4.0.dist-info/licenses/LICENSE +201 -0
  795. trueppm_api-0.4.0.dist-info/licenses/NOTICE +7 -0
  796. trueppm_api-0.4.0.dist-info/licenses/NOTICES +104 -0
  797. trueppm_api-0.4.0.dist-info/licenses/licenses/GPL-3.0.txt +674 -0
  798. trueppm_api-0.4.0.dist-info/licenses/licenses/LGPL-3.0.txt +165 -0
  799. trueppm_api-0.4.0.dist-info/licenses/licenses/MPL-2.0.txt +373 -0
@@ -0,0 +1,3445 @@
1
+ """ViewSets for the Program entity (ADR-0070).
2
+
3
+ Programs are top-level (not project-scoped), so they live in their own viewset
4
+ rather than under the ProjectViewSet nesting. Membership is nested separately
5
+ in the access app, mirroring how :class:`ProjectMembershipViewSet` lives next
6
+ to :class:`ProjectViewSet`.
7
+
8
+ This module is intentionally thin — the heavy lifting (atomic creation, cascade
9
+ delete, role checks) is in :mod:`trueppm_api.apps.access.services` and
10
+ :mod:`trueppm_api.apps.access.permissions`.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import uuid
17
+ from collections.abc import Iterable
18
+ from dataclasses import asdict, dataclass
19
+ from functools import partial
20
+ from typing import Any, cast
21
+
22
+ from django.core.exceptions import ValidationError as DjangoValidationError
23
+ from django.db import transaction
24
+ from django.db.models import Count, Exists, IntegerField, OuterRef, Q, QuerySet, Subquery
25
+ from django.db.models.functions import Coalesce
26
+ from django.http import FileResponse, Http404, HttpResponse, HttpResponseBase
27
+ from django.shortcuts import get_object_or_404
28
+ from django.urls import reverse
29
+ from django.utils import timezone
30
+ from drf_spectacular.types import OpenApiTypes
31
+ from drf_spectacular.utils import (
32
+ OpenApiParameter,
33
+ OpenApiResponse,
34
+ extend_schema,
35
+ inline_serializer,
36
+ )
37
+ from rest_framework import filters, pagination, serializers, status, viewsets
38
+ from rest_framework.decorators import action
39
+ from rest_framework.permissions import BasePermission, IsAuthenticated
40
+ from rest_framework.request import Request
41
+ from rest_framework.response import Response
42
+ from rest_framework.throttling import UserRateThrottle
43
+
44
+ from trueppm_api.apps.access.models import ProgramMembership
45
+ from trueppm_api.apps.access.permissions import (
46
+ IsProgramAdmin,
47
+ IsProgramMember,
48
+ IsProgramNotClosed,
49
+ IsProgramOwner,
50
+ IsProgramScheduler,
51
+ McpProgramExportConsent,
52
+ McpReadableViewMixin,
53
+ McpScope,
54
+ )
55
+ from trueppm_api.apps.access.services import (
56
+ PROGRAM_LEAD_NOT_MEMBER_DETAIL,
57
+ PROGRAM_OWNER_NOT_MEMBER_DETAIL,
58
+ create_program,
59
+ delete_program_cascade,
60
+ hard_delete_program,
61
+ transfer_program_sponsorship,
62
+ )
63
+ from trueppm_api.apps.idempotency.mixins import IdempotencyMixin
64
+
65
+ # DirectoryPagination is defined in views.py (which does not import this module, so
66
+ # the module-level import is cycle-safe) and shared so /programs/ matches /projects/
67
+ # on the raised page ceiling (ADR-0401).
68
+ from trueppm_api.apps.profiles.services import annotate_is_pinned
69
+ from trueppm_api.apps.projects.bulk_settings import (
70
+ BulkFieldsRequestSerializer,
71
+ ProgramBulkFieldsSerializer,
72
+ ProjectBulkFieldsSerializer,
73
+ apply_bulk_fields,
74
+ build_bulk_response,
75
+ )
76
+ from trueppm_api.apps.projects.lifecycle import not_draft_q, visible_projects
77
+ from trueppm_api.apps.projects.models import (
78
+ Baseline,
79
+ Dependency,
80
+ ExportJobStatus,
81
+ Methodology,
82
+ Program,
83
+ ProgramExportJob,
84
+ ProgramImportJob,
85
+ Project,
86
+ Sprint,
87
+ Task,
88
+ TaskStatus,
89
+ TaskType,
90
+ format_short_id_display,
91
+ )
92
+ from trueppm_api.apps.projects.program_rollup import drift_counts_by_project
93
+ from trueppm_api.apps.projects.serializers import (
94
+ ProgramExportJobSerializer,
95
+ ProgramImportJobSerializer,
96
+ ProgramProjectRowSerializer,
97
+ ProgramResourceContentionSerializer,
98
+ ProgramRiskPolicySerializer,
99
+ ProgramRollupConfigSerializer,
100
+ ProgramRollupSerializer,
101
+ ProgramScheduleSerializer,
102
+ ProgramSerializer,
103
+ SeedImportRequestSerializer,
104
+ )
105
+ from trueppm_api.apps.projects.views import (
106
+ _ALLOCATION_ASSIGNMENT_LIMIT,
107
+ _SCHEDULE_NOT_COMPUTED,
108
+ PIN_ENDPOINT_DESCRIPTION,
109
+ PIN_LIMIT_RESPONSE,
110
+ PROGRAM_PIN_RESPONSE,
111
+ DirectoryPagination,
112
+ _cap_assignments_at_resource_boundary,
113
+ _resolve_allocation_window,
114
+ _ScheduleNotComputedError,
115
+ pin_limit_detail,
116
+ )
117
+ from trueppm_api.apps.workspace.permissions import IsWorkspaceAdmin
118
+ from trueppm_api.core.export_downloads import stream_export_job_or_error
119
+ from trueppm_api.core.openapi import suppress_list_pagination, validation_envelope_400
120
+ from trueppm_api.core.request_body import object_body
121
+
122
+ # Upper bound on sub-programs created by a single split call (#967). Generous
123
+ # enough for "one sub-program per project" on a large program, but caps the
124
+ # unbounded-empty-program creation vector.
125
+ _MAX_SPLITS = 50
126
+
127
+
128
+ class _SeedImporterThrottle(UserRateThrottle):
129
+ """Shared base for the two actions that run the seed importer (#2402).
130
+
131
+ ``import_seed`` and ``load_sample`` both call ``import_seed()``, by a wide
132
+ margin the most expensive write in the API. Each call hard-deletes the
133
+ caller's prior program carrying the same code (memberships → projects →
134
+ cascade over tasks, dependencies, sprints, risks, baselines) and rebuilds the
135
+ document synchronously inside one transaction: per-row saves with
136
+ ``simple_history`` rows attached, the v2 replay timeline, and the
137
+ forecast-history backfill. The bundled default sample alone costs ~3,700
138
+ sequential DB round-trips, and holds a ``select_for_update()`` throughout.
139
+
140
+ Left on the general ``user`` default of 1000/min a single authenticated
141
+ member could drive a thousand full teardown-and-rebuild cycles a minute —
142
+ the resource-exhaustion shape the ``monte_carlo`` scopes already guard
143
+ against, at a higher per-call cost. The two actions get *separate* buckets so
144
+ loading a demo never spends a user's real import allowance.
145
+
146
+ Subclasses ``UserRateThrottle`` (as ``ShareLinkMintThrottle`` does) rather
147
+ than ``ScopedRateThrottle`` deliberately: these are attached per-action
148
+ through the ``@action(throttle_classes=[…])`` kwarg, so the view carries no
149
+ ``throttle_scope`` attribute. ``ScopedRateThrottle.allow_request`` re-reads
150
+ the scope off the view and silently returns True when it finds none, which
151
+ would clobber a class-level ``scope`` and leave the endpoint unthrottled
152
+ while *looking* bounded. ``UserRateThrottle`` resolves the scope from the
153
+ class at construction and already keys the bucket per user.
154
+
155
+ ADR-0604's global kill switch neutralizes these scopes along with every other
156
+ one — it nulls each rate in ``DEFAULT_THROTTLE_RATES``, and a ``None`` rate
157
+ makes ``SimpleRateThrottle.allow_request`` return True immediately.
158
+ """
159
+
160
+
161
+ class LoadSampleThrottle(_SeedImporterThrottle):
162
+ """Caps bundled-sample demo loads per account (#2402)."""
163
+
164
+ scope = "sample_load"
165
+
166
+
167
+ class SeedImportThrottle(_SeedImporterThrottle):
168
+ """Caps caller-supplied seed imports per account (#2402).
169
+
170
+ Strictly cheaper to abuse than :class:`LoadSampleThrottle`: the payload is
171
+ caller-supplied, so the per-call cost is chosen by the attacker rather than
172
+ fixed by a bundled fixture.
173
+ """
174
+
175
+ scope = "seed_import"
176
+
177
+
178
+ class ProgramScheduleThrottle(UserRateThrottle):
179
+ """Caps on-read program schedule computes per account (#2839).
180
+
181
+ ``GET /programs/{id}/schedule/`` runs the deterministic CPM over every member
182
+ project's merged graph (up to ``MAX_PROGRAM_TASKS``) on each read, uncached, so
183
+ on the 1000/min account default a scripted loop is a compute amplifier.
184
+
185
+ Measured cost: a 5,000-task merged read (MAX_PROGRAM_TASKS, one or five member
186
+ projects) takes ~460-480 ms end to end on a developer laptop against local
187
+ Postgres. The default is 60/min, the same tier as the schedule derivation's
188
+ ``cpm_on_read`` scope, whose single-project pass is cheaper: one account at the
189
+ ceiling is 1 read/s x ~0.47 s, about half a core, against ~7.8 cores at the
190
+ 1000/min default.
191
+
192
+ That is below the live page's theoretical ceiling, on purpose. The page's
193
+ member-project sockets share ONE 300 ms debounce, so an open tab sends at most
194
+ one refetch per window (200/min, whatever the member count). One edit fires
195
+ ``task_updated`` at once and, when the async CPM pass commits,
196
+ ``cpm_complete`` + ``task_dates_updated`` (sometimes ``task_run_completed``)
197
+ together, so about 2-3 refetches per edit: 60/min trips at roughly 20-30
198
+ schedule edits a minute across the whole program, per viewing account. The
199
+ bucket is per account, so several open tabs (or programs viewed at once) share
200
+ it. When it trips, the page keeps rendering its last schedule with a "live
201
+ updates paused" notice and refetches once after ``Retry-After`` (at most 60 s),
202
+ or sooner on the next live event — a stale chart for up to a minute, the right
203
+ trade against a merged CPM pass per edit event.
204
+
205
+ ``UserRateThrottle`` for the same reason as the importer throttles above: it is
206
+ attached through ``@action(throttle_classes=[…])``, where ``ScopedRateThrottle``
207
+ would find no ``throttle_scope`` on the view and silently allow everything.
208
+ """
209
+
210
+ scope = "program_schedule"
211
+
212
+
213
+ class SampleDownloadThrottle(UserRateThrottle):
214
+ """Caps bundled-fixture downloads per account (#2490).
215
+
216
+ Deliberately *not* a sibling of :class:`_SeedImporterThrottle`: a download
217
+ streams a file off disk and touches no table, so it belongs in a far more
218
+ generous tier than the teardown-and-rebuild those two guard.
219
+
220
+ Subclasses ``UserRateThrottle`` rather than ``ScopedRateThrottle`` for the
221
+ same reason the importer throttles do: attached per-action through
222
+ ``@action(throttle_classes=[…])``, the view carries no ``throttle_scope``
223
+ attribute, and ``ScopedRateThrottle.allow_request`` silently returns True
224
+ when it cannot find one — leaving the endpoint unthrottled while *looking*
225
+ bounded.
226
+ """
227
+
228
+ scope = "sample_download"
229
+
230
+
231
+ def _if_none_match_matches(header: str | None, etag: str) -> bool:
232
+ """Return True when an ``If-None-Match`` header covers ``etag`` (#2490).
233
+
234
+ Minimal RFC 9110 §13.1.2 handling for the one endpoint that needs it: ``*``
235
+ matches anything, otherwise the comma-separated candidate list is compared
236
+ against our strong tag, tolerating the ``W/`` weak prefix a proxy may add.
237
+ """
238
+ if not header:
239
+ return False
240
+ candidates = [part.strip() for part in header.split(",")]
241
+ if "*" in candidates:
242
+ return True
243
+ return any(candidate.removeprefix("W/") == etag for candidate in candidates)
244
+
245
+
246
+ class SampleCatalogEntrySerializer(serializers.Serializer[Any]):
247
+ """One bundled demo fixture, as advertised by the catalog (#375, #2490).
248
+
249
+ Response-only — the catalog is a read of files inside the installed package,
250
+ so nothing here is ever deserialized from a request.
251
+
252
+ The nullable fields are the honest ones. ``available`` is False when the
253
+ registry names a file this installation does not have; the counts and
254
+ ``schema_version`` are null when the file is present but could not be parsed.
255
+ Neither case hides the fixture from the listing, because the bytes are what
256
+ an auditor came for and a failed summary is our problem, not theirs.
257
+ """
258
+
259
+ key = serializers.CharField(help_text="Registry key, e.g. `atlas-platform-launch`.")
260
+ title = serializers.CharField()
261
+ description = serializers.CharField()
262
+ filename = serializers.CharField(help_text="Name the download is served under.")
263
+ available = serializers.BooleanField(
264
+ help_text="False when the registered fixture is missing from this installation."
265
+ )
266
+ size_bytes = serializers.IntegerField(allow_null=True)
267
+ sha256 = serializers.CharField(
268
+ allow_null=True,
269
+ help_text=(
270
+ "SHA-256 of the exact bytes the download serves, and the value of its "
271
+ "`ETag`. Proves transport integrity — not provenance."
272
+ ),
273
+ )
274
+ schema_version = serializers.CharField(allow_null=True)
275
+ project_count = serializers.IntegerField(allow_null=True)
276
+ task_count = serializers.IntegerField(allow_null=True)
277
+ resource_count = serializers.IntegerField(allow_null=True)
278
+ download_url = serializers.CharField(
279
+ help_text="Server-built download path. Clients link this rather than assembling it."
280
+ )
281
+
282
+
283
+ @dataclass(frozen=True)
284
+ class _SeedPayloadProblem:
285
+ """A request-level reason a seed body could not be read at all (#2418).
286
+
287
+ Distinguished from a *document* problem, which is what validation reports.
288
+ ``is_document_level`` marks the case the dry run answers with ``200
289
+ {valid: false}`` rather than a 400: unparseable JSON is a fact about the
290
+ file the operator handed us, and telling them so is the entire job of a dry
291
+ run. An oversize upload is a fact about the *request* and stays a 400 on
292
+ both paths — we never read it, so we have nothing to diagnose.
293
+ """
294
+
295
+ detail: str
296
+ is_document_level: bool
297
+
298
+
299
+ #: Request-level control fields that ride alongside a seed document but are not
300
+ #: part of it (ADR-0726 §1). Declared by ``SeedImportRequestSerializer``.
301
+ _SEED_CONTROL_FIELDS = frozenset({"replace", "expected_program_id"})
302
+
303
+
304
+ def _seed_concurrency_refusal(user: Any) -> Response | None:
305
+ """Refuse a seed import when the caller already has too many outstanding (#2615).
306
+
307
+ ``SeedImportThrottle`` bounds how *often* a job may be created; nothing
308
+ bounded how many were outstanding. The per-program in-flight de-dupe in
309
+ ``enqueue_program_import`` cannot help on this path — ``import_seed`` creates
310
+ a fresh ``Program`` immediately before enqueuing, so a brand-new program can
311
+ never already have a job and the filter never matches. That left 6/min of
312
+ full subtree builds able to accumulate in the queue indefinitely.
313
+
314
+ Counted per **user**, not per program, because the user is the only stable
315
+ thing across the requests: the program differs on every one of them.
316
+
317
+ Best-effort rather than a locked invariant. This is a resource bound, not a
318
+ security boundary, and a caller who wins a race to N+1 concurrent imports has
319
+ gained nothing that the throttle does not already re-bound one tick later —
320
+ so the cost of serializing every import request against a shared lock is not
321
+ worth paying. ``import_seed`` calls this twice (once before parsing, once
322
+ inside the transaction) which narrows the window without pretending to close
323
+ it.
324
+ """
325
+ from django.conf import settings
326
+
327
+ from trueppm_api.apps.projects.models import ImportJobStatus, ProgramImportJob
328
+
329
+ cap = int(getattr(settings, "SEED_IMPORT_MAX_CONCURRENT_JOBS", 3))
330
+ if cap <= 0: # 0 disables the bound; the throttle is then the only limit
331
+ return None
332
+ outstanding = ProgramImportJob.objects.filter(
333
+ requested_by=user,
334
+ status__in=[ImportJobStatus.PENDING, ImportJobStatus.RUNNING],
335
+ ).count()
336
+ if outstanding < cap:
337
+ return None
338
+ return Response(
339
+ {
340
+ "detail": (
341
+ f"You already have {outstanding} seed imports queued or running "
342
+ f"(limit {cap}). Wait for one to finish, then re-send."
343
+ ),
344
+ "code": "seed_import_concurrency_limit",
345
+ },
346
+ status=status.HTTP_429_TOO_MANY_REQUESTS,
347
+ )
348
+
349
+
350
+ def _seed_slug_taken_response(slug: str) -> Response:
351
+ """``409 seed_slug_taken``: the document's program slug is another program's key.
352
+
353
+ Names only the key the caller sent — never the program holding it, which the
354
+ caller may not be able to see (ADR-1237 §6).
355
+ """
356
+ return Response(
357
+ {
358
+ "detail": (
359
+ f'The program key "{slug}" is already in use. Change program.slug in '
360
+ "the document and import it again."
361
+ ),
362
+ "code": "seed_slug_taken",
363
+ },
364
+ status=status.HTTP_409_CONFLICT,
365
+ )
366
+
367
+
368
+ def _discard_seed_payload(path: str) -> None:
369
+ """Drop a stored seed payload whose import never produced a job row.
370
+
371
+ The retention purge reclaims payloads by walking ``ProgramImportJob`` rows,
372
+ so an object written for a request that then refused is invisible to it
373
+ permanently. Best-effort: a storage error here must not turn a clean 409 into
374
+ a 500, and a leaked object is recoverable by an operator while a wrong status
375
+ code is not.
376
+ """
377
+ import logging
378
+
379
+ from django.core.files.storage import default_storage
380
+
381
+ try:
382
+ default_storage.delete(path)
383
+ except Exception: # pragma: no cover - storage drift; the 409 still stands
384
+ logging.getLogger(__name__).warning("could not discard orphaned seed payload %s", path)
385
+
386
+
387
+ def _read_seed_json_body(
388
+ request: Request, max_bytes: int, too_large: _SeedPayloadProblem
389
+ ) -> tuple[Any, _SeedPayloadProblem | None]:
390
+ """Read a seed document from a raw JSON request body.
391
+
392
+ This path used to be capped only by DATA_UPLOAD_MAX_MEMORY_SIZE (100 MB), so
393
+ posting the same document as a body instead of a file bypassed
394
+ SEED_MAX_UPLOAD_MB entirely. Gate on the raw bytes: ``request.body`` is the
395
+ undecoded payload, so this measures what actually arrived rather than a
396
+ declared Content-Length that may be absent under chunked transfer-encoding.
397
+ """
398
+ try:
399
+ raw = request.body
400
+ except Exception:
401
+ # Stream already consumed (a multipart request with no ``file`` part
402
+ # reaches here). Fall back to the parsed form data, which is bounded by
403
+ # DATA_UPLOAD_MAX_MEMORY_SIZE and carries no document.
404
+ raw = None
405
+
406
+ if raw is None:
407
+ data = request.data
408
+ else:
409
+ if len(raw) > max_bytes:
410
+ return None, too_large
411
+ try:
412
+ data = json.loads(raw.decode("utf-8")) if raw else request.data
413
+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:
414
+ return None, _SeedPayloadProblem(
415
+ detail=f"Request body is not valid JSON: {exc}",
416
+ is_document_level=True,
417
+ )
418
+
419
+ if hasattr(data, "items"):
420
+ # On the multipart path the control fields sit beside ``file`` and never
421
+ # touch the document. On the JSON-body path there is only one object, so
422
+ # they arrive *inside* it — and the seed schema is
423
+ # ``additionalProperties: false``, which would reject the whole document
424
+ # with "'replace' was unexpected". Strip them here so both request shapes
425
+ # present the same document to the validator.
426
+ return {k: v for k, v in data.items() if k not in _SEED_CONTROL_FIELDS}, None
427
+ return data, None
428
+
429
+
430
+ def _read_seed_multipart(
431
+ request: Request, max_bytes: int, too_large: _SeedPayloadProblem
432
+ ) -> tuple[Any, _SeedPayloadProblem | None]:
433
+ """Read a seed document from the multipart ``file`` part."""
434
+ upload = request.FILES.get("file")
435
+ if upload is None:
436
+ return request.data, None
437
+
438
+ # Bound the in-memory parse: an authenticated user must not be able
439
+ # to exhaust memory with a giant upload (mirrors the MSP importer).
440
+ if upload.size is not None and upload.size > max_bytes:
441
+ return None, too_large
442
+ try:
443
+ return json.loads(upload.read().decode("utf-8")), None
444
+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:
445
+ return None, _SeedPayloadProblem(
446
+ detail=f"Uploaded file is not valid JSON: {exc}",
447
+ is_document_level=True,
448
+ )
449
+
450
+
451
+ def _read_seed_payload(request: Request) -> tuple[Any, _SeedPayloadProblem | None]:
452
+ """Read a seed document from a multipart ``file`` or a raw JSON body.
453
+
454
+ Shared by the real import and the dry run so the two cannot drift on the
455
+ upload ceiling or the accepted request shapes — a dry run whose parse rules
456
+ differ from the import's would answer a question nobody asked.
457
+ """
458
+ from django.conf import settings
459
+
460
+ max_bytes = settings.SEED_MAX_UPLOAD_MB * 1024 * 1024
461
+ too_large = _SeedPayloadProblem(
462
+ detail=f"Seed file too large. Maximum: {settings.SEED_MAX_UPLOAD_MB} MB.",
463
+ is_document_level=False,
464
+ )
465
+
466
+ # Branch on the declared content type, NOT on ``request.FILES``. Reading
467
+ # ``FILES`` on a DRF Request calls ``_load_data_and_files()``, which runs the
468
+ # parser — so probing it first would perform the very JSON parse this
469
+ # function exists to bound, and any size check after it could only change the
470
+ # response, never the memory cost.
471
+ if not (request.content_type or "").startswith("multipart/"):
472
+ return _read_seed_json_body(request, max_bytes, too_large)
473
+ return _read_seed_multipart(request, max_bytes, too_large)
474
+
475
+
476
+ class SeedValidateThrottle(UserRateThrottle):
477
+ """Caps seed dry runs per account (#2418).
478
+
479
+ Deliberately *not* a :class:`_SeedImporterThrottle` subclass: the dry run
480
+ never reaches the importer, so it carries none of the teardown-and-rebuild
481
+ cost that bucket exists to bound. It still needs a bound of its own —
482
+ JSON-Schema validation is CPU proportional to a caller-sized document — but
483
+ a looser one, and in a separate bucket so iterating on a file until it
484
+ validates cannot exhaust the allowance for importing the file that finally
485
+ passes.
486
+ """
487
+
488
+ scope = "seed_validate"
489
+
490
+
491
+ def _seed_replace_conflict(*, allow_null: bool = False, required: bool = True) -> Any:
492
+ """A fresh schema for "the program a confirmed re-import would tear down".
493
+
494
+ A factory rather than a module constant because the same shape is nested
495
+ inside two different response envelopes (the ``409`` refusal and the dry
496
+ run's ``replaces`` key), and a DRF serializer instance binds to one parent —
497
+ sharing a single instance across both would be a latent binding bug.
498
+
499
+ The counts are the substance of it: a program *name* is not enough
500
+ information to consent to destroying 812 tasks (ADR-0726 §1).
501
+
502
+ ``allow_null`` differs per envelope and must not be hoisted into the shared
503
+ shape: a ``409`` refusal always names the conflict that caused it, while the
504
+ dry run reports ``null`` whenever nothing collides — which is its ordinary
505
+ answer, not an edge case (#2649).
506
+ """
507
+ return inline_serializer(
508
+ "SeedReplaceConflict",
509
+ {
510
+ "program_id": serializers.UUIDField(),
511
+ "name": serializers.CharField(),
512
+ "code": serializers.CharField(),
513
+ "project_count": serializers.IntegerField(),
514
+ "task_count": serializers.IntegerField(),
515
+ },
516
+ allow_null=allow_null,
517
+ required=required,
518
+ )
519
+
520
+
521
+ SEED_REPLACE_CONFLICT_RESPONSE = inline_serializer(
522
+ "SeedReplaceConflictResponse",
523
+ {
524
+ "detail": serializers.CharField(),
525
+ "code": serializers.CharField(),
526
+ # Absent on ``seed_slug_taken`` (ADR-1237): that refusal names no program,
527
+ # because the one holding the key may be invisible to the caller.
528
+ "conflict": _seed_replace_conflict(required=False),
529
+ },
530
+ )
531
+
532
+ # The ``429`` envelope. Both refusals on this endpoint answer 429 and both carry
533
+ # ``detail``, but only the concurrency bound carries ``code`` — DRF's own
534
+ # throttle response has no code — so it is optional here rather than required
535
+ # (#2615).
536
+ SEED_IMPORT_REFUSED_RESPONSE = inline_serializer(
537
+ "SeedImportRefusedResponse",
538
+ {
539
+ "detail": serializers.CharField(),
540
+ "code": serializers.CharField(required=False),
541
+ },
542
+ )
543
+
544
+ # The ``202`` envelope (ADR-0726 §6). ``program_id`` exists the moment this
545
+ # returns — the shell is created inside the request — so a client can navigate
546
+ # straight to it while the subtree is still building.
547
+ SEED_IMPORT_QUEUED_RESPONSE = inline_serializer(
548
+ "SeedImportQueuedResponse",
549
+ {
550
+ "queued": serializers.BooleanField(),
551
+ "program_id": serializers.UUIDField(),
552
+ "import_request_id": serializers.UUIDField(),
553
+ "replaced_program_id": serializers.UUIDField(allow_null=True),
554
+ },
555
+ )
556
+
557
+
558
+ # Response envelope for the seed dry run (#2418).
559
+ #
560
+ # ``valid`` is the answer; ``errors`` is the complete JSON-path-anchored
561
+ # diagnostic list (empty when valid). The remaining fields echo what the
562
+ # *document claims to be*, so an operator can confirm they grabbed the right
563
+ # file before pointing a wipe-then-recreate import (ADR-0109) at a live program
564
+ # slug — they are read defensively and may be ``null`` on a document too
565
+ # malformed to state them.
566
+ #
567
+ # Declared via ``inline_serializer`` rather than a Serializer subclass because
568
+ # the envelope's ``errors`` key would shadow ``Serializer.errors``, the base
569
+ # property DRF uses to report validation failures. This serializer only ever
570
+ # describes a response shape — it is never instantiated to validate input — but
571
+ # a field named after a base-class property is a trap for whoever tries later.
572
+ SEED_VALIDATE_RESPONSE = inline_serializer(
573
+ "SeedValidateResponse",
574
+ {
575
+ "valid": serializers.BooleanField(),
576
+ "errors": serializers.ListField(child=serializers.CharField()),
577
+ "schema_version": serializers.CharField(allow_null=True),
578
+ "program_slug": serializers.CharField(allow_null=True),
579
+ "program_name": serializers.CharField(allow_null=True),
580
+ "project_count": serializers.IntegerField(),
581
+ "task_count": serializers.IntegerField(),
582
+ "resource_count": serializers.IntegerField(),
583
+ # ADR-0726 §7: what importing this document would tear down, or null.
584
+ # Computed at the view layer, never inside ``inspect_seed`` — that
585
+ # function is pure and lives in a module that never imports the ORM, and
586
+ # the dry run's "persists nothing" guarantee is structural because of it.
587
+ #
588
+ # Nullable, and that is the common case (#2649): ``preview_replacement``
589
+ # answers ``None`` for a free slug, a slug owned by someone else, and any
590
+ # document too malformed to state one — so a client must treat the key as
591
+ # present-but-null, never as proof of a collision.
592
+ "replaces": _seed_replace_conflict(allow_null=True),
593
+ },
594
+ )
595
+
596
+
597
+ class LoadSampleResponseSerializer(serializers.Serializer[Any]):
598
+ """Response envelope for the load-sample action (#1054).
599
+
600
+ ``landing_project_id`` is the project whose first open sprint was assigned to
601
+ the caller — the board a contributor should land on so their assigned work is
602
+ immediately visible; ``null`` when the sample has no open sprint (e.g. the
603
+ waterfall-only sample), in which case the client falls back to the program
604
+ overview. ``sample_key`` echoes the loaded sample so the client renders the
605
+ matching "Start exploring" guidance without having to guess the default.
606
+ """
607
+
608
+ program = ProgramSerializer()
609
+ landing_project_id = serializers.UUIDField(allow_null=True)
610
+ sample_key = serializers.CharField()
611
+
612
+
613
+ class ShiftSampleDatesResponseSerializer(serializers.Serializer[Any]):
614
+ """Response envelope for the shift-sample-dates action (#3481, ADR-1175).
615
+
616
+ ``shifted`` is False — with a ``200``, not an error — when the sample is
617
+ already current. Re-anchoring is idempotent by construction (the anchor
618
+ advances with the rows), so a second press is a legitimate no-op rather than a
619
+ fault, and the client renders "already current" instead of a failure.
620
+
621
+ ``days`` is the derivation the UI shows the user: a bulk date move that cannot
622
+ say *how far* everything moved is exactly the number a delivery manager cannot
623
+ defend. ``rows_shifted`` counts rows rewritten, not date columns (see
624
+ ``ShiftReport``), and ``projects`` is how many projects were re-queued for CPM.
625
+ """
626
+
627
+ shifted = serializers.BooleanField()
628
+ days = serializers.IntegerField()
629
+ anchor_date = serializers.DateField()
630
+ rows_shifted = serializers.IntegerField()
631
+ projects = serializers.IntegerField()
632
+
633
+
634
+ def _broadcast_projects_updated(project_ids: list[str]) -> None:
635
+ """Fan ``project_updated`` out to each project's own channel group.
636
+
637
+ One deferred callback for a whole bulk apply. The sends themselves stay
638
+ per-project because each is a distinct channel group — there is no group to
639
+ collapse them into — but the callback registration, and any future batching of
640
+ the replay-buffer write, has a single place to live.
641
+ """
642
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
643
+
644
+ for project_id in project_ids:
645
+ broadcast_board_event(project_id, "project_updated", {"id": project_id})
646
+
647
+
648
+ # ProgramViewSet configures SearchFilter + OrderingFilter for its own `list` route, and
649
+ # drf-spectacular consequently publishes `search` and `ordering` on EVERY list-shaped
650
+ # operation on the viewset — including custom @actions, which build their own querysets
651
+ # and never call `self.filter_queryset()`. The parameters were accepted, documented, and
652
+ # dropped on the floor: worse than a 400, because nothing signals that they did nothing
653
+ # (#3420). An action either honors them (see `projects`) or undeclares them with this.
654
+ _UNDECLARE_FILTER_PARAMS = [
655
+ OpenApiParameter("search", exclude=True),
656
+ OpenApiParameter("ordering", exclude=True),
657
+ ]
658
+
659
+
660
+ def _group_contention_assignments(rows: Iterable[Any]) -> list[dict[str, Any]]:
661
+ """Group assignment rows into per-resource span dicts, each span tagged with its project."""
662
+ resources_map: dict[str, dict[str, Any]] = {}
663
+ for assignment in rows:
664
+ resource = assignment.resource
665
+ rid = str(resource.id)
666
+ if rid not in resources_map:
667
+ # ``email`` is deliberately absent (#3599). This dict bypasses
668
+ # ``ResourceSerializer.to_representation``, which is where the #891
669
+ # harvest control lives, so echoing it here re-opened that control
670
+ # to anyone who can reach a project they created themselves.
671
+ resources_map[rid] = {
672
+ "id": rid,
673
+ "name": resource.name,
674
+ "max_units": str(resource.max_units),
675
+ "tasks": [],
676
+ }
677
+ task = assignment.task
678
+ resources_map[rid]["tasks"].append(
679
+ {
680
+ "assignment_id": str(assignment.id),
681
+ "id": str(task.id),
682
+ "name": task.name,
683
+ "project_id": str(task.project_id),
684
+ "project_name": task.project.name,
685
+ "early_start": task.early_start.isoformat() if task.early_start else None,
686
+ "early_finish": task.early_finish.isoformat() if task.early_finish else None,
687
+ # ADR-0752: the task's SPAN start, read-only CPM output.
688
+ # Null until the next recalculation after upgrade; the
689
+ # client falls back to early_start (same fallback the
690
+ # Coalesce above applies server-side for windowing).
691
+ "scheduled_start": task.scheduled_start.isoformat()
692
+ if task.scheduled_start
693
+ else None,
694
+ "units": str(assignment.units),
695
+ "status": task.status,
696
+ }
697
+ )
698
+
699
+ # Restore in Python the ordering the query no longer does in SQL
700
+ # (ADR-1118): resources by name, then each resource's spans by source
701
+ # project name and span start. `sorted` is stable and the DB already
702
+ # ordered within a resource by (project_id, early_start), so ties resolve
703
+ # deterministically. `early_start` is nullable — unscheduled spans sort
704
+ # last, matching Postgres' ASC NULLS LAST.
705
+ for row in resources_map.values():
706
+ row["tasks"].sort(
707
+ key=lambda t: (
708
+ t["project_name"],
709
+ t["early_start"] is None,
710
+ t["early_start"] or "",
711
+ )
712
+ )
713
+ return sorted(resources_map.values(), key=lambda r: r["name"])
714
+
715
+
716
+ class ProgramViewSet(McpReadableViewMixin, IdempotencyMixin, viewsets.ModelViewSet[Program]):
717
+ """CRUD for programs.
718
+
719
+ URL: ``/api/v1/programs/``
720
+
721
+ Permission matrix (ADR-0070 §RBAC):
722
+ list — IsAuthenticated; queryset filtered to programs the caller is a member of
723
+ retrieve — IsProgramMember (Viewer+)
724
+ create — IsAuthenticated; caller auto-becomes OWNER via ``create_program``
725
+ update — IsProgramAdmin
726
+ destroy — IsProgramOwner; cascade-removes memberships in one transaction
727
+ """
728
+
729
+ # ADR-0678 (#2482): Program rows are filtered on the program's own denial, but
730
+ # five detail actions read CHILD PROJECT data — schedule, rollup, projects,
731
+ # task_search, resource_contention — which the row filter cannot reach. Each
732
+ # scopes explicitly; see ADR-0678 threat-model finding T1.
733
+ mcp_scope = McpScope.AGGREGATE
734
+
735
+ # `schedule` runs the deterministic CPM over every member project's merged graph
736
+ # on each read (#2839), so an mcp:read token gets the compute bucket on that
737
+ # action; the cheap CRUD reads stay on the baseline mcp_read bucket.
738
+ mcp_compute_heavy_actions = frozenset({"schedule"})
739
+
740
+ serializer_class = ProgramSerializer
741
+ pagination_class = DirectoryPagination
742
+ # Parity with ProjectViewSet: name/code substring search so the program
743
+ # switchers and command palette stay findable past the default page (ADR-0401).
744
+ filter_backends = [filters.SearchFilter, filters.OrderingFilter]
745
+ search_fields = ["name", "code"]
746
+ ordering_fields = ["name"]
747
+
748
+ def get_object(self) -> Program:
749
+ """Resolve the program by pk without the SEARCH/ORDERING backends (#3420).
750
+
751
+ ``GenericAPIView.get_object()`` resolves through
752
+ ``self.filter_queryset(self.get_queryset())``, so the SearchFilter configured
753
+ above for the ``list`` route also ran against the **parent lookup** on every
754
+ detail route. A ``?search=`` intended for a nested action's own queryset was
755
+ matched against the *program's* name and code instead, and a program whose name
756
+ did not happen to contain the term was filtered out of its own detail lookup and
757
+ returned **404** — on ``retrieve``, ``projects``, ``rollup``, ``schedule`` and
758
+ every other detail route here. That is worse than the silent drop #3420 was
759
+ filed about, and it is why the ``projects`` action could not simply start
760
+ calling ``filter_queryset()``: the request never reached the point of filtering
761
+ the project rows.
762
+
763
+ **Suppress the backends, not ``filter_queryset()``.** The obvious fix —
764
+ resolving with ``get_object_or_404(self.get_queryset(), ...)`` — is wrong.
765
+ ``McpReadableViewMixin`` enforces the
766
+ ADR-0678 team MCP opt-out in ``filter_queryset()`` *specifically because*
767
+ ``ProgramViewSet`` is one of the three viewsets that builds its queryset from
768
+ scratch instead of chaining to ``super().get_queryset()``, so the mixin's
769
+ ``get_queryset`` hook never runs here. Bypassing ``filter_queryset()`` on the
770
+ detail path therefore fails that opt-out **open** — an agent token reads the
771
+ export of a program that denied it. Emptying ``filter_backends`` for the
772
+ duration of the lookup keeps the mixin's override in the chain (it calls
773
+ ``super().filter_queryset()``, which iterates the reduced list) and drops only
774
+ the two backends that have no business resolving a pk.
775
+
776
+ Suppressed **by name**, not by emptying the list. ``filter_backends = []`` would
777
+ read as "drop whatever is configured", which fails open: a narrowing backend
778
+ added to this viewset later would be silently skipped on every detail route
779
+ while this docstring still claimed only the two cosmetic ones were in scope.
780
+
781
+ The MCP half is pinned by
782
+ ``test_program_detail_routes_honor_the_program_denial_for_an_agent``
783
+ (``tests/apps/access/test_mcp_team_opt_out.py``), which fails against the
784
+ ``get_object_or_404`` form above. Before this branch nothing covered it: the
785
+ existing opted-out detail test exercises ``ProjectViewSet``, which *does* chain
786
+ to ``super().get_queryset()`` and so stays safe by the other hook either way.
787
+ """
788
+ suppressed = (filters.SearchFilter, filters.OrderingFilter)
789
+ original = self.filter_backends
790
+ self.filter_backends = [b for b in original if b not in suppressed]
791
+ try:
792
+ return super().get_object()
793
+ finally:
794
+ self.filter_backends = original
795
+
796
+ def get_permissions(self) -> list[BasePermission]:
797
+ # ADR-0186 §E: append the read-only MCP token guards around the
798
+ # action-specific RBAC list so a mcp:read token is confined to safe
799
+ # methods on every action (no write-branch leak); human auth passes both.
800
+ return [*self._rbac_permissions(), *self.mcp_token_guards()]
801
+
802
+ def _rbac_permissions(self) -> list[BasePermission]:
803
+ # Bootstrap actions: no program exists yet for these to be scoped against
804
+ # (create mints one; import_seed/validate_import work from a standalone seed
805
+ # document and load_sample from a bundled fixture, none an existing
806
+ # program), so there is no membership to check — "any authenticated user
807
+ # may create a program" (ADR-0070 §RBAC) extends to its three seed/sample-
808
+ # driven equivalents. Named explicitly rather than left to the fallback
809
+ # below so the fallback can fail closed for everything else (#2939): these
810
+ # are not the same case as an existing-program write, and conflating them
811
+ # would either 403 legitimate program creation or silently re-open the gap
812
+ # this branch exists to close.
813
+ if self.action in ("create", "import_seed", "validate_import", "load_sample"):
814
+ return [IsAuthenticated()]
815
+ # bulk_project_fields shares update/partial_update's exact gate (ADR-0161:
816
+ # program-admin authority over the program's own projects; the program PK
817
+ # in the URL is the IDOR boundary, and closed programs are not
818
+ # bulk-editable) — merged into one branch to keep this dispatch's branch
819
+ # count in budget (#2939 added the bootstrap-action branch below).
820
+ if self.action in ("update", "partial_update", "bulk_project_fields"):
821
+ return [IsAuthenticated(), IsProgramAdmin(), IsProgramNotClosed()]
822
+ if self.action == "bulk_fields":
823
+ # Workspace → programs matrix (ADR-0161): org-level workspace-admin authority.
824
+ # Program has no workspace FK — the workspace is the singleton — so this is the
825
+ # org-wide admin gate, not a per-program one.
826
+ return [IsAuthenticated(), IsWorkspaceAdmin()]
827
+ if self.action in (
828
+ "destroy",
829
+ "close",
830
+ "reopen",
831
+ "transfer_sponsorship",
832
+ "split",
833
+ "remove_sample",
834
+ "shift_sample_dates",
835
+ ):
836
+ # Owner-only. The first six are lifecycle actions that bypass the
837
+ # IsProgramNotClosed gate via the class's _CLOSE_BYPASS_ACTIONS set —
838
+ # otherwise an Owner could never reopen or delete a closed program.
839
+ #
840
+ # `shift_sample_dates` (#3481) shares the permission LIST but is
841
+ # deliberately absent from that bypass set, so IsProgramNotClosed
842
+ # genuinely binds for it: teardown must survive a closed program, while
843
+ # re-anchoring a closed program's dates is meaningless. The branch is
844
+ # shared rather than split because the difference lives in
845
+ # _CLOSE_BYPASS_ACTIONS, not here — a second branch returning an
846
+ # identical list would imply a distinction this function does not make.
847
+ #
848
+ # IsOrgAdmin / IsOrgScheduler are NOT usable for any of these: both are
849
+ # effectively "any authenticated user" (self-grantable via project
850
+ # create, #3569). shift_sample_dates bulk-rewrites every dated row in a
851
+ # program, so its gate has to be a real object-level one.
852
+ #
853
+ # get_permissions() appends mcp_token_guards() around this list, which
854
+ # is what keeps a read-scoped agent token off a durable bulk write —
855
+ # OSS agents ship read + schedule:simulate only (ADR-0112).
856
+ return [IsAuthenticated(), IsProgramOwner(), IsProgramNotClosed()]
857
+ if self.action in ("rollup_config", "risk_policy"):
858
+ # Method-level split: GET is read-open to any program member
859
+ # (closed programs remain readable for audit/forensics); PATCH
860
+ # requires admin and is blocked on closed programs. DRF evaluates
861
+ # permissions before dispatch, so the discriminator is the HTTP
862
+ # method on the request.
863
+ if self.request.method == "PATCH":
864
+ return [IsAuthenticated(), IsProgramAdmin(), IsProgramNotClosed()]
865
+ return [IsAuthenticated(), IsProgramMember()]
866
+ if self.action in ("rollup", "schedule"):
867
+ # Computed overview rollup / merged program schedule — read-only. Open
868
+ # to any program member, including on closed programs (overview and the
869
+ # cross-project schedule stay available for forensics/archival).
870
+ # Per-project task redaction inside the schedule payload (ADR-0120 D5)
871
+ # is enforced in the action body, not here — a program member who cannot
872
+ # read a member project still reaches the endpoint but sees only that
873
+ # project's ExternalTaskCards.
874
+ return [IsAuthenticated(), IsProgramMember()]
875
+ if self.action == "export":
876
+ # Program seed export — Admin+ for BOTH the GET sync JSON seed and the
877
+ # POST async .tar.gz bundle (#1957, mirroring the project-side gate).
878
+ # The seed dumps team-private data raw across every member project
879
+ # (story points, committed/completed/capacity velocity, per-member
880
+ # effort) with no ADR-0104 field-gating (deferred to 0.5, #1959), so a
881
+ # Viewer/Member reaching it is a bulk ADR-0104 bypass. Bulk export at
882
+ # program grain is a program-admin action. Stays available on closed
883
+ # programs (portability for archival/forensics).
884
+ #
885
+ # McpProgramExportConsent (#3014) governs the GET seed for AGENT callers
886
+ # only: the seed carries every member project's rows verbatim, so without
887
+ # it an mcp:read token reads through the parent what a child team closed
888
+ # to agents. No effect on the POST — TokenReadOnlyMethods already refuses
889
+ # a token there — and none on any human.
890
+ #
891
+ # Program Admin authority does not extend to a member project's content
892
+ # (#4310, ADR-0161 amendment): the export body includes only the member
893
+ # projects the caller holds live ProjectMembership on, enforced in
894
+ # ``export_program`` and the async bundle builder, not here.
895
+ return [IsAuthenticated(), IsProgramAdmin(), McpProgramExportConsent()]
896
+ if self.action in ("export_jobs", "export_job_detail"):
897
+ # Async program export bundle list / poll (#1958, ADR-0219): Admin+,
898
+ # matching the POST enqueue. Available on closed programs; object-level
899
+ # cross-program IDOR (a job_id from another program) is closed in the
900
+ # action bodies via program-scoped lookups.
901
+ #
902
+ # These two report job status, size and timestamps — program-level
903
+ # bookkeeping that names no child project's contents (#3014) — so
904
+ # withholding them behind McpProgramExportConsent would cost an agent
905
+ # the ability to poll a job while protecting nothing.
906
+ return [IsAuthenticated(), IsProgramAdmin()]
907
+ if self.action == "export_job_download":
908
+ # Same Admin+ floor and closed-program availability as the list / poll
909
+ # above, but only the download streams child-project data (#3014), so it
910
+ # additionally carries the agent export-consent gate.
911
+ return [IsAuthenticated(), IsProgramAdmin(), McpProgramExportConsent()]
912
+ if self.action in ("import_job_detail", "mention_reach"):
913
+ # import_job_detail — poll one seed import job (ADR-0726). Admin+,
914
+ # matching the export job poll: the summary reports the program's entity
915
+ # counts, and the error detail can echo validation diagnostics naming
916
+ # projects and tasks the caller must already be entitled to see. The
917
+ # importing caller is the program's OWNER by construction, so this never
918
+ # locks anyone out of a job they started. Object-level cross-program IDOR
919
+ # is closed in the action body via the program-scoped lookup.
920
+ #
921
+ # mention_reach — who @program-stakeholders actually reaches (ADR-0697).
922
+ # Admin+, matching the external-stakeholder registry's own floor
923
+ # (ADR-0264 §3) — the strip this backs only ever renders beside a list
924
+ # the caller can already read, so a lower floor buys nothing, and the
925
+ # internal arm is a partial disclosure of membership across projects the
926
+ # caller may hold no grant on (ADR-0070's explicit-grants boundary). No
927
+ # IsProgramNotClosed: it is a read, and a closed program's alias stays
928
+ # inspectable for forensics.
929
+ #
930
+ # Merged into one branch because the two share an identical permission
931
+ # list; keeps this dispatch's branch count in budget.
932
+ return [IsAuthenticated(), IsProgramAdmin()]
933
+ if self.action == "resource_contention":
934
+ # Resource allocation/contention data is Scheduler+ even on read
935
+ # (web-rule 94, matching the per-project resource-allocation gate);
936
+ # a Viewer or Member must not see who is staffed where.
937
+ return [IsAuthenticated(), IsProgramScheduler()]
938
+ if self.action in ("retrieve", "projects", "integrations_summary", "task_search"):
939
+ # ``task_search`` backs the cross-project dependency picker (ADR-0120
940
+ # D5): a create-assist read, gated exactly like ``projects`` — any
941
+ # program member. ``IsProgramNotClosed`` is a no-op for the GET (it
942
+ # only blocks writes) but is kept for parity with this read group; a
943
+ # closed program is still browsable. The real authorization is the
944
+ # per-project readability narrowing inside the action body (only
945
+ # projects the caller can read are searched), which enforces the D5
946
+ # "creator needs read access to both tasks" rule — the edge itself is
947
+ # created later via the per-project ``/dependencies/`` POST, not here.
948
+ return [IsAuthenticated(), IsProgramMember(), IsProgramNotClosed()]
949
+ # Membership-bound, not bare IsAuthenticated (#2939): every action that
950
+ # legitimately needs no program scope is named above. A future @action
951
+ # landing here unnamed is therefore either a detail=True route (get_object()
952
+ # still runs the real membership check, matching prior behavior exactly) or
953
+ # a GET (`_unresolved_scope_allows` allows safe methods on an unscoped
954
+ # route, same as any other top-level list) — both unaffected — or an unsafe
955
+ # detail=False write, which `_unresolved_scope_allows` (#3767) now DENIES
956
+ # by default instead of silently inheriting bare-authenticated access.
957
+ return [IsAuthenticated(), IsProgramMember()]
958
+
959
+ def perform_update(self, serializer: serializers.BaseSerializer[Program]) -> None:
960
+ # ADR-0441: reassigning a program's working calendar (a different default, or
961
+ # cleared to inherit the workspace) re-points every member project that sets no
962
+ # calendar of its own, so capture the before-value and fan out a CPM recompute
963
+ # to the inheriting projects only when ``calendar`` actually changes. Other
964
+ # program-field edits (name, methodology, sharing, …) never touch scheduling.
965
+ old_calendar_id = serializer.instance.calendar_id if serializer.instance else None
966
+ instance = serializer.save()
967
+ if instance.calendar_id != old_calendar_id:
968
+ from trueppm_api.apps.projects.views import _recalc_projects_for_program_calendar
969
+
970
+ _recalc_projects_for_program_calendar(instance.pk, actor=self.request.user)
971
+
972
+ def get_queryset(self) -> QuerySet[Program]:
973
+ """Programs visible to the current user (those they have membership on).
974
+
975
+ Annotates ``_my_role`` (caller's role on each program), ``project_count``,
976
+ and ``member_count`` so the serializer can render the role chip and
977
+ counts without N+1 queries.
978
+ """
979
+ user = self.request.user
980
+ if not (user and user.is_authenticated):
981
+ return Program.objects.none()
982
+
983
+ my_role_sq = ProgramMembership.objects.filter(
984
+ program=OuterRef("pk"),
985
+ user=user,
986
+ is_deleted=False,
987
+ ).values("role")[:1]
988
+
989
+ # Live member headcount as a correlated Subquery, NOT an aggregate over the
990
+ # ``memberships`` join (#3471). The visibility scope below is an ``Exists``
991
+ # probe rather than a ``memberships__user=user`` join filter for the same
992
+ # reason: a join filter narrows the joined rows to the caller's OWN
993
+ # membership *before* any aggregate over that relation runs, so
994
+ # ``Count("memberships", filter=...)`` counted exactly one row for every
995
+ # program and the directory said "1 member" on a program with 16. An
996
+ # ``Exists`` is a semi-join — it decides row visibility without constraining
997
+ # the rows an aggregate would see — and keeping the count in its own
998
+ # subquery also stops ``memberships`` fanning out against the ``projects``
999
+ # join that ``project_count`` needs.
1000
+ member_count_sq = (
1001
+ ProgramMembership.objects.filter(program=OuterRef("pk"), is_deleted=False)
1002
+ .order_by()
1003
+ .values("program")
1004
+ .annotate(c=Count("pk"))
1005
+ .values("c")
1006
+ )
1007
+
1008
+ qs = (
1009
+ Program.objects.filter(is_deleted=False)
1010
+ .filter(
1011
+ Exists(
1012
+ ProgramMembership.objects.filter(
1013
+ program=OuterRef("pk"),
1014
+ user=user,
1015
+ is_deleted=False,
1016
+ )
1017
+ )
1018
+ )
1019
+ # select_related on ``lead`` so ProgramSerializer.lead_detail does not
1020
+ # incur one extra User query per program on list responses (#523).
1021
+ # select_related ``calendar`` + prefetch its exceptions so
1022
+ # ProgramSerializer.effective_calendar (ADR-0441, with holiday_count) does
1023
+ # not N+1 the program list. The workspace-tier calendar is the shared
1024
+ # singleton, resolved once via the serializer's ``_sharing_workspace`` cache.
1025
+ .select_related("lead", "calendar")
1026
+ .prefetch_related("calendar__exceptions")
1027
+ .annotate(
1028
+ _my_role=Subquery(my_role_sq),
1029
+ # Drafts are excluded (#2962/#3128) so this badge counts the same
1030
+ # set the drill-through lists. ``ProgramViewSet.projects`` already
1031
+ # applies ``visible_projects``, so counting drafts here would make
1032
+ # the directory say 3 and the tab it opens show 2 — a rollup count
1033
+ # that disagrees with its own detail.
1034
+ project_count=Count(
1035
+ "projects",
1036
+ distinct=True,
1037
+ filter=Q(projects__is_deleted=False) & not_draft_q("projects"),
1038
+ ),
1039
+ member_count=Coalesce(Subquery(member_count_sq, output_field=IntegerField()), 0),
1040
+ _is_sample=Exists(
1041
+ Project.objects.filter(program=OuterRef("pk"), is_sample=True, is_deleted=False)
1042
+ ),
1043
+ )
1044
+ .order_by("name")
1045
+ )
1046
+ if getattr(self, "action", None) in ("retrieve", "partial_update", "update"):
1047
+ # The key-rename cap (ADR-1237): the settings page reads this to make
1048
+ # the key field read-only at 10. Detail responses only, so the list
1049
+ # never pays a per-row count.
1050
+ from trueppm_api.apps.projects.models import ObjectKey
1051
+
1052
+ retired_sq = (
1053
+ ObjectKey.objects.filter(program=OuterRef("pk"), is_current=False)
1054
+ .order_by()
1055
+ .values("program")
1056
+ .annotate(c=Count("pk"))
1057
+ .values("c")
1058
+ )
1059
+ qs = qs.annotate(
1060
+ _retired_key_count=Coalesce(Subquery(retired_sq, output_field=IntegerField()), 0)
1061
+ )
1062
+ # `is_pinned` for THIS caller (#2390, ADR-0627). Bound positionally to
1063
+ # `user`, so it can answer "did I pin it" and never "who pinned it".
1064
+ return annotate_is_pinned(qs, user, field="program")
1065
+
1066
+ # -----------------------------------------------------------------------
1067
+ # CRUD
1068
+ # -----------------------------------------------------------------------
1069
+
1070
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
1071
+ # Pass serializer context so ``validate_lead`` can read ``request.user``:
1072
+ # on create the only member-to-be is the creator, so a lead supplied at
1073
+ # create must equal the creator (#2025).
1074
+ write = ProgramSerializer(data=request.data, context=self.get_serializer_context())
1075
+ write.is_valid(raise_exception=True)
1076
+
1077
+ # Service-layer call wraps the Program + OWNER membership in a single
1078
+ # transaction — see ADR-0070 §Durable Execution.
1079
+ from trueppm_api.apps.projects.services import KeyAssignmentError
1080
+
1081
+ try:
1082
+ program = create_program(
1083
+ name=write.validated_data["name"],
1084
+ description=write.validated_data.get("description", ""),
1085
+ methodology=write.validated_data.get("methodology", Methodology.HYBRID),
1086
+ created_by=request.user,
1087
+ lead=write.validated_data.get("lead"),
1088
+ # Blank or omitted derives a key from the name (ADR-1237 §1).
1089
+ code=write.validated_data.get("code", ""),
1090
+ )
1091
+ except KeyAssignmentError as exc:
1092
+ # A key taken between validation and insert (ADR-1237 §6): the same
1093
+ # field error validation would have given, never naming the holder.
1094
+ return Response({"code": [str(exc)]}, status=status.HTTP_400_BAD_REQUEST)
1095
+
1096
+ # Re-fetch through the get_queryset so the response includes my_role
1097
+ # and the count annotations.
1098
+ fresh = self.get_queryset().get(pk=program.pk)
1099
+ return Response(ProgramSerializer(fresh).data, status=status.HTTP_201_CREATED)
1100
+
1101
+ @extend_schema(
1102
+ summary="Dry-run: validate a JSON seed bundle without importing it",
1103
+ description=(
1104
+ "Runs the full seed validator — JSON-Schema conformance, referential "
1105
+ "integrity, node budgets, three-point estimate ordering — and returns "
1106
+ "every diagnostic it finds. **Persists nothing.**\n\n"
1107
+ 'A document that fails validation is `200 {"valid": false}`, not a '
1108
+ "`400`: the request succeeded, the *document* is what failed, and the "
1109
+ "caller needs the diagnostics either way. A `400` here means the "
1110
+ "request itself was unusable (upload over the size ceiling).\n\n"
1111
+ "Same authorization as `POST /programs/import/` — a dry run parses an "
1112
+ "untrusted document and is not a lighter-privilege surface."
1113
+ ),
1114
+ responses={200: SEED_VALIDATE_RESPONSE},
1115
+ )
1116
+ @action(
1117
+ detail=False,
1118
+ methods=["post"],
1119
+ url_path="import/validate",
1120
+ throttle_classes=[SeedValidateThrottle],
1121
+ )
1122
+ def validate_import(self, request: Request) -> Response:
1123
+ """Validate a seed document and report every problem, importing nothing.
1124
+
1125
+ The CSV importer has had a preview endpoint since #743; the JSON seed
1126
+ has had an equally good validator with no way to run it. That asymmetry
1127
+ matters because ``import_seed`` is wipe-then-recreate on the program
1128
+ slug (ADR-0109) — an operator pointing it at a live slug could not
1129
+ answer *"will this file be accepted?"* without committing to the
1130
+ destructive operation first (#2418).
1131
+
1132
+ Persisting nothing is the contract, and it is structural rather than
1133
+ merely intended: this calls ``inspect_seed``, a pure function in a
1134
+ module that never imports the ORM, and never reaches the importer.
1135
+
1136
+ Permission parity with ``import_seed`` is deliberate — both fall through
1137
+ to the ``get_permissions`` ``IsAuthenticated`` default. A dry run parses
1138
+ the same untrusted document under the same authorization; the only thing
1139
+ it withholds is the write.
1140
+ """
1141
+ from trueppm_api.apps.projects.seed import SeedReport, inspect_seed
1142
+ from trueppm_api.apps.projects.seed.replace import preview_replacement
1143
+
1144
+ payload, problem = _read_seed_payload(request)
1145
+ if problem is not None and not problem.is_document_level:
1146
+ return Response({"detail": problem.detail}, status=status.HTTP_400_BAD_REQUEST)
1147
+ if problem is not None:
1148
+ report = SeedReport(
1149
+ valid=False,
1150
+ errors=[f"$: {problem.detail}"],
1151
+ schema_version=None,
1152
+ program_slug=None,
1153
+ program_name=None,
1154
+ project_count=0,
1155
+ task_count=0,
1156
+ resource_count=0,
1157
+ )
1158
+ else:
1159
+ report = inspect_seed(payload)
1160
+
1161
+ # The destructive half of the answer (ADR-0726 §7). A dry run that says
1162
+ # "valid" while withholding "and it will move 3 projects to Trash" is
1163
+ # answering the less important question.
1164
+ body = asdict(report)
1165
+ body["replaces"] = preview_replacement(request.user, payload)
1166
+ return Response(body, status=status.HTTP_200_OK)
1167
+
1168
+ def _seed_replace_refusal(
1169
+ self,
1170
+ user: Any,
1171
+ slug: str,
1172
+ *,
1173
+ replace: bool,
1174
+ expected_program_id: Any,
1175
+ candidates: list[Any] | None = None,
1176
+ ) -> Response | None:
1177
+ """The three ``409`` refusals, or ``None`` when the import may proceed.
1178
+
1179
+ Shared between the unlocked pre-check (which decides the refusal before a
1180
+ payload is stored, so the ordinary confirm round-trip leaks nothing) and
1181
+ the locked re-check inside the transaction (which is authoritative and
1182
+ catches a collision created in between). Both must answer identically, so
1183
+ they call one function rather than two copies of the same three branches.
1184
+ """
1185
+ from trueppm_api.apps.projects.seed.replace import (
1186
+ describe_conflict,
1187
+ resolve_replace_candidates,
1188
+ )
1189
+
1190
+ if candidates is None:
1191
+ candidates = resolve_replace_candidates(user, slug)
1192
+ if not candidates:
1193
+ return None
1194
+
1195
+ if expected_program_id is not None:
1196
+ named = [p for p in candidates if str(p.pk) == str(expected_program_id)]
1197
+ if not named:
1198
+ return Response(
1199
+ {
1200
+ "detail": (
1201
+ "expected_program_id does not name the program that would "
1202
+ "be replaced — it may have changed since you checked."
1203
+ ),
1204
+ "code": "seed_replace_mismatch",
1205
+ "conflict": describe_conflict(candidates[0]).as_dict(),
1206
+ },
1207
+ status=status.HTTP_409_CONFLICT,
1208
+ )
1209
+ candidates = named
1210
+
1211
+ if not replace:
1212
+ return Response(
1213
+ {
1214
+ "detail": (
1215
+ f'A program you own already uses the code "{slug}". Re-importing '
1216
+ "moves its projects to Trash, where each can be restored "
1217
+ "individually as a standalone project; the program itself is not "
1218
+ "recoverable. Confirm to continue."
1219
+ ),
1220
+ "code": "seed_replace_required",
1221
+ "conflict": describe_conflict(candidates[0]).as_dict(),
1222
+ },
1223
+ status=status.HTTP_409_CONFLICT,
1224
+ )
1225
+
1226
+ if len(candidates) > 1:
1227
+ # ``Program.code`` is non-unique by design, so one caller can
1228
+ # legitimately own two programs sharing this slug. A single
1229
+ # ``conflict`` object can name only one of them, so a bare
1230
+ # ``replace=true`` would destroy a program the caller was never shown,
1231
+ # never counted, and that no audit field records — exactly what
1232
+ # ``expected_program_id`` exists to prevent.
1233
+ return Response(
1234
+ {
1235
+ "detail": (
1236
+ f"You own {len(candidates)} live programs using the code "
1237
+ f'"{slug}". Re-send with expected_program_id to name the one '
1238
+ "to replace."
1239
+ ),
1240
+ "code": "seed_replace_ambiguous",
1241
+ "conflicts": [describe_conflict(p).as_dict() for p in candidates],
1242
+ },
1243
+ status=status.HTTP_409_CONFLICT,
1244
+ )
1245
+
1246
+ return None
1247
+
1248
+ def _confirm_locked_replace(
1249
+ self,
1250
+ user: Any,
1251
+ slug: str,
1252
+ candidates: list[Any],
1253
+ *,
1254
+ replace: bool,
1255
+ expected_program_id: Any,
1256
+ ) -> tuple[list[Any], Response | None]:
1257
+ """Narrow locked replace candidates to the named program, or refuse with ``409``.
1258
+
1259
+ Runs inside the import transaction after ``resolve_replace_candidates`` has
1260
+ locked the rows. ``expected_program_id`` narrows the teardown to the one
1261
+ program the caller named; without this the set the caller consented to and
1262
+ the set actually destroyed could differ — see the ambiguity refusal below.
1263
+ The caller discards the stored payload when a refusal is returned.
1264
+ """
1265
+ from trueppm_api.apps.projects.seed.replace import describe_conflict
1266
+
1267
+ if expected_program_id is not None:
1268
+ named = [p for p in candidates if str(p.pk) == str(expected_program_id)]
1269
+ if not named:
1270
+ return candidates, Response(
1271
+ {
1272
+ "detail": (
1273
+ "expected_program_id does not name the program that "
1274
+ "would be replaced — it may have changed since you "
1275
+ "checked."
1276
+ ),
1277
+ "code": "seed_replace_mismatch",
1278
+ "conflict": describe_conflict(candidates[0]).as_dict(),
1279
+ },
1280
+ status=status.HTTP_409_CONFLICT,
1281
+ )
1282
+ candidates = named
1283
+
1284
+ if not replace or len(candidates) > 1:
1285
+ # A collision that only appeared between the unlocked pre-check and
1286
+ # this locked resolve. Rare (it needs a concurrent create), so the
1287
+ # orphaned payload is cleaned up by the caller rather than
1288
+ # restructured around.
1289
+ refusal = self._seed_replace_refusal(
1290
+ user,
1291
+ slug,
1292
+ replace=replace,
1293
+ expected_program_id=expected_program_id,
1294
+ candidates=candidates,
1295
+ ) or Response(
1296
+ {"detail": "The replace could not be confirmed. Try again."},
1297
+ status=status.HTTP_409_CONFLICT,
1298
+ )
1299
+ return candidates, refusal
1300
+
1301
+ return candidates, None
1302
+
1303
+ @extend_schema(
1304
+ summary="Queue a JSON seed bundle as a new program",
1305
+ request=SeedImportRequestSerializer,
1306
+ responses={
1307
+ 202: OpenApiResponse(
1308
+ response=SEED_IMPORT_QUEUED_RESPONSE,
1309
+ description=(
1310
+ "Import queued (ADR-0726). The program shell exists at "
1311
+ "`program_id` immediately; its projects and tasks are built in "
1312
+ "the background. Poll GET /programs/{program_id}/import/jobs/"
1313
+ "{import_request_id}/ until `status` is 'success' or 'failed'."
1314
+ ),
1315
+ ),
1316
+ 400: OpenApiResponse(
1317
+ description="Unreadable request, or a document that fails validation."
1318
+ ),
1319
+ 409: OpenApiResponse(
1320
+ response=SEED_REPLACE_CONFLICT_RESPONSE,
1321
+ description=(
1322
+ "A live program you own already holds this seed's slug. Re-send "
1323
+ "with `replace=true` to confirm; optionally pin the target with "
1324
+ "`expected_program_id`. The replaced program's projects move to "
1325
+ "Trash individually as standalone projects; the program shell "
1326
+ "itself is not recoverable. `code` is `seed_replace_required`, "
1327
+ "`seed_replace_mismatch`, or `seed_replace_ambiguous` — or "
1328
+ "`seed_slug_taken` when the slug is the key of a program you "
1329
+ "cannot replace (another user's, or one in Trash); keys are "
1330
+ "never reissued, so change `program.slug` and re-import."
1331
+ ),
1332
+ ),
1333
+ 429: OpenApiResponse(
1334
+ response=SEED_IMPORT_REFUSED_RESPONSE,
1335
+ description=(
1336
+ "Either the `seed_import` rate bucket is exhausted (no `code`; retry "
1337
+ "after the interval in `Retry-After`), or you already have "
1338
+ "`SEED_IMPORT_MAX_CONCURRENT_JOBS` imports queued or running "
1339
+ "(`code: seed_import_concurrency_limit`). The second is cleared by an "
1340
+ "outstanding import finishing, not by waiting out a window."
1341
+ ),
1342
+ ),
1343
+ },
1344
+ )
1345
+ @action(
1346
+ detail=False,
1347
+ methods=["post"],
1348
+ url_path="import",
1349
+ throttle_classes=[SeedImportThrottle],
1350
+ )
1351
+ def import_seed(self, request: Request) -> Response:
1352
+ """Queue a JSON seed import, returning ``202`` with the program and job ids.
1353
+
1354
+ Accepts either a ``file`` multipart upload or a raw JSON body. The caller
1355
+ becomes the program OWNER (same authorization as ``create`` — any
1356
+ authenticated user may create a program). ``create_users`` is forced off:
1357
+ importing a seed on a live instance must never mint arbitrary logins.
1358
+
1359
+ **The split (ADR-0726 §4).** Validation, the replace decision, the
1360
+ replacement itself, and the program shell all happen *here*, inside the
1361
+ request; only the O(n) subtree build is queued. Two reasons, both
1362
+ deliberate: a destructive act belongs in the request the operator
1363
+ authorized rather than behind a queue, and resolving the collision here
1364
+ closes the TOCTOU window between "nothing collides" and a worker deleting
1365
+ something. What is left to the worker is purely additive, which is why a
1366
+ 100k-entity document no longer 504s mid-transaction (#2574).
1367
+
1368
+ **Replacement requires consent (#2581).** A live program of the caller's
1369
+ whose ``code`` matches this seed's slug is refused with ``409`` unless
1370
+ ``replace=true`` is sent. Confirmed, its projects are **soft**-deleted —
1371
+ they land in project Trash individually, as standalone projects, and
1372
+ offline clients receive tombstones. The program shell itself is not
1373
+ recoverable; there is no program Trash (#2587).
1374
+
1375
+ Rate-limited to the ``seed_import`` scope (:class:`SeedImportThrottle`).
1376
+ The bucket now bounds *job creation* rather than request CPU, which is
1377
+ the correct unit once the build is async — paired with the per-program
1378
+ in-flight de-dupe in ``enqueue_program_import``, that is what keeps this
1379
+ from trading a CPU exhaustion vector for a queue backlog.
1380
+
1381
+ Permission parity (#1957): import stays ``IsAuthenticated`` (via the
1382
+ get_permissions default) deliberately, because program ``create`` is
1383
+ likewise ``IsAuthenticated``. The *replace* is separately scoped to
1384
+ programs the caller owns outright (#994), so the looser gate on create
1385
+ never widens what a seed can destroy.
1386
+ """
1387
+ import json as _json
1388
+
1389
+ from trueppm_api.apps.access.services import create_program
1390
+ from trueppm_api.apps.projects.models import ObjectKeySource
1391
+ from trueppm_api.apps.projects.seed import SeedValidationError, validate_seed
1392
+ from trueppm_api.apps.projects.seed.replace import (
1393
+ resolve_replace_candidates,
1394
+ )
1395
+ from trueppm_api.apps.projects.services import (
1396
+ KeyAssignmentError,
1397
+ adopt_released_keys,
1398
+ assign_key,
1399
+ enqueue_program_import,
1400
+ is_key_taken,
1401
+ release_keys_for_replace,
1402
+ soft_delete_program_subtree,
1403
+ store_seed_payload,
1404
+ )
1405
+
1406
+ # Before parsing: an over-cap caller is refused without spending the
1407
+ # validation pass on a document that was never going to be queued.
1408
+ over_cap = _seed_concurrency_refusal(request.user)
1409
+ if over_cap is not None:
1410
+ return over_cap
1411
+
1412
+ payload, problem = _read_seed_payload(request)
1413
+ if problem is not None:
1414
+ return Response({"detail": problem.detail}, status=status.HTTP_400_BAD_REQUEST)
1415
+
1416
+ options = SeedImportRequestSerializer(data=request.data)
1417
+ options.is_valid(raise_exception=True)
1418
+ replace = bool(options.validated_data.get("replace"))
1419
+ expected_program_id = options.validated_data.get("expected_program_id")
1420
+
1421
+ try:
1422
+ validate_seed(payload)
1423
+ except SeedValidationError as exc:
1424
+ # Standardized on the `detail` envelope (#1325). For the line-level
1425
+ # import report `detail` is the *list* of validation messages (the FE
1426
+ # renders them as discrete items); the single-message errors above use
1427
+ # a plain string. seedImportErrors() normalizes both to a string list.
1428
+ return Response({"detail": exc.errors}, status=status.HTTP_400_BAD_REQUEST)
1429
+
1430
+ seed_program = payload["program"]
1431
+ slug = seed_program["slug"]
1432
+
1433
+ # Decide the refusals BEFORE storing anything. The 409 is the *designed*
1434
+ # default path for a re-import — POST, confirm, POST — so storing the
1435
+ # payload first would leak one full copy of every ordinary re-import into
1436
+ # object storage, referenced by no job row and therefore invisible to the
1437
+ # row-driven retention purge forever.
1438
+ #
1439
+ # This first pass is deliberately unlocked: it only decides whether to
1440
+ # answer 409. The authoritative resolve happens under
1441
+ # ``select_for_update`` inside the transaction below, and re-runs the same
1442
+ # guards, so a collision that appears in between is still caught.
1443
+ refusal = self._seed_replace_refusal(
1444
+ request.user, slug, replace=replace, expected_program_id=expected_program_id
1445
+ )
1446
+ if refusal is not None:
1447
+ return refusal
1448
+ # A slug held by a program this caller cannot replace — someone else's, or
1449
+ # one of their own that is already in Trash — can never become this
1450
+ # program's key (ADR-1237: keys are unique and never reissued). Refused
1451
+ # here, before anything is stored, rather than as an IntegrityError 500
1452
+ # at the shell insert. The body names the key the caller sent, never the
1453
+ # holder (ADR-1237 §6).
1454
+ if not resolve_replace_candidates(request.user, slug) and is_key_taken("program", slug):
1455
+ return _seed_slug_taken_response(slug)
1456
+
1457
+ # Past the refusals: persist the payload OUTSIDE the transaction. On an
1458
+ # S3-backed deployment this is a multi-megabyte network PUT, and the block
1459
+ # below holds SELECT FOR UPDATE on the replaced program and every one of
1460
+ # its projects until commit.
1461
+ upload = request.FILES.get("file")
1462
+ payload_path = store_seed_payload(_json.dumps(payload).encode("utf-8"))
1463
+
1464
+ with transaction.atomic():
1465
+ # Re-check the concurrency cap here and nowhere later: the pre-parse
1466
+ # check ran before validation, so a concurrent request may have taken
1467
+ # the last slot meanwhile. It must precede ``resolve_replace_candidates``
1468
+ # because everything below it is destructive — returning a refusal
1469
+ # after ``soft_delete_program_subtree`` would COMMIT the teardown and
1470
+ # answer 429, losing the caller's program to a rate limit.
1471
+ over_cap = _seed_concurrency_refusal(request.user)
1472
+ if over_cap is not None:
1473
+ _discard_seed_payload(payload_path)
1474
+ return over_cap
1475
+
1476
+ candidates = resolve_replace_candidates(request.user, slug, lock=True)
1477
+ replaced_program_id = None
1478
+ if candidates:
1479
+ candidates, refusal = self._confirm_locked_replace(
1480
+ request.user,
1481
+ slug,
1482
+ candidates,
1483
+ replace=replace,
1484
+ expected_program_id=expected_program_id,
1485
+ )
1486
+ if refusal is not None:
1487
+ _discard_seed_payload(payload_path)
1488
+ return refusal
1489
+
1490
+ replaced_program_id = candidates[0].pk
1491
+ # The replaced shell is unrecoverable, so its keys move to the new
1492
+ # one: same slug, and links to the old program keep resolving.
1493
+ released_keys = release_keys_for_replace(candidates[0])
1494
+ # The trashed projects keep their keys for now; the worker moves
1495
+ # them to the rebuilt projects inside its build transaction, so a
1496
+ # failed build leaves no original keyless (#4150).
1497
+ replaced_project_ids = soft_delete_program_subtree(
1498
+ candidates[0], actor=request.user, reason="seed_replace"
1499
+ )
1500
+ else:
1501
+ released_keys = []
1502
+ replaced_project_ids = []
1503
+
1504
+ program = create_program(
1505
+ name=seed_program["name"],
1506
+ description=seed_program.get("description", ""),
1507
+ methodology=seed_program["methodology"],
1508
+ created_by=request.user,
1509
+ code=None,
1510
+ )
1511
+ if not adopt_released_keys(program, released_keys):
1512
+ try:
1513
+ assign_key(program, slug, source=ObjectKeySource.USER, actor=request.user)
1514
+ except KeyAssignmentError:
1515
+ # Taken between the unlocked check above and here.
1516
+ transaction.set_rollback(True)
1517
+ _discard_seed_payload(payload_path)
1518
+ return _seed_slug_taken_response(slug)
1519
+
1520
+ job = enqueue_program_import(
1521
+ program=program,
1522
+ requested_by=request.user,
1523
+ payload_path=payload_path,
1524
+ filename=getattr(upload, "name", "") or "",
1525
+ replace=replace,
1526
+ replaced_program_id=replaced_program_id,
1527
+ replaced_project_ids=replaced_project_ids,
1528
+ )
1529
+
1530
+ program_id = str(program.pk)
1531
+ return Response(
1532
+ {
1533
+ "queued": True,
1534
+ "program_id": program_id,
1535
+ "import_request_id": str(job.pk),
1536
+ "replaced_program_id": (str(replaced_program_id) if replaced_program_id else None),
1537
+ },
1538
+ status=status.HTTP_202_ACCEPTED,
1539
+ )
1540
+
1541
+ @extend_schema(
1542
+ summary="Poll one async program seed import job's status",
1543
+ responses={200: ProgramImportJobSerializer},
1544
+ )
1545
+ @action(
1546
+ detail=True,
1547
+ methods=["get"],
1548
+ url_path=r"import/jobs/(?P<job_id>[0-9a-f-]{36})",
1549
+ )
1550
+ def import_job_detail(
1551
+ self, request: Request, pk: str | None = None, job_id: str | None = None
1552
+ ) -> Response:
1553
+ """Poll an async seed import job (ADR-0726, #2574).
1554
+
1555
+ The mirror of ``export_job_detail``, and scoped the same way: the job is
1556
+ looked up against the resolved (membership-checked) program, so a
1557
+ ``job_id`` belonging to another program 404s rather than leaking
1558
+ (object-level IDOR guard).
1559
+ """
1560
+ program = self.get_object()
1561
+ # The URL regex admits 36-char strings that are not UUIDs (36 dashes,
1562
+ # say). Passing one to a UUID pk filter raises Django's ValidationError,
1563
+ # which DRF does not map — a 500 where the caller should simply get a 404.
1564
+ try:
1565
+ parsed_job_id = uuid.UUID(str(job_id))
1566
+ except (TypeError, ValueError) as exc:
1567
+ raise Http404("Import job not found") from exc
1568
+ job = ProgramImportJob.objects.filter(program=program, pk=parsed_job_id).first()
1569
+ if job is None:
1570
+ raise Http404("Import job not found")
1571
+ return Response(ProgramImportJobSerializer(job).data, status=status.HTTP_200_OK)
1572
+
1573
+ @extend_schema(
1574
+ summary="Pin or unpin this program for the requesting user",
1575
+ description=PIN_ENDPOINT_DESCRIPTION,
1576
+ request=None,
1577
+ responses={
1578
+ 200: PROGRAM_PIN_RESPONSE,
1579
+ 204: None,
1580
+ 400: OpenApiResponse(
1581
+ response=PIN_LIMIT_RESPONSE,
1582
+ description="Pin limit reached (`code: pin_limit_reached`).",
1583
+ ),
1584
+ },
1585
+ )
1586
+ @action(detail=True, methods=["post", "delete"], url_path="pin")
1587
+ def pin(self, request: Request, pk: str | None = None) -> Response:
1588
+ """Pin (POST) or unpin (DELETE) this program for the current user (#2390).
1589
+
1590
+ Any member who can read the program may pin it — a pin grants nothing
1591
+ and reveals nothing. Scoped to ``request.user``; see ADR-0627 §D5.
1592
+ """
1593
+ from trueppm_api.apps.profiles.services import PinLimitReached, set_pin
1594
+
1595
+ program = self.get_object()
1596
+ if request.method == "DELETE":
1597
+ set_pin(request.user, program=program, pinned=False)
1598
+ return Response(status=status.HTTP_204_NO_CONTENT)
1599
+ try:
1600
+ set_pin(request.user, program=program, pinned=True)
1601
+ except PinLimitReached as exc:
1602
+ return Response(
1603
+ {"detail": pin_limit_detail(exc.limit), "code": "pin_limit_reached"},
1604
+ status=status.HTTP_400_BAD_REQUEST,
1605
+ )
1606
+ return Response({"is_pinned": True}, status=status.HTTP_200_OK)
1607
+
1608
+ @extend_schema(
1609
+ methods=["GET"],
1610
+ summary="Export the program as a downloadable JSON seed file",
1611
+ responses={
1612
+ 200: OpenApiResponse(
1613
+ # The GET path serves the canonical seed as an application/json
1614
+ # object (attachment), so declare OBJECT — matching the sibling
1615
+ # project export. BINARY declared a string/binary body that the
1616
+ # real JSON response violates under response_schema_conformance
1617
+ # (#2213).
1618
+ response=OpenApiTypes.OBJECT,
1619
+ description=(
1620
+ "A downloadable canonical JSON seed document describing this program "
1621
+ "and the member projects the caller holds project membership on "
1622
+ "(member projects the caller cannot read are omitted entirely; "
1623
+ "program-level blocks are always included). Delivered as a file "
1624
+ "attachment. Round-trips "
1625
+ "back through the importer. `resources[].email` and `accounts[].email` "
1626
+ "are withheld (key omitted) unless the caller holds workspace Admin+ — "
1627
+ "the endpoint itself stays reachable at program Admin+, which is "
1628
+ "self-grantable by creating a project/program, so the field is gated "
1629
+ "independently of endpoint access (#3627)."
1630
+ ),
1631
+ ),
1632
+ 403: OpenApiResponse(
1633
+ description=(
1634
+ "Not a program Admin — or an agent (`mcp:read`) token where a member "
1635
+ "project has opted out of agent reads and "
1636
+ "`TRUEPPM_MCP_PROGRAM_EXPORT_POLICY` is `withhold` (#3014). The body "
1637
+ "carries the ADR-0809 refusal envelope naming `capability_scope`."
1638
+ )
1639
+ ),
1640
+ },
1641
+ )
1642
+ @extend_schema(
1643
+ methods=["POST"],
1644
+ summary="Queue a richer asynchronous program export bundle",
1645
+ request=None,
1646
+ responses={
1647
+ 202: OpenApiResponse(
1648
+ response=ProgramExportJobSerializer,
1649
+ description=(
1650
+ "An async program export job (ADR-0219, #1958). The job builds a "
1651
+ ".tar.gz containing the canonical JSON seed plus, per member project "
1652
+ "the requester holds project membership on, MS Project XML, task "
1653
+ "attachments, time entries, and the audit/change history. Membership "
1654
+ "is evaluated when the bundle is built. Poll GET .../export/jobs/{job_id}/ "
1655
+ "until status is 'success', "
1656
+ "then fetch download_url. Admin+ only; an in-flight job is returned "
1657
+ "rather than queuing a duplicate build."
1658
+ ),
1659
+ ),
1660
+ },
1661
+ )
1662
+ @action(detail=True, methods=["get", "post"], url_path="export")
1663
+ def export(self, request: Request, pk: str | None = None) -> HttpResponse:
1664
+ """GET: synchronous JSON seed (#616). POST: queue the async bundle (#1958).
1665
+
1666
+ Both paths are Admin+ (#1957, see get_permissions). The GET path returns the
1667
+ canonical JSON seed as a synchronous attachment; the POST path (ADR-0219)
1668
+ enqueues the richer async ``.tar.gz`` bundle across every member project the
1669
+ requester holds project membership on (#4310) and returns ``202`` with the job row.
1670
+ """
1671
+ program = self.get_object()
1672
+
1673
+ if request.method == "POST":
1674
+ from trueppm_api.apps.projects.services import enqueue_program_export
1675
+
1676
+ job = enqueue_program_export(program=program, requested_by=request.user)
1677
+ return Response(
1678
+ ProgramExportJobSerializer(job, context={"request": request}).data,
1679
+ status=status.HTTP_202_ACCEPTED,
1680
+ )
1681
+
1682
+ from trueppm_api.apps.projects.seed.exporter import dump_seed, export_program
1683
+
1684
+ body = dump_seed(export_program(program, requesting_user=request.user))
1685
+ filename = f"{program.code or program.pk}.json"
1686
+ response = HttpResponse(body, content_type="application/json")
1687
+ response["Content-Disposition"] = f'attachment; filename="{filename}"'
1688
+ return response
1689
+
1690
+ @extend_schema(
1691
+ summary="List this program's async export jobs",
1692
+ responses={200: ProgramExportJobSerializer(many=True)},
1693
+ # #3420: the viewset's SearchFilter/OrderingFilter make drf-spectacular publish
1694
+ # `search` and `ordering` on every list-shaped operation, this one included —
1695
+ # and this action never runs them. Undeclare rather than honor: the backends are
1696
+ # configured with `search_fields = ["name", "code"]` and
1697
+ # `ordering_fields = ["name"]`, and ProgramExportJob has no `name` and no `code`
1698
+ # column, so wiring `filter_queryset()` in here would turn `?search=x` from a
1699
+ # silently-ignored parameter into a FieldError 500.
1700
+ #
1701
+ # `exclude=True` is the only form that removes an auto-generated parameter —
1702
+ # `parameters=[]` reads as "no overrides" and drf-spectacular emits the filter
1703
+ # backends' parameters anyway, which is the silent no-op this is fixing.
1704
+ parameters=_UNDECLARE_FILTER_PARAMS,
1705
+ )
1706
+ @action(detail=True, methods=["get"], url_path="export/jobs")
1707
+ def export_jobs(self, request: Request, pk: str | None = None) -> Response:
1708
+ """List recent async export jobs for this program (#1958, ADR-0219). Admin+.
1709
+
1710
+ Page-number envelope so an integrator can tell a truncated list from a
1711
+ complete one. Scoped to the resolved (membership-checked) program, so no
1712
+ cross-program rows leak.
1713
+ """
1714
+ program = self.get_object()
1715
+ jobs = ProgramExportJob.objects.filter(program=program)
1716
+ paginator = pagination.PageNumberPagination()
1717
+ page = paginator.paginate_queryset(jobs, request, view=self)
1718
+ data = ProgramExportJobSerializer(
1719
+ page if page is not None else jobs, many=True, context={"request": request}
1720
+ ).data
1721
+ return paginator.get_paginated_response(data)
1722
+
1723
+ @extend_schema(
1724
+ summary="Poll one async program export job's status",
1725
+ responses={200: ProgramExportJobSerializer},
1726
+ )
1727
+ @action(
1728
+ detail=True,
1729
+ methods=["get"],
1730
+ url_path=r"export/jobs/(?P<job_id>[0-9a-f-]{36})",
1731
+ )
1732
+ def export_job_detail(
1733
+ self, request: Request, pk: str | None = None, job_id: str | None = None
1734
+ ) -> Response:
1735
+ """Poll an async program export job (#1958, ADR-0219). Admin+.
1736
+
1737
+ The job is looked up scoped to the resolved program, so a ``job_id``
1738
+ belonging to another program 404s rather than leaking (object-level IDOR
1739
+ guard).
1740
+ """
1741
+ program = self.get_object()
1742
+ job = get_object_or_404(ProgramExportJob, pk=job_id, program=program)
1743
+ return Response(ProgramExportJobSerializer(job, context={"request": request}).data)
1744
+
1745
+ @extend_schema(
1746
+ summary="Download a completed async program export bundle",
1747
+ responses={
1748
+ (200, "application/gzip"): OpenApiResponse(
1749
+ response=OpenApiTypes.BINARY,
1750
+ description="The program export .tar.gz as a file attachment.",
1751
+ ),
1752
+ 409: OpenApiResponse(
1753
+ response=OpenApiTypes.OBJECT, description="Export is not ready yet."
1754
+ ),
1755
+ 410: OpenApiResponse(
1756
+ response=OpenApiTypes.OBJECT, description="Download link has expired."
1757
+ ),
1758
+ 403: OpenApiResponse(
1759
+ description=(
1760
+ "Not a program Admin — or an agent (`mcp:read`) token where a member "
1761
+ "project has opted out of agent reads and "
1762
+ "`TRUEPPM_MCP_PROGRAM_EXPORT_POLICY` is `withhold` (#3014). The body "
1763
+ "carries the ADR-0809 refusal envelope naming `capability_scope`."
1764
+ )
1765
+ ),
1766
+ 404: OpenApiResponse(
1767
+ response=OpenApiTypes.OBJECT,
1768
+ description=(
1769
+ "No job with this id in this program, OR the job belongs to a different "
1770
+ "admin's export request (#4310). A bundle can be downloaded only by the "
1771
+ "admin who requested it — another Program Admin's request for the same "
1772
+ "job id gets the same 404 an unrelated program would, not a 403, so the "
1773
+ "two cases are indistinguishable from outside."
1774
+ ),
1775
+ ),
1776
+ },
1777
+ )
1778
+ @action(
1779
+ detail=True,
1780
+ methods=["get"],
1781
+ url_path=r"export/jobs/(?P<job_id>[0-9a-f-]{36})/download",
1782
+ )
1783
+ def export_job_download(
1784
+ self, request: Request, pk: str | None = None, job_id: str | None = None
1785
+ ) -> Any:
1786
+ """Stream a completed program export bundle (#1958, ADR-0219). Admin+.
1787
+
1788
+ Authenticated — the archive contains the whole program including its audit
1789
+ history, so it is never served from a raw, unauthenticated storage URL.
1790
+ ``409`` if not ready, ``410 Gone`` once the link has expired. The job is
1791
+ program-scoped so a ``job_id`` from another program 404s (IDOR guard). It is
1792
+ also requester-scoped (#4310): a ``job_id`` belonging to another admin's export
1793
+ request 404s the same way, not 403 — the lookup filters on ``requested_by``
1794
+ alongside ``program``, so the two refusals are indistinguishable from outside.
1795
+
1796
+ **ADR-0678 agent opt-out — settled in #3014.** The mixin's ``Program`` branch
1797
+ governs this route on ``program.mcp_enabled`` alone, so a child project's
1798
+ "off" did not withhold the bundle: an ``mcp:read`` token at Admin+ could
1799
+ download an archive carrying the tasks of a team that had switched agent
1800
+ reads off. ``McpProgramExportConsent`` now decides that, per the operator's
1801
+ ``TRUEPPM_MCP_PROGRAM_EXPORT_POLICY`` — ``withhold`` (default) refuses the
1802
+ download to an agent when any member project has opted out; ``allow`` keeps
1803
+ the previous program-level-artifact behavior. Humans are unaffected either
1804
+ way. The lever is serve-or-refuse rather than filter because the archive is
1805
+ built asynchronously and streamed as opaque bytes, so at download time there
1806
+ is nothing left to narrow.
1807
+ """
1808
+ program = self.get_object()
1809
+ # #4310 (B1): the archive holds member-project content, so it is served only to
1810
+ # the admin who requested it. Metadata (detail/list) stays program-scoped.
1811
+ job = get_object_or_404(
1812
+ ProgramExportJob, pk=job_id, program=program, requested_by=request.user
1813
+ )
1814
+ return stream_export_job_or_error(
1815
+ job,
1816
+ success_status=ExportJobStatus.SUCCESS,
1817
+ filename=f"program-{program.code or program.pk}.tar.gz",
1818
+ )
1819
+
1820
+ @extend_schema(
1821
+ summary="Within-program resource contention (cross-project allocation)",
1822
+ parameters=[
1823
+ OpenApiParameter(
1824
+ name="start",
1825
+ type=OpenApiTypes.DATE,
1826
+ location=OpenApiParameter.QUERY,
1827
+ required=False,
1828
+ description=(
1829
+ "Window start (ISO 8601 `YYYY-MM-DD`). Defaults to the earliest task "
1830
+ "SPAN start (`scheduled_start`, ADR-0752, falling back to "
1831
+ "`early_start`) across all member projects."
1832
+ ),
1833
+ ),
1834
+ OpenApiParameter(
1835
+ name="end",
1836
+ type=OpenApiTypes.DATE,
1837
+ location=OpenApiParameter.QUERY,
1838
+ required=False,
1839
+ description=(
1840
+ "Window end (ISO 8601 `YYYY-MM-DD`). Defaults to the latest "
1841
+ "`early_finish` across all member projects."
1842
+ ),
1843
+ ),
1844
+ OpenApiParameter(
1845
+ name="resource",
1846
+ type=OpenApiTypes.UUID,
1847
+ location=OpenApiParameter.QUERY,
1848
+ required=False,
1849
+ many=True,
1850
+ description="Repeatable. Filter to specific resource IDs.",
1851
+ ),
1852
+ OpenApiParameter(
1853
+ name="status",
1854
+ type=OpenApiTypes.STR,
1855
+ location=OpenApiParameter.QUERY,
1856
+ required=False,
1857
+ many=True,
1858
+ description="Repeatable. Filter tasks by status value.",
1859
+ ),
1860
+ ],
1861
+ responses={
1862
+ 200: ProgramResourceContentionSerializer,
1863
+ 400: OpenApiResponse(
1864
+ description="Malformed `start`/`end` date, or `start` is after `end`."
1865
+ ),
1866
+ 409: OpenApiResponse(description="No member project has a computed schedule yet."),
1867
+ },
1868
+ )
1869
+ @action(detail=True, methods=["get"], url_path="resource-contention")
1870
+ def resource_contention(self, request: Request, pk: str | None = None) -> Response:
1871
+ """Cross-project resource allocation for the within-program contention view (#1149).
1872
+
1873
+ The program-scoped counterpart to ``ProjectViewSet.resource_allocation`` (#85):
1874
+ returns each resource with their task spans across the member projects of this
1875
+ program **the caller holds live ProjectMembership on** (#4310), each span tagged
1876
+ with its source project, so the client can show who is over-allocated across
1877
+ sibling projects in overlapping windows (the contention the GA-launch sample
1878
+ program deliberately creates). A member project the caller cannot read
1879
+ contributes no spans, the same scoping ``task_search`` applies.
1880
+
1881
+ This is OSS, within-program **visibility** only — it surfaces contention data but
1882
+ does not level resources or cross a program boundary. Cross-program leveling and the
1883
+ portfolio heat map remain Enterprise. Overallocation detection is intentionally
1884
+ client-side (ADR-0031): the caller receives the merged spans and sums daily units
1885
+ against each resource's ``max_units``.
1886
+
1887
+ Bounded by ``_ALLOCATION_ASSIGNMENT_LIMIT`` assignment rows, cut on a resource
1888
+ boundary and disclosed as ``truncated`` / ``resource_count`` (ADR-1118) — the
1889
+ same contract as the per-project endpoint, and for the same reason: a resource
1890
+ returned with only part of its spans would report a *wrong* load, not an
1891
+ incomplete one, because ADR-0031's verdict is summed over the whole set.
1892
+
1893
+ ``max_units`` here is deliberately the resource's **own** default and NOT a
1894
+ per-project ``units_override`` (#3574). This span is cross-project by
1895
+ construction, so there is no single project whose override applies; and the
1896
+ overrides are slices of one person's time rather than additive capacities, so
1897
+ summing them would not produce a total ceiling either. The per-project reads
1898
+ (``ProjectViewSet.resource_allocation``, the utilization engine, the heat map,
1899
+ the Overview card) all apply the override; this one states the whole person.
1900
+
1901
+ Windowed and rendered on the task's SPAN (``scheduled_start``..``early_finish``,
1902
+ ADR-0752), not on ``early_start``..``early_finish`` (#2677) — the same defect
1903
+ fixed for ``ProjectViewSet.resource_allocation`` and for the utilization heat map
1904
+ (#2623): since ADR-0132, ``early_start`` is the *remaining-work* window for an
1905
+ in-progress task and narrows toward ``early_finish`` as ``percent_complete``
1906
+ rises, which would otherwise misreport cross-project contention as work is
1907
+ reported. ``scheduled_start`` falls back to ``early_start`` via ``Coalesce`` for
1908
+ rows a CPM run has not yet populated it on.
1909
+
1910
+ Query parameters mirror the per-project endpoint:
1911
+ start (YYYY-MM-DD, optional) — window start; defaults to the earliest
1912
+ task span start across all member projects. Returns 409 if no
1913
+ member project has CPM dates yet.
1914
+ end (YYYY-MM-DD, optional) — window end; defaults to the latest early_finish.
1915
+ resource (UUID, optional, repeatable) — filter to specific resource IDs.
1916
+ status (string, optional, repeatable) — filter tasks by status value.
1917
+ """
1918
+ from django.db.models import DateField
1919
+ from django.db.models.functions import Coalesce
1920
+
1921
+ from trueppm_api.apps.projects.mcp_settings import mcp_excluded_project_ids
1922
+ from trueppm_api.apps.resources.models import TaskResource
1923
+
1924
+ program = self.get_object()
1925
+
1926
+ # Member projects (non-deleted) — the contention scope. With no live
1927
+ # projects (or none scheduled) and no explicit window, the window cannot
1928
+ # be resolved and the endpoint returns 409 like the per-project one.
1929
+ # ADR-0678 T1 (#2482): the contention scope aggregates CHILD PROJECT task
1930
+ # spans, each tagged with its source project, so an opted-out project would
1931
+ # otherwise surface its schedule through its parent program.
1932
+ # Drafts are excluded (#2962/#3128): contention is a health figure about
1933
+ # PEOPLE. A speculative allocation on a plan nobody has committed to would
1934
+ # show a real person as contended in a real week, and the Resource Manager
1935
+ # acting on it would be levelling against work that may never exist.
1936
+ member_qs = visible_projects(program.projects.filter(is_deleted=False))
1937
+ _excluded = mcp_excluded_project_ids(request)
1938
+ if _excluded is not None:
1939
+ member_qs = member_qs.exclude(pk__in=_excluded)
1940
+ member_project_ids = list(member_qs.values_list("id", flat=True))
1941
+ # #4310 (round 2, B1): IsProgramScheduler is a PROGRAM gate. Project read is
1942
+ # ProjectMembership-gated regardless of program role, the same predicate
1943
+ # task_search applies — without this, a Program Admin/Scheduler with no
1944
+ # membership on a member project read its task names, dates and status here.
1945
+ from trueppm_api.apps.access.permissions import live_member_project_ids
1946
+
1947
+ _readable = live_member_project_ids(request.user, member_project_ids)
1948
+ member_project_ids = [pid for pid in member_project_ids if pid in _readable]
1949
+
1950
+ # --- Resolve window bounds across all member projects ---
1951
+ base_tasks = Task.objects.filter(project_id__in=member_project_ids, is_deleted=False)
1952
+
1953
+ try:
1954
+ window_start, window_end = _resolve_allocation_window(request, base_tasks)
1955
+ except _ScheduleNotComputedError:
1956
+ return Response(
1957
+ {"detail": _SCHEDULE_NOT_COMPUTED},
1958
+ status=status.HTTP_409_CONFLICT,
1959
+ )
1960
+ except ValueError as exc:
1961
+ # False positive: the only ValueError raised here is the curated
1962
+ # _parse_window_date message ("'start'/'end' must be ISO 8601 …").
1963
+ return Response(
1964
+ {"detail": str(exc)}, # codeql[py/stack-trace-exposure]
1965
+ status=status.HTTP_400_BAD_REQUEST,
1966
+ )
1967
+
1968
+ if window_start > window_end:
1969
+ return Response(
1970
+ {"detail": "'start' must not be after 'end'."},
1971
+ status=status.HTTP_400_BAD_REQUEST,
1972
+ )
1973
+
1974
+ # --- Optional filters ---
1975
+ resource_ids = request.query_params.getlist("resource")
1976
+ status_filters = request.query_params.getlist("status")
1977
+
1978
+ # --- Single query: all assignments across member projects in the window ---
1979
+ # Tasks with null CPM dates are retained (unscheduled); the client renders
1980
+ # them outside the contention math, mirroring the per-project endpoint.
1981
+ # _span_start (ADR-0752 / #2677): the task's SPAN start, not the
1982
+ # remaining-work window early_start narrows to as percent_complete
1983
+ # rises. Mirrors the per-project resource_allocation annotation.
1984
+ # ``.active()`` (#3572): mirrors the per-project resource_allocation endpoint.
1985
+ # Contention is a statement about who is over-committed across sibling
1986
+ # projects; a deactivated person is not competing for anything.
1987
+ qs = (
1988
+ TaskResource.objects.active()
1989
+ .filter(
1990
+ task__project_id__in=member_project_ids,
1991
+ task__is_deleted=False,
1992
+ )
1993
+ .select_related("resource", "task", "task__project")
1994
+ .annotate(
1995
+ _span_start=Coalesce(
1996
+ "task__scheduled_start", "task__early_start", output_field=DateField()
1997
+ )
1998
+ )
1999
+ # Ordered by resource_id rather than resource__name (ADR-1118 /
2000
+ # #3576) — see the per-project endpoint for the full rationale. The
2001
+ # by-name resource ordering and the by-project-name task ordering the
2002
+ # response promises are both restored in Python after grouping;
2003
+ # task__project__name in particular was a *third* table in the sort
2004
+ # key, on top of the join-away resource name.
2005
+ .order_by("resource_id", "task__project_id", "task__early_start")
2006
+ )
2007
+
2008
+ if resource_ids:
2009
+ qs = qs.filter(resource__id__in=resource_ids)
2010
+
2011
+ if status_filters:
2012
+ qs = qs.filter(task__status__in=status_filters)
2013
+
2014
+ qs = qs.exclude(
2015
+ task__early_finish__isnull=False,
2016
+ task__early_start__isnull=False,
2017
+ task__early_finish__lt=window_start,
2018
+ ).exclude(
2019
+ task__early_finish__isnull=False,
2020
+ task__early_start__isnull=False,
2021
+ _span_start__gt=window_end,
2022
+ )
2023
+
2024
+ # --- Build response grouped by resource, each span tagged with its project ---
2025
+ rows, truncated, resource_count_for = _cap_assignments_at_resource_boundary(
2026
+ qs, _ALLOCATION_ASSIGNMENT_LIMIT
2027
+ )
2028
+ resources_out = _group_contention_assignments(rows)
2029
+ return Response(
2030
+ {
2031
+ "program_id": str(program.id),
2032
+ "window_start": window_start.isoformat(),
2033
+ "window_end": window_end.isoformat(),
2034
+ "resources": resources_out,
2035
+ "resource_count": resource_count_for(len(resources_out)),
2036
+ "truncated": truncated,
2037
+ }
2038
+ )
2039
+
2040
+ @extend_schema(
2041
+ summary="List bundled demo samples available to the loader",
2042
+ responses={200: SampleCatalogEntrySerializer(many=True)},
2043
+ # #3420: same undeclaration as `export_jobs`, for a harder reason — this action
2044
+ # returns a hand-built list of dicts over fixtures baked into the image, not a
2045
+ # queryset, so `filter_queryset()` cannot be applied to it at all.
2046
+ parameters=_UNDECLARE_FILTER_PARAMS,
2047
+ )
2048
+ # The catalog is a fixed-size list of the fixtures baked into the image — it is
2049
+ # returned as a bare array and is never paginated. ProgramViewSet does set a
2050
+ # pagination_class, so without this opt-out the auto-schema declares a
2051
+ # PaginatedSampleCatalogEntryList envelope no response can satisfy (#2515,
2052
+ # cf. the `projects` action below and #2213).
2053
+ @suppress_list_pagination
2054
+ @action(detail=False, methods=["get"], url_path="samples")
2055
+ def samples(self, request: Request) -> Response:
2056
+ """List the bundled samples, with the provenance to audit them (#375, #2490).
2057
+
2058
+ Beyond the loader's title/description, each entry carries what someone
2059
+ deciding whether to trust the fixture actually needs: its size, a SHA-256
2060
+ of the exact bytes this instance will serve, the schema version, and the
2061
+ entity counts. The counts answer the question the demo loader otherwise
2062
+ forces on faith — *how much is this about to write into my database?*
2063
+
2064
+ Counts, digest and size all come from one read of one file
2065
+ (``sample_metadata``), so a client that verifies the digest has verified
2066
+ the same bytes the counts describe.
2067
+
2068
+ A fixture that is present but unparseable reports ``null`` counts and
2069
+ stays downloadable: failing to summarize a file is no reason to withhold
2070
+ it from someone who wants to read it themselves.
2071
+ """
2072
+ from trueppm_api.apps.projects.seed.samples import SAMPLES, sample_metadata
2073
+
2074
+ entries = []
2075
+ for sample in SAMPLES.values():
2076
+ meta = sample_metadata(sample)
2077
+ entries.append(
2078
+ {
2079
+ "key": sample.key,
2080
+ "title": sample.title,
2081
+ "description": sample.description,
2082
+ "filename": sample.filename,
2083
+ "available": meta.available,
2084
+ "size_bytes": meta.size_bytes,
2085
+ "sha256": meta.sha256,
2086
+ "schema_version": meta.schema_version,
2087
+ "project_count": meta.project_count,
2088
+ "task_count": meta.task_count,
2089
+ "resource_count": meta.resource_count,
2090
+ "download_url": reverse("program-download-sample", kwargs={"key": sample.key}),
2091
+ }
2092
+ )
2093
+ return Response(entries)
2094
+
2095
+ @extend_schema(
2096
+ summary="Download a bundled demo sample's JSON seed file",
2097
+ responses={
2098
+ 200: OpenApiResponse(
2099
+ response=OpenApiTypes.BINARY,
2100
+ description=(
2101
+ "The exact committed fixture bytes, as a JSON file attachment. "
2102
+ "`ETag` is the same SHA-256 the catalog advertises."
2103
+ ),
2104
+ ),
2105
+ 404: OpenApiResponse(description="No such sample key, or the file is missing."),
2106
+ },
2107
+ )
2108
+ @action(
2109
+ detail=False,
2110
+ methods=["get"],
2111
+ url_path=r"samples/(?P<key>[^/.]+)/download",
2112
+ url_name="download-sample",
2113
+ throttle_classes=[SampleDownloadThrottle],
2114
+ )
2115
+ def download_sample(self, request: Request, key: str | None = None) -> HttpResponseBase:
2116
+ """Stream a bundled fixture's exact bytes so it can be read before import (#2490).
2117
+
2118
+ "Load demo data" writes an entire program on one click. This is how a
2119
+ self-hoster reads what it will write first — download the file, inspect
2120
+ it, dry-run it through ``POST /programs/import/validate/``, then import.
2121
+
2122
+ **The security of this endpoint rests on one property: the key never
2123
+ becomes a path.** ``SAMPLES.get(key)`` is a dict lookup and a miss is a
2124
+ 404; the fixture path is built inside the registry from the package
2125
+ directory and the entry's own filename. There is deliberately no
2126
+ sanitizing, no ``..`` stripping and no ``safe_join`` here — every one of
2127
+ those constructs implies a path is being assembled from input, and a
2128
+ reviewer should read their presence as a bug. A traversal-shaped key is
2129
+ not scrubbed; it is simply not a key, so it 404s before any I/O.
2130
+
2131
+ Bytes are streamed rather than parsed and re-serialized: byte-for-byte
2132
+ fidelity is the point, and re-encoding would invalidate the digest the
2133
+ catalog advertised. The ``ETag`` is that same digest, so a conditional
2134
+ request costs nothing and a client can verify what it received.
2135
+ """
2136
+ from trueppm_api.apps.projects.seed.samples import SAMPLES, sample_metadata
2137
+
2138
+ sample = SAMPLES.get(key or "")
2139
+ if sample is None:
2140
+ raise Http404("Unknown sample")
2141
+
2142
+ meta = sample_metadata(sample)
2143
+ if not meta.available:
2144
+ # Registered but absent from disk: a broken install, not a bad
2145
+ # request. Still a 404 to the client — there is nothing to serve.
2146
+ raise Http404("Sample file is not present in this installation")
2147
+
2148
+ etag = f'"{meta.sha256}"' if meta.sha256 else None
2149
+ # Handled here rather than by ConditionalGetMiddleware, which this
2150
+ # project does not install. Without it the ETag would be advertised but
2151
+ # never honored, so every revalidation would re-send the whole file.
2152
+ if etag and _if_none_match_matches(request.headers.get("If-None-Match"), etag):
2153
+ not_modified = HttpResponse(status=status.HTTP_304_NOT_MODIFIED)
2154
+ not_modified.headers["ETag"] = etag
2155
+ return not_modified
2156
+
2157
+ response = FileResponse(
2158
+ sample.path.open("rb"),
2159
+ as_attachment=True,
2160
+ # From the registry entry, never interpolated from the request.
2161
+ filename=sample.filename,
2162
+ content_type="application/json",
2163
+ )
2164
+ if etag:
2165
+ response.headers["ETag"] = etag
2166
+ response.headers["X-Content-Type-Options"] = "nosniff"
2167
+ response.headers["Cache-Control"] = "private, max-age=0, must-revalidate"
2168
+ return response
2169
+
2170
+ @extend_schema(
2171
+ summary="Load a bundled sample program",
2172
+ responses={
2173
+ 201: LoadSampleResponseSerializer,
2174
+ 400: OpenApiResponse(description="``sample`` does not name a known sample key."),
2175
+ 409: OpenApiResponse(
2176
+ description=(
2177
+ "Two live programs already share this sample's slug as their "
2178
+ "``code``, so a reload cannot tell which one to replace. Body: "
2179
+ '``{detail, code: "seed_replace_ambiguous"}``.'
2180
+ )
2181
+ ),
2182
+ },
2183
+ )
2184
+ @action(
2185
+ detail=False,
2186
+ methods=["post"],
2187
+ url_path="load-sample",
2188
+ throttle_classes=[LoadSampleThrottle],
2189
+ )
2190
+ def load_sample(self, request: Request) -> Response:
2191
+ """Load a bundled sample program — the "Load demo data" action (#375, #1054).
2192
+
2193
+ Body: ``{"sample": "<key>"}`` (optional; defaults to the launch demo).
2194
+ The caller becomes OWNER (same authorization as ``create``). Demo
2195
+ persona accounts are created so the boards render fully.
2196
+
2197
+ Rate-limited to the ``sample_load`` scope (:class:`LoadSampleThrottle`),
2198
+ which replaces the viewset's general ``user`` default: one call rebuilds
2199
+ an entire program, so even a modest loop is abusive (#2402).
2200
+
2201
+ **Latency:** this runs the whole import synchronously — seconds, not
2202
+ milliseconds, and proportional to the fixture. Clients must not apply a
2203
+ short request timeout; the web client opts out of its 30 s default for
2204
+ this call the same way it does for MSP import.
2205
+
2206
+ The caller is then assigned the first open sprint's tasks (#1054) so a
2207
+ contributor who loads the demo from My Work sees their own work right
2208
+ away. The response is a ``{program, landing_project_id, sample_key}``
2209
+ envelope: ``landing_project_id`` is the board to land that contributor on
2210
+ (``null`` when the sample has no open sprint), and ``sample_key`` lets the
2211
+ client render the matching post-load "Start exploring" guidance.
2212
+ """
2213
+ from trueppm_api.apps.projects.seed.importer import SeedReplaceAmbiguous
2214
+ from trueppm_api.apps.projects.seed.samples import (
2215
+ DEFAULT_SAMPLE,
2216
+ UnknownSampleError,
2217
+ load_sample,
2218
+ prepare_sample_for_user,
2219
+ )
2220
+ from trueppm_api.apps.projects.services import KeyAssignmentError
2221
+
2222
+ key = object_body(request).get("sample", DEFAULT_SAMPLE)
2223
+ try:
2224
+ program = load_sample(key, owner=request.user, create_users=True)
2225
+ except KeyAssignmentError as exc:
2226
+ # next_free_key's suffix-attempt cap (security-review Low,
2227
+ # perf-check Low): reachable here if this sample were loaded far
2228
+ # more times than any real workspace would — a 400, not a 500.
2229
+ return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)
2230
+ except SeedReplaceAmbiguous as exc:
2231
+ # The demo loader reloads in place, so it passes replace=True — but
2232
+ # Program.code is non-unique, and two live sample programs sharing
2233
+ # this slug cannot be told apart by a reload. A 409 the caller can
2234
+ # act on, not the 500 an unhandled refusal would produce.
2235
+ return Response(
2236
+ {"detail": str(exc), "code": "seed_replace_ambiguous"},
2237
+ status=status.HTTP_409_CONFLICT,
2238
+ )
2239
+ except UnknownSampleError as exc:
2240
+ # Standardized on the `detail` envelope (#1325). False positive: the
2241
+ # message only echoes the caller's own submitted sample key.
2242
+ return Response(
2243
+ {"detail": str(exc)}, # codeql[py/stack-trace-exposure]
2244
+ status=status.HTTP_400_BAD_REQUEST,
2245
+ )
2246
+
2247
+ landing_project = prepare_sample_for_user(program, request.user)
2248
+
2249
+ fresh = self.get_queryset().get(pk=program.pk)
2250
+ return Response(
2251
+ {
2252
+ "program": ProgramSerializer(fresh).data,
2253
+ "landing_project_id": (
2254
+ str(landing_project.id) if landing_project is not None else None
2255
+ ),
2256
+ "sample_key": key,
2257
+ },
2258
+ status=status.HTTP_201_CREATED,
2259
+ )
2260
+
2261
+ @extend_schema(
2262
+ summary="Shift a sample program's dates to today",
2263
+ request=None,
2264
+ responses={
2265
+ 200: ShiftSampleDatesResponseSerializer,
2266
+ 400: OpenApiResponse(
2267
+ description=(
2268
+ "The program is not sample data (``code: not_a_sample``), or it is a "
2269
+ "sample loaded before #3481 and carries no anchor date "
2270
+ "(``code: no_anchor_recorded``) — that one is reloaded, not shifted."
2271
+ )
2272
+ ),
2273
+ },
2274
+ )
2275
+ @action(detail=True, methods=["post"], url_path="shift-sample-dates")
2276
+ def shift_sample_dates(self, request: Request, pk: str | None = None) -> Response:
2277
+ """Re-anchor a sample's dates to today — "Shift dates to today" (#3481).
2278
+
2279
+ Owner-only, and blocked on closed programs. **Takes no request body**: the
2280
+ offset is always ``today - sample_anchor_date`` rounded to whole weeks, so
2281
+ there is no caller-supplied target date to validate, no unbounded offset,
2282
+ and nothing to replay. That is a deliberate contract choice, not an
2283
+ omission — a bulk date rewrite that accepts an arbitrary delta is a very
2284
+ different endpoint to secure.
2285
+
2286
+ Idempotent: the anchor advances by exactly the offset applied, so pressing
2287
+ the button twice returns ``shifted: false`` and writes nothing.
2288
+
2289
+ ADR-1175 for the three-tier field rule — what moves, what is recomputed,
2290
+ and what is deliberately left alone.
2291
+ """
2292
+ from trueppm_api.apps.projects.seed.reanchor import (
2293
+ NoAnchorRecorded,
2294
+ NotASampleProgram,
2295
+ shift_sample_dates,
2296
+ )
2297
+
2298
+ program = self.get_object()
2299
+ try:
2300
+ report = shift_sample_dates(program, actor=request.user)
2301
+ except NotASampleProgram as exc:
2302
+ # A plain Response, never a raised APIException: DRF's exception
2303
+ # handler calls set_rollback() for every APIException, and under
2304
+ # ATOMIC_REQUESTS that would discard the refusal path's writes and any
2305
+ # on_commit callback with them. This path writes nothing, so there is
2306
+ # nothing to lose either way — returning directly keeps it that way.
2307
+ return Response(
2308
+ {"detail": str(exc), "code": "not_a_sample"},
2309
+ status=status.HTTP_400_BAD_REQUEST,
2310
+ )
2311
+ except NoAnchorRecorded as exc:
2312
+ return Response(
2313
+ {"detail": str(exc), "code": "no_anchor_recorded"},
2314
+ status=status.HTTP_400_BAD_REQUEST,
2315
+ )
2316
+
2317
+ if report.shifted:
2318
+ # Every task, sprint and baseline on every project moved, so each
2319
+ # project's board is stale for any live subscriber. Deferred to commit
2320
+ # — a broadcast sent inside the transaction would advertise dates a
2321
+ # rollback could still take back.
2322
+ broadcast_ids = [
2323
+ str(pk_)
2324
+ for pk_ in Project.objects.filter(program=program, is_deleted=False).values_list(
2325
+ "id", flat=True
2326
+ )
2327
+ ]
2328
+ transaction.on_commit(partial(_broadcast_projects_updated, broadcast_ids))
2329
+
2330
+ return Response(
2331
+ {
2332
+ "shifted": report.shifted,
2333
+ "days": report.days,
2334
+ "anchor_date": report.anchor_date.isoformat(),
2335
+ "rows_shifted": report.rows_shifted,
2336
+ "projects": report.projects,
2337
+ },
2338
+ status=status.HTTP_200_OK,
2339
+ )
2340
+
2341
+ @extend_schema(
2342
+ summary="Tear down a sample program",
2343
+ responses={204: OpenApiResponse(description="Sample program purged; empty body.")},
2344
+ )
2345
+ @action(detail=True, methods=["post"], url_path="remove-sample")
2346
+ def remove_sample(self, request: Request, pk: str | None = None) -> Response:
2347
+ """Tear down a sample program — the "Remove sample data" action (#375).
2348
+
2349
+ Owner-only. Refuses to delete a program that is not sample data, so the
2350
+ teardown can never remove real work. Hard-deletes the *entire* program
2351
+ subtree (all projects, not only is_sample ones — a sample program holds
2352
+ only sample projects). Unlike ``destroy`` this is a hard delete, not a
2353
+ soft delete: sample data is disposable, so it is purged outright. Each
2354
+ deleted project gets its own ``project_hard_deleted`` broadcast (#4374) —
2355
+ that is what an open tab actually reconciles on; the program-level
2356
+ ``program_deleted`` broadcast below is kept for forward compatibility but
2357
+ reaches no client today, since no program WS channel exists yet (#836).
2358
+ """
2359
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
2360
+
2361
+ program = self.get_object()
2362
+ is_sample = Project.objects.filter(
2363
+ program=program, is_sample=True, is_deleted=False
2364
+ ).exists()
2365
+ if not is_sample:
2366
+ return Response(
2367
+ {"detail": "This program is not sample data."},
2368
+ status=status.HTTP_400_BAD_REQUEST,
2369
+ )
2370
+ program_id = str(program.pk)
2371
+ with transaction.atomic():
2372
+ # Lock the program row so a concurrent member-add / project-assign
2373
+ # can't resurrect a PROTECTed reference mid-teardown.
2374
+ Program.objects.select_for_update().filter(pk=program.pk).first()
2375
+ # hard_delete_program resolves the PROTECT-ing children from _meta rather
2376
+ # than listing them here — the hand-written list this replaced covered
2377
+ # memberships but not mention groups, so teardown 500'd on any sample
2378
+ # program that had one (#2364). broadcast=True is what makes an open tab
2379
+ # on one of the deleted projects learn it is gone (#4374).
2380
+ hard_delete_program(program.pk, broadcast=True)
2381
+ transaction.on_commit(
2382
+ lambda: broadcast_board_event(program_id, "program_deleted", {"id": program_id})
2383
+ )
2384
+ return Response(status=status.HTTP_204_NO_CONTENT)
2385
+
2386
+ def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:
2387
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
2388
+
2389
+ instance = self.get_object()
2390
+ program_id = str(instance.pk)
2391
+ delete_program_cascade(instance.pk)
2392
+ # delete_program_cascade detaches projects (program=NULL) — emit a single
2393
+ # program-level event rather than fanning out per-project; clients
2394
+ # already invalidate project queries on program_deleted.
2395
+ transaction.on_commit(
2396
+ lambda: broadcast_board_event(program_id, "program_deleted", {"id": program_id})
2397
+ )
2398
+ return Response(status=status.HTTP_204_NO_CONTENT)
2399
+
2400
+ # -----------------------------------------------------------------------
2401
+ # Lifecycle actions (#530)
2402
+ # -----------------------------------------------------------------------
2403
+
2404
+ @extend_schema(
2405
+ summary="Close the program",
2406
+ responses={200: ProgramSerializer},
2407
+ )
2408
+ @action(detail=True, methods=["post"], url_path="close")
2409
+ def close(self, request: Request, pk: str | None = None) -> Response:
2410
+ """Mark the program as closed (read-only shell). Owner only (#530).
2411
+
2412
+ Closing a program freezes the program-level surfaces (members, settings,
2413
+ ceremonies). Child projects are NOT cascaded — they retain their own
2414
+ lifecycle, matching the UI dialog's "projects remain active" warning.
2415
+ """
2416
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
2417
+
2418
+ program = self.get_object()
2419
+ if not program.is_closed:
2420
+ program.is_closed = True
2421
+ program.closed_at = timezone.now()
2422
+ program.closed_by = request.user # type: ignore[assignment]
2423
+ program.save(update_fields=["is_closed", "closed_at", "closed_by"])
2424
+ program_id = str(program.pk)
2425
+ transaction.on_commit(
2426
+ lambda: broadcast_board_event(program_id, "program_closed", {"id": program_id})
2427
+ )
2428
+ fresh = self.get_queryset().get(pk=program.pk)
2429
+ return Response(ProgramSerializer(fresh).data, status=status.HTTP_200_OK)
2430
+
2431
+ @extend_schema(
2432
+ summary="Reopen a closed program",
2433
+ responses={200: ProgramSerializer},
2434
+ )
2435
+ @action(detail=True, methods=["post"], url_path="reopen")
2436
+ def reopen(self, request: Request, pk: str | None = None) -> Response:
2437
+ """Reopen a closed program. Owner only (#530)."""
2438
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
2439
+
2440
+ program = self.get_object()
2441
+ if program.is_closed:
2442
+ program.is_closed = False
2443
+ program.closed_at = None
2444
+ program.closed_by = None
2445
+ program.save(update_fields=["is_closed", "closed_at", "closed_by"])
2446
+ program_id = str(program.pk)
2447
+ transaction.on_commit(
2448
+ lambda: broadcast_board_event(program_id, "program_reopened", {"id": program_id})
2449
+ )
2450
+ fresh = self.get_queryset().get(pk=program.pk)
2451
+ return Response(ProgramSerializer(fresh).data, status=status.HTTP_200_OK)
2452
+
2453
+ @extend_schema(
2454
+ summary="Transfer program sponsorship to another member",
2455
+ responses={
2456
+ 200: ProgramSerializer,
2457
+ 400: validation_envelope_400(
2458
+ "Missing new_owner_user_id, or new_owner_user_id/new_lead_user_id does "
2459
+ "not resolve to an existing active member of this program (an unknown "
2460
+ "id, a real id with no membership, and a deactivated member's id all "
2461
+ "return the same body — #4575)."
2462
+ ),
2463
+ },
2464
+ )
2465
+ @action(detail=True, methods=["post"], url_path="transfer-sponsorship")
2466
+ def transfer_sponsorship(self, request: Request, pk: str | None = None) -> Response:
2467
+ """Transfer program sponsorship to another existing member (#530).
2468
+
2469
+ Body: ``{"new_owner_user_id": "<uuid>", "new_lead_user_id": "<uuid>?"}``.
2470
+ The new sponsor must already hold a ``ProgramMembership`` at any role —
2471
+ invite first if not. The current OWNER is atomically demoted to ADMIN.
2472
+ Optionally rotates ``program.lead`` so the program header chip moves
2473
+ with the role.
2474
+ """
2475
+ from django.contrib.auth import get_user_model
2476
+
2477
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
2478
+
2479
+ program = self.get_object()
2480
+ # A non-object JSON body (list, string) has no ``.get`` — treat it as
2481
+ # empty so the ``new_owner_user_id is required`` branch returns 400
2482
+ # rather than raising AttributeError (500).
2483
+ body = request.data if isinstance(request.data, dict) else {}
2484
+ new_owner_id = body.get("new_owner_user_id")
2485
+ new_lead_id = body.get("new_lead_user_id")
2486
+
2487
+ if not new_owner_id:
2488
+ return Response(
2489
+ {"detail": "new_owner_user_id is required."},
2490
+ status=status.HTTP_400_BAD_REQUEST,
2491
+ )
2492
+
2493
+ # An unresolvable id (unknown pk, or a pk that doesn't even parse)
2494
+ # returns the SAME 400 body as "that user exists but isn't a member"
2495
+ # below — not a distinct 404 — so neither status code nor message
2496
+ # lets a caller distinguish "no such user" from "real user, not a
2497
+ # member" (or "real user, deactivated") without ever seeing the
2498
+ # target's email. See services.py's module docstring on these
2499
+ # constants for the full rationale (#4575).
2500
+ User = get_user_model()
2501
+ try:
2502
+ new_owner = User.objects.get(pk=new_owner_id)
2503
+ except (User.DoesNotExist, DjangoValidationError, ValueError):
2504
+ return Response(
2505
+ {"detail": PROGRAM_OWNER_NOT_MEMBER_DETAIL},
2506
+ status=status.HTTP_400_BAD_REQUEST,
2507
+ )
2508
+
2509
+ new_lead = None
2510
+ if new_lead_id:
2511
+ try:
2512
+ new_lead = User.objects.get(pk=new_lead_id)
2513
+ except (User.DoesNotExist, DjangoValidationError, ValueError):
2514
+ return Response(
2515
+ {"detail": PROGRAM_LEAD_NOT_MEMBER_DETAIL},
2516
+ status=status.HTTP_400_BAD_REQUEST,
2517
+ )
2518
+
2519
+ try:
2520
+ transfer_program_sponsorship(
2521
+ program=program,
2522
+ new_owner=new_owner,
2523
+ actor=request.user,
2524
+ new_lead=new_lead,
2525
+ )
2526
+ except DjangoValidationError as exc:
2527
+ # False positive: surfaces the service's own curated validation
2528
+ # message (role/membership reason), not a trace or internal.
2529
+ detail = exc.messages[0] if exc.messages else str(exc)
2530
+ return Response(
2531
+ {"detail": detail}, # codeql[py/stack-trace-exposure]
2532
+ status=status.HTTP_400_BAD_REQUEST,
2533
+ )
2534
+
2535
+ program_id = str(program.pk)
2536
+ transaction.on_commit(
2537
+ lambda: broadcast_board_event(
2538
+ program_id,
2539
+ "program_sponsorship_transferred",
2540
+ {"id": program_id, "new_owner_id": str(new_owner.pk)},
2541
+ )
2542
+ )
2543
+ fresh = self.get_queryset().get(pk=program.pk)
2544
+ return Response(ProgramSerializer(fresh).data, status=status.HTTP_200_OK)
2545
+
2546
+ @extend_schema(
2547
+ summary="Split a program into sub-programs",
2548
+ responses={
2549
+ 200: OpenApiResponse(
2550
+ description=(
2551
+ "The closed parent program plus the created sub-programs: "
2552
+ "`{program, sub_programs}`."
2553
+ )
2554
+ ),
2555
+ 400: OpenApiResponse(
2556
+ description="Invalid payload, or a project does not belong to this program."
2557
+ ),
2558
+ },
2559
+ )
2560
+ @action(detail=True, methods=["post"], url_path="split")
2561
+ def split(self, request: Request, pk: str | None = None) -> Response:
2562
+ """Split a program into sub-programs and close the original (ADR-0156, #967).
2563
+
2564
+ Each entry in ``splits`` becomes a new program owned by the caller
2565
+ (methodology copied from the parent, inheritable settings left to inherit
2566
+ the workspace defaults); the entry's projects are moved under it. Only the
2567
+ ``Project.program`` FK moves, so tasks, dependencies, baselines, and history
2568
+ are preserved. The original program is closed afterwards and keeps any
2569
+ projects that were not redistributed. The whole operation is atomic.
2570
+
2571
+ Owner only (``IsProgramOwner``); a closed program cannot be split
2572
+ (``IsProgramNotClosed``), which also makes a retried request safe — once
2573
+ the parent is closed a replay is rejected before it can double-split.
2574
+
2575
+ Body: ``{"splits": [{"name": str, "project_ids": [uuid]}, ...]}``
2576
+ """
2577
+ from trueppm_api.apps.access.services import split_program
2578
+ from trueppm_api.apps.projects.services import KeyAssignmentError
2579
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
2580
+
2581
+ # Owner-only object check (also confirms the program exists).
2582
+ program = self.get_object()
2583
+
2584
+ # Guard the top-level body shape first: a non-object JSON body (string/
2585
+ # scalar) has no ``.get``, so an unguarded access raises AttributeError →
2586
+ # 500. Any non-object body is treated as a missing "splits" → 400 (#2126).
2587
+ splits = request.data.get("splits") if isinstance(request.data, dict) else None
2588
+ if not isinstance(splits, list) or not splits:
2589
+ return Response(
2590
+ {"detail": "splits must be a non-empty array."},
2591
+ status=status.HTTP_400_BAD_REQUEST,
2592
+ )
2593
+ # Bound the number of sub-programs created in one call — even an Owner
2594
+ # shouldn't be able to spawn unbounded empty programs in a single request.
2595
+ if len(splits) > _MAX_SPLITS:
2596
+ return Response(
2597
+ {"detail": f"A program can be split into at most {_MAX_SPLITS} sub-programs."},
2598
+ status=status.HTTP_400_BAD_REQUEST,
2599
+ )
2600
+ for split in splits:
2601
+ if not isinstance(split, dict):
2602
+ return Response(
2603
+ {"detail": "Each split entry must be an object."},
2604
+ status=status.HTTP_400_BAD_REQUEST,
2605
+ )
2606
+ if not split.get("name") or not isinstance(split.get("project_ids"), list):
2607
+ return Response(
2608
+ {"detail": "Each split must include 'name' and 'project_ids' array."},
2609
+ status=status.HTTP_400_BAD_REQUEST,
2610
+ )
2611
+
2612
+ try:
2613
+ sub_programs = split_program(program=program, splits=splits, actor=request.user)
2614
+ except DjangoValidationError as exc:
2615
+ # False positive: surfaces the service's own curated validation
2616
+ # message (the offending project id is the caller's own input).
2617
+ detail = exc.messages[0] if exc.messages else str(exc)
2618
+ return Response(
2619
+ {"detail": detail}, # codeql[py/stack-trace-exposure]
2620
+ status=status.HTTP_400_BAD_REQUEST,
2621
+ )
2622
+ except KeyAssignmentError as exc:
2623
+ # A sub-program's derived key hit next_free_key's suffix-attempt cap
2624
+ # (security-review Low, perf-check Low) — a 400, not a 500.
2625
+ return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)
2626
+
2627
+ program_id = str(program.pk)
2628
+ sub_ids = [str(sub.pk) for sub in sub_programs]
2629
+ transaction.on_commit(
2630
+ lambda: broadcast_board_event(
2631
+ program_id,
2632
+ "program_split",
2633
+ {"id": program_id, "sub_program_ids": sub_ids},
2634
+ )
2635
+ )
2636
+
2637
+ fresh = self.get_queryset().get(pk=program.pk)
2638
+ return Response(
2639
+ {
2640
+ "program": ProgramSerializer(fresh).data,
2641
+ "sub_programs": ProgramSerializer(sub_programs, many=True).data,
2642
+ },
2643
+ status=status.HTTP_200_OK,
2644
+ )
2645
+
2646
+ # -----------------------------------------------------------------------
2647
+ # Custom actions
2648
+ # -----------------------------------------------------------------------
2649
+
2650
+ @extend_schema(
2651
+ summary="List projects in this program",
2652
+ responses={200: ProgramProjectRowSerializer(many=True)},
2653
+ )
2654
+ # This action returns a bare array, but ProgramViewSet sets pagination_class,
2655
+ # so the auto-schema would otherwise declare a PaginatedProjectList envelope
2656
+ # the real body violates (#2213). Opt out so the schema matches the response.
2657
+ @suppress_list_pagination
2658
+ @action(detail=True, methods=["get"], url_path="projects")
2659
+ def projects(self, request: Request, pk: str | None = None) -> Response:
2660
+ """List projects in this program.
2661
+
2662
+ URL: ``GET /api/v1/programs/{pk}/projects/``
2663
+
2664
+ Permission: IsProgramMember (any program role can see the project list,
2665
+ but the project itself only opens if the user also has project membership
2666
+ — that gate is enforced by the project's own viewset on click-through).
2667
+
2668
+ Because that gate is membership-*existence* only, a program **Viewer** reaches
2669
+ this action, and the row set below is every non-draft project in the program
2670
+ rather than the caller's own. Both halves are deliberate — a program member is
2671
+ meant to see what is in the program — but together they mean the response shape
2672
+ is the disclosure boundary, which is why this serializes
2673
+ ``ProgramProjectRowSerializer`` and not ``ProjectSerializer`` (#3439). Read that
2674
+ class's docstring before widening it; the fields it omits are governance
2675
+ settings that belong on the membership-gated ``GET /projects/{id}/``.
2676
+ """
2677
+ from trueppm_api.apps.projects.mcp_settings import mcp_excluded_project_ids
2678
+
2679
+ program = self.get_object()
2680
+ # Per-project overdue / at-risk counts (#560), so the Projects tab reads
2681
+ # like a morning standup. "Incomplete" excludes COMPLETE and soft-deleted
2682
+ # rows; "overdue" = past the CPM early_finish; "at-risk" reuses the
2683
+ # canonical ≤5-working-days-of-float rule (cf. ProjectViewSet.status_summary).
2684
+ #
2685
+ # Computed below via program_rollup.drift_counts_by_project(), a grouped
2686
+ # query over Task keyed by project_id (same shape as
2687
+ # risk_counts_by_project), rather than an annotation on this Project
2688
+ # queryset (#4276): leaf rows only — a phase's `total_float`/
2689
+ # `early_finish` are rollups of its children (ADR-0024/ADR-0293), not
2690
+ # facts about the phase row itself — and that exclusion's RawSQL names
2691
+ # its own FROM table (`projects_task`) literally, which neither a
2692
+ # reverse-FK `Count("tasks", filter=...)` (the join Django adds for
2693
+ # `tasks` is not guaranteed to resolve to that bare name) nor a second
2694
+ # correlated `Subquery` over `Task` stacked in the same `.annotate()`
2695
+ # (Django disambiguates with `U0`/`U1` instead) can be relied on to
2696
+ # preserve. See that function's docstring for why.
2697
+ today = timezone.localdate()
2698
+ # ---------------------------------------------------------------------
2699
+ # THIS ACTION BUILDS ITS OWN QUERYSET, and therefore inherits NOTHING from
2700
+ # ProjectScopedViewSet.get_queryset — not its `pk__in=member_project_ids`
2701
+ # membership filter, and not the per-caller annotations it adds on the way
2702
+ # past. That bypass has now produced three separate defects: `is_pinned`
2703
+ # silently false on every row (#2553), `my_role`/`can_author` silently null
2704
+ # and false on every row (#3357), and the full 86-field ProjectSerializer
2705
+ # reaching callers with no ProjectMembership (#3439). Each was repaired here
2706
+ # by hand, below, because there is no shared path to inherit from.
2707
+ #
2708
+ # So: the row set is program-scoped, NOT membership-scoped — every non-draft
2709
+ # project in the program, for any program role down to Viewer. That is
2710
+ # intentional (a program member is meant to see what is in the program), and
2711
+ # it is why the response serializer, not the filter, is what keeps a
2712
+ # non-member row safe. If you add a per-caller field to ProjectSerializer,
2713
+ # it does NOT arrive here; wire it explicitly, and decide whether it belongs
2714
+ # on ProgramProjectRowSerializer at all.
2715
+ #
2716
+ # OPEN QUESTION, deliberately left open: `Project.visibility` is stored but not
2717
+ # yet enforced (TODO(#2066) on the model). When it is, this route has to answer
2718
+ # whether a PRIVATE project's row — its existence, name, code, start date, health
2719
+ # and risk counts — still reaches every program Viewer. The paragraph above is a
2720
+ # statement about the defect #3439 fixed, NOT a ruling on #2066; do not cite it
2721
+ # as settling that. `visible_projects()` drops drafts and nothing else today.
2722
+ # ---------------------------------------------------------------------
2723
+ qs = (
2724
+ visible_projects(Project.objects.filter(program=program, is_deleted=False))
2725
+ # `program` is select_related because the three surviving inheritance reads
2726
+ # — effective_methodology, inherited_methodology, effective_iteration_label
2727
+ # — resolve project ?? program ?? workspace and would otherwise cost a query
2728
+ # per row for the program tier. (The workspace tier is the shared singleton,
2729
+ # loaded once by the serializer's cached workspace.)
2730
+ #
2731
+ # The calendar joins and the two `*__exceptions` prefetches that used to sit
2732
+ # here are GONE with #3439: they existed solely for `effective_calendar` /
2733
+ # `calendar_source`, and ProgramProjectRowSerializer does not serialize
2734
+ # either. Keeping them cost two queries per request — each an unbounded read
2735
+ # of calendar-exception rows — to build data nothing rendered. Re-add them
2736
+ # only alongside a field that actually reads a calendar.
2737
+ .select_related("program")
2738
+ .annotate(
2739
+ # Bulk-methodology impact preview counts (#3296). Each is its own
2740
+ # correlated Subquery — a single-column, single-group query plan
2741
+ # over its own base model — rather than a filtered Count joined
2742
+ # onto this Project queryset's `tasks` / `baselines` / dependency
2743
+ # relations, which would multiply the join instead of adding to
2744
+ # it. (overdue_count/at_risk_count moved off this queryset
2745
+ # entirely, to program_rollup.drift_counts_by_project() — see the
2746
+ # comment above this annotate() block.)
2747
+ sprint_count=Coalesce(
2748
+ Subquery(
2749
+ Sprint.objects.filter(project=OuterRef("pk"))
2750
+ .order_by()
2751
+ .values("project")
2752
+ .annotate(c=Count("id"))
2753
+ .values("c"),
2754
+ output_field=IntegerField(),
2755
+ ),
2756
+ 0,
2757
+ ),
2758
+ # Mirrors `_backlog_stories()` (product_backlog_services.py) — the
2759
+ # same scope the product-backlog view lists, which WATERFALL hides.
2760
+ backlog_story_count=Coalesce(
2761
+ Subquery(
2762
+ Task.objects.filter(
2763
+ project=OuterRef("pk"),
2764
+ is_deleted=False,
2765
+ status=TaskStatus.BACKLOG,
2766
+ sprint__isnull=True,
2767
+ )
2768
+ .exclude(type=TaskType.EPIC)
2769
+ .order_by()
2770
+ .values("project")
2771
+ .annotate(c=Count("id"))
2772
+ .values("c"),
2773
+ output_field=IntegerField(),
2774
+ ),
2775
+ 0,
2776
+ ),
2777
+ baseline_count=Coalesce(
2778
+ Subquery(
2779
+ Baseline.objects.filter(project=OuterRef("pk"))
2780
+ .order_by()
2781
+ .values("project")
2782
+ .annotate(c=Count("id"))
2783
+ .values("c"),
2784
+ output_field=IntegerField(),
2785
+ ),
2786
+ 0,
2787
+ ),
2788
+ # `Dependency.objects` is the unfiltered default manager (sync/reap
2789
+ # need soft-deleted rows elsewhere) — `is_deleted=False` here mirrors
2790
+ # `LiveDependencyManager`, the scope the Gantt itself draws.
2791
+ dependency_count=Coalesce(
2792
+ Subquery(
2793
+ Dependency.objects.filter(
2794
+ predecessor__project=OuterRef("pk"), is_deleted=False
2795
+ )
2796
+ .order_by()
2797
+ .values("predecessor__project")
2798
+ .annotate(c=Count("id"))
2799
+ .values("c"),
2800
+ output_field=IntegerField(),
2801
+ ),
2802
+ 0,
2803
+ ),
2804
+ )
2805
+ .order_by("start_date", "name")
2806
+ )
2807
+ # ADR-0678 T1 (#2482): this lists CHILD PROJECT rows (with per-project task
2808
+ # counts), which the mixin's Program-row filter does not reach.
2809
+ _excluded = mcp_excluded_project_ids(request)
2810
+ if _excluded is not None:
2811
+ qs = qs.exclude(pk__in=_excluded)
2812
+ # `is_pinned` for THIS caller (#2553). The annotation normally arrives via
2813
+ # ProjectViewSet.get_queryset, which this action bypasses by building its
2814
+ # own queryset — and ProjectSerializer.get_is_pinned reads the attribute
2815
+ # defensively, so the omission degraded to a silent `false` on every row
2816
+ # rather than raising. Bound positionally to request.user (ADR-0627 §D5),
2817
+ # so it can only ever answer "did I pin this".
2818
+ qs = annotate_is_pinned(qs, request.user, field="project")
2819
+ # …and `_my_role` for the same reason, one class of bug later (#3357).
2820
+ # `ProjectSerializer` derives THREE caller-scoped fields from this annotation —
2821
+ # `my_role`, `my_role_label` and `can_author` — plus, as of #3357,
2822
+ # `can_undo_batch_operations`. Every one of them reads the attribute
2823
+ # defensively and then falls back to a request-scoped lookup, and this action
2824
+ # serializes without `context`, so the fallback finds no request and fails
2825
+ # closed. The result was not "degraded": it was a confident `null` role and a
2826
+ # uniform `can_author: false` on every row for every caller including an
2827
+ # Owner, on a route whose `@extend_schema` publishes `ProjectSerializer` as its
2828
+ # response. A Subquery, so this stays one scalar per row rather than the
2829
+ # per-row membership query the fallback path would have cost.
2830
+ if request.user is not None and request.user.is_authenticated:
2831
+ from trueppm_api.apps.access.models import ProjectMembership
2832
+
2833
+ qs = qs.annotate(
2834
+ _my_role=Subquery(
2835
+ ProjectMembership.objects.filter(
2836
+ project=OuterRef("pk"), user=request.user, is_deleted=False
2837
+ ).values("role")[:1]
2838
+ )
2839
+ )
2840
+ # #3420: ProgramViewSet declares SearchFilter + OrderingFilter, so
2841
+ # drf-spectacular publishes `search` and `ordering` on this operation — but the
2842
+ # action never ran them, so both were accepted, documented, and dropped. Honor
2843
+ # them: `search_fields = ["name", "code"]` and `ordering_fields = ["name"]` are
2844
+ # all real Project columns, so they need no translation to apply here.
2845
+ #
2846
+ # Applied AFTER the `.order_by("start_date", "name")` above, deliberately.
2847
+ # OrderingFilter is a no-op when the caller sends no `?ordering=` (the view sets
2848
+ # no `ordering` default), so the roster's start-date order survives untouched;
2849
+ # send one and it replaces that order, which is the whole point. Running it
2850
+ # *before* the `order_by` — the obvious placement — would let the hardcoded
2851
+ # order clobber the caller's every time, reintroducing the same silent-drop bug
2852
+ # one line later.
2853
+ #
2854
+ # Second effect, deliberate: `McpReadableViewMixin.filter_queryset` is in this
2855
+ # viewset's MRO, so this call ALSO runs the ADR-0678 opt-out over the Project
2856
+ # queryset (it dispatches on the model, landing on the `Project` branch). That
2857
+ # duplicates the explicit `mcp_excluded_project_ids` exclusion above — the two
2858
+ # are idempotent and agree. Both are kept on purpose: the explicit exclude is the
2859
+ # #2482 T1 enforcement and must not depend on this line's placement, and this
2860
+ # line must not be reordered to "avoid" a filter it is not the authority for.
2861
+ # For an agent token it also sets `request._mcp_scope_filtered`, so the T8 audit
2862
+ # annotation now records the narrowing on this route as well.
2863
+ qs = self.filter_queryset(qs)
2864
+ # Materialized here (one query — the queryset above, including every
2865
+ # annotation, is still lazy up to this point) so overdue_count/
2866
+ # at_risk_count can be attached as plain attributes from the
2867
+ # drift_counts_by_project() dict (#4276) — the same `getattr(obj,
2868
+ # "overdue_count", None)` read ProjectSerializer.get_overdue_count()
2869
+ # already does, so neither the serializer nor its field declarations
2870
+ # change. A second query (the grouped Task aggregate), not a per-row
2871
+ # query: project_rows is the full bounded page, not one row at a time.
2872
+ project_rows = list(qs)
2873
+ drift_counts = drift_counts_by_project([p.id for p in project_rows], today)
2874
+ for p in project_rows:
2875
+ # Dynamic attributes, same as the other `_change_reason`-style
2876
+ # non-field writes in this app — there is no model field to type
2877
+ # them against, by design (see the comment above).
2878
+ p.overdue_count, p.at_risk_count = drift_counts.get( # type: ignore[attr-defined]
2879
+ p.id, (0, 0)
2880
+ )
2881
+ # Serialized WITH context (#3439). Be precise about why, because the obvious
2882
+ # reason is no longer the true one: of the 20 retained fields, the only two that
2883
+ # ever read `self.context["request"]` were `can_author` and
2884
+ # `can_undo_batch_operations`, and ProgramProjectRowSerializer overrides both to
2885
+ # resolve from the `_my_role` annotation alone. So **no retained field needs the
2886
+ # request today**. It is passed because a serializer rendering a response should
2887
+ # be able to see the request that asked for it — the omission was a latent defect
2888
+ # waiting on the first context-reading field anyone added — and passing it now
2889
+ # means that field works instead of silently failing closed.
2890
+ #
2891
+ # The cost of passing it is bounded and checked: it activates the parent's
2892
+ # `__init__` branch that re-scopes `copy_settings_from`, which exits without a
2893
+ # query because that field is absent from `Meta.fields`. Add a write-only field
2894
+ # to this serializer and that branch starts costing a membership query per
2895
+ # request — and the two overridden getters are what keep the per-ROW cost at
2896
+ # zero. See the query-count test before changing either.
2897
+ return Response(
2898
+ ProgramProjectRowSerializer(project_rows, many=True, context={"request": request}).data
2899
+ )
2900
+
2901
+ @extend_schema(
2902
+ summary="Get the program-scoped integrations summary",
2903
+ responses={
2904
+ 200: OpenApiResponse(
2905
+ description=(
2906
+ "Summary object with `webhooks` and `api_tokens` sections "
2907
+ "scoped to the program."
2908
+ )
2909
+ ),
2910
+ 503: OpenApiResponse(
2911
+ description="A subservice failed; body names the `failed` section."
2912
+ ),
2913
+ },
2914
+ )
2915
+ @action(detail=True, methods=["get"], url_path="integrations-summary")
2916
+ def integrations_summary(self, request: Request, pk: str | None = None) -> Response:
2917
+ """Program-scoped integrations summary (ADR-0076).
2918
+
2919
+ URL: ``GET /api/v1/programs/{pk}/integrations-summary/``
2920
+
2921
+ Returns the program's outbound webhooks and inbound API tokens that
2922
+ are scoped to the program itself — does NOT bubble up resources from
2923
+ child projects (those have their own per-project summaries).
2924
+
2925
+ Same shape and per-section 503 fallback semantics as the project
2926
+ endpoint so the frontend can re-use the hook contract.
2927
+ """
2928
+ import logging
2929
+
2930
+ from django.db.models import Q
2931
+ from rest_framework import status as drf_status
2932
+
2933
+ from trueppm_api.apps.projects.views import (
2934
+ _summarize_api_tokens,
2935
+ _summarize_webhooks,
2936
+ )
2937
+
2938
+ logger = logging.getLogger(__name__)
2939
+
2940
+ program = self.get_object()
2941
+ sections: dict[str, Any] = {}
2942
+
2943
+ try:
2944
+ sections["webhooks"] = _summarize_webhooks(Q(program_id=program.id))
2945
+ except Exception:
2946
+ logger.exception("program integrations-summary webhooks subservice failed")
2947
+ return Response(
2948
+ {"failed": "webhooks"},
2949
+ status=drf_status.HTTP_503_SERVICE_UNAVAILABLE,
2950
+ )
2951
+
2952
+ try:
2953
+ sections["api_tokens"] = _summarize_api_tokens(Q(program_id=program.id))
2954
+ except Exception:
2955
+ logger.exception("program integrations-summary api_tokens subservice failed")
2956
+ return Response(
2957
+ {"failed": "api_tokens"},
2958
+ status=drf_status.HTTP_503_SERVICE_UNAVAILABLE,
2959
+ )
2960
+
2961
+ return Response(sections, status=drf_status.HTTP_200_OK)
2962
+
2963
+ @extend_schema(
2964
+ summary="Count who @program-stakeholders reaches",
2965
+ responses={
2966
+ 200: inline_serializer(
2967
+ name="ProgramMentionReach",
2968
+ fields={
2969
+ "group_key": serializers.CharField(),
2970
+ "viewer_member_count": serializers.IntegerField(),
2971
+ "external_stakeholder_count": serializers.IntegerField(),
2972
+ },
2973
+ )
2974
+ },
2975
+ )
2976
+ @action(detail=True, methods=["get"], url_path="mention-reach")
2977
+ def mention_reach(self, request: Request, pk: str | None = None) -> Response:
2978
+ """Who the ``@program-stakeholders`` alias reaches, counted per arm.
2979
+
2980
+ URL: ``GET /api/v1/programs/{pk}/mention-reach/``
2981
+
2982
+ The alias has two arms that ADR-0264 deliberately keeps apart, and this
2983
+ endpoint keeps them apart too:
2984
+
2985
+ * ``viewer_member_count`` — exact-``Role.VIEWER`` members across the
2986
+ program's live projects, deduplicated by user. Real accounts; they get a
2987
+ durable in-app notification today.
2988
+ * ``external_stakeholder_count`` — registry rows with no ``User``. They
2989
+ receive nothing today; outbound delivery is deferred to #1675.
2990
+
2991
+ **The response carries no total on purpose** (ADR-0697 §1a). Summing the two
2992
+ arms would re-assert in the API the very union #1675 removed from the
2993
+ resolver — the union under which an internal mention could silently email a
2994
+ client. Clients must render the arms separately.
2995
+
2996
+ Computed on read from the same querysets the resolver uses, so the number a
2997
+ PM is shown is the number a mention would fan out to. Permission: program
2998
+ Admin+.
2999
+ """
3000
+ from trueppm_api.apps.access.groups import count_program_stakeholder_reach
3001
+ from trueppm_api.apps.projects.mcp_settings import mcp_excluded_project_ids
3002
+
3003
+ program = self.get_object()
3004
+
3005
+ # ADR-0678 T1 (#2482): the internal arm aggregates CHILD PROJECT membership,
3006
+ # which the mixin's row filter — it only ever sees the Program row — cannot
3007
+ # reach. Intersect explicitly, exactly as rollup/schedule/projects do. The
3008
+ # ADR-0678 T8 audit flag needs no set here: get_object() already ran the
3009
+ # mixin's filter, which sets it centrally for a token caller.
3010
+ reach = count_program_stakeholder_reach(
3011
+ program.pk, exclude_project_ids=mcp_excluded_project_ids(request)
3012
+ )
3013
+ return Response(
3014
+ {
3015
+ "group_key": "program-stakeholders",
3016
+ "viewer_member_count": reach.viewer_member_count,
3017
+ "external_stakeholder_count": reach.external_stakeholder_count,
3018
+ }
3019
+ )
3020
+
3021
+ @extend_schema(
3022
+ summary="Read or update the program rollup KPIs config",
3023
+ responses={200: ProgramRollupConfigSerializer},
3024
+ )
3025
+ @action(detail=True, methods=["get", "patch"], url_path="rollup-config")
3026
+ def rollup_config(self, request: Request, pk: str | None = None) -> Response:
3027
+ """Read or update the program rollup KPIs config (ADR-0169, #527).
3028
+
3029
+ URL: ``GET|PATCH /api/v1/programs/{pk}/rollup-config/``
3030
+
3031
+ Permission split is method-level (see ``get_permissions``): any
3032
+ member can read, only admins can write. Audit is automatic via the
3033
+ ``HistoricalRecords()`` already on Program — every successful PATCH
3034
+ creates a ``HistoricalProgram`` row with the field diff.
3035
+ """
3036
+ program = self.get_object()
3037
+ if request.method == "GET":
3038
+ return Response(ProgramRollupConfigSerializer(program).data)
3039
+
3040
+ serializer = ProgramRollupConfigSerializer(program, data=request.data, partial=True)
3041
+ serializer.is_valid(raise_exception=True)
3042
+ serializer.save()
3043
+ # Re-serialize from the fresh instance so the response carries any
3044
+ # field-level normalization (de-duped KPI list) applied by the
3045
+ # serializer's validators.
3046
+ return Response(ProgramRollupConfigSerializer(program).data)
3047
+
3048
+ @extend_schema(
3049
+ summary="Compute the program KPI rollup across its projects",
3050
+ responses={200: ProgramRollupSerializer},
3051
+ )
3052
+ @action(detail=True, methods=["get"], url_path="rollup")
3053
+ def rollup(self, request: Request, pk: str | None = None) -> Response:
3054
+ """Computed rollup of the enabled KPIs across the program's projects.
3055
+
3056
+ URL: ``GET /api/v1/programs/{pk}/rollup/``
3057
+
3058
+ Consumes the #527 config (``rollup_enabled_kpis`` +
3059
+ ``rollup_aggregation_policy``) and returns the rolled-up values per
3060
+ ADR-0088 — the program health dot, the active policy (and whether it
3061
+ could be honored), the contributing project count, and a per-KPI map
3062
+ where deferred KPIs carry ``{"available": False, "reason": ...}``.
3063
+
3064
+ Read-only and computed on demand (no persisted rollup row), so it always
3065
+ reflects the projects' current state. Permission: any program member.
3066
+ """
3067
+ from trueppm_api.apps.projects.mcp_settings import mcp_excluded_project_ids
3068
+ from trueppm_api.apps.projects.program_rollup import compute_program_rollup
3069
+
3070
+ program = self.get_object()
3071
+ return Response(
3072
+ compute_program_rollup(
3073
+ program,
3074
+ # ADR-0678 T1 (#2482): this is a program-scoped read that aggregates
3075
+ # CHILD PROJECT data, so the mixin's row filter (which sees only the
3076
+ # Program row) does not reach it. Opted-out projects are dropped here.
3077
+ exclude_project_ids=mcp_excluded_project_ids(request),
3078
+ )
3079
+ )
3080
+
3081
+ @extend_schema(
3082
+ summary="Compute the program-true cross-project schedule",
3083
+ responses={200: ProgramScheduleSerializer},
3084
+ )
3085
+ @action(
3086
+ detail=True,
3087
+ methods=["get"],
3088
+ url_path="schedule",
3089
+ throttle_classes=[ProgramScheduleThrottle],
3090
+ )
3091
+ def schedule(self, request: Request, pk: str | None = None) -> Response:
3092
+ """Merged, program-true critical path across the program's projects.
3093
+
3094
+ URL: ``GET /api/v1/programs/{pk}/schedule/``
3095
+
3096
+ Loads every member project's tasks and every accepted cross-project edge
3097
+ into one engine graph and runs the deterministic CPM once (ADR-0120 D3
3098
+ read side; render-don't-derive per ADR-0115) — the source the #1118
3099
+ program schedule view consumes. Computed on demand; nothing is persisted,
3100
+ so it always reflects current project state.
3101
+
3102
+ Permission: any program member (closed programs stay readable for
3103
+ forensics). Tasks in member projects the requester cannot read are
3104
+ redacted to the ADR-0120 D5 ExternalTaskCard shape — never their
3105
+ description, assignee, status, or points, only title and program-true
3106
+ CPM dates. ``can_access_project`` is the per-project membership predicate;
3107
+ injecting it keeps the schedule service request-agnostic.
3108
+ """
3109
+ from trueppm_api.apps.access.permissions import (
3110
+ _membership_role,
3111
+ role_can_subscribe_live,
3112
+ )
3113
+ from trueppm_api.apps.projects.mcp_settings import mcp_excluded_project_ids
3114
+ from trueppm_api.apps.projects.program_schedule import compute_program_schedule
3115
+
3116
+ program = self.get_object()
3117
+ return Response(
3118
+ compute_program_schedule(
3119
+ program,
3120
+ can_access_project=lambda project_id: (
3121
+ _membership_role(request, project_id) is not None
3122
+ ),
3123
+ # ADR-0678 T1 (#2482): opted-out projects are DROPPED from the merged
3124
+ # graph, not redacted — the ExternalTaskCard redaction still exposes
3125
+ # task titles and program-true CPM dates, which is the wrong answer for
3126
+ # a project that explicitly withheld consent.
3127
+ exclude_project_ids=mcp_excluded_project_ids(request),
3128
+ # #4375: the program page opens one socket per member project; this
3129
+ # is the consumer's own floor, so it never dials one that refuses it.
3130
+ # ``_membership_role`` caches per request, so this adds no queries
3131
+ # beyond the ``can_access_project`` lookups above.
3132
+ can_subscribe_live=lambda project_id: role_can_subscribe_live(
3133
+ _membership_role(request, project_id)
3134
+ ),
3135
+ )
3136
+ )
3137
+
3138
+ @extend_schema(
3139
+ summary="Search tasks across a program's projects (cross-project dep picker)",
3140
+ parameters=[
3141
+ OpenApiParameter(
3142
+ "q",
3143
+ OpenApiTypes.STR,
3144
+ description="Case-insensitive substring matched against task name or notes.",
3145
+ required=True,
3146
+ ),
3147
+ OpenApiParameter(
3148
+ "exclude_project",
3149
+ OpenApiTypes.UUID,
3150
+ description=(
3151
+ "Project to omit from results — the picker's own project, whose "
3152
+ "tasks the client already has locally."
3153
+ ),
3154
+ required=False,
3155
+ ),
3156
+ ],
3157
+ responses={
3158
+ 200: OpenApiResponse(
3159
+ description=(
3160
+ "Slim rows `[{id, name, short_id, short_id_display, qualified_id, "
3161
+ "project_id, project_name}]` for tasks in member projects the "
3162
+ "caller can read."
3163
+ )
3164
+ )
3165
+ },
3166
+ )
3167
+ @action(detail=True, methods=["get"], url_path="task-search")
3168
+ def task_search(self, request: Request, pk: str | None = None) -> Response:
3169
+ """Search tasks across a program's projects, to pick a cross-project edge.
3170
+
3171
+ URL: ``GET /api/v1/programs/{pk}/task-search/?q=<term>&exclude_project=<uuid>``
3172
+
3173
+ Backs the ADR-0120 cross-project dependency picker: the schedule picker is
3174
+ single-project, so a user cannot today reach a sibling project's task to
3175
+ gate against it. This returns a slim, sensitive-field-free list scoped to
3176
+ the program's member projects **the caller can actively read** — the D5
3177
+ "creator needs read access to both tasks" creation rule. A member project
3178
+ the caller cannot read is simply not searched (its tasks are not offered),
3179
+ so no unauthorized task titles leak through the picker.
3180
+
3181
+ Slim shape (``[{id, name, short_id, short_id_display, qualified_id,
3182
+ project_id, project_name}]``) carries no cost/budget/status/assignee
3183
+ fields, so role-based field visibility is moot — project readability is
3184
+ the only gate (same rationale as the per-project ``TaskViewSet.search``
3185
+ action). ``short_id`` is still returned for callers that need the raw
3186
+ value, but ``short_id_display``/``qualified_id`` are what a UI must
3187
+ render (#2671) — this hand-built row bypassed ``TaskSerializer``
3188
+ entirely and returned the raw hex, which is exactly the leak both the
3189
+ cross-project dependency picker (``ScheduleDependencyPicker``) and the
3190
+ cross-project relation picker (``RelatedLinkPicker``) inherited from it.
3191
+ ``qualified_id`` is where this endpoint matters most: it is the only one
3192
+ of the six/seven #2671 sites where results are genuinely cross-project,
3193
+ so the project-code prefix is what disambiguates two sibling projects'
3194
+ task 3 from each other.
3195
+ """
3196
+ from django.db.models import Case, IntegerField, Value, When
3197
+
3198
+ from trueppm_api.apps.access.models import ProjectMembership
3199
+
3200
+ program = self.get_object()
3201
+
3202
+ # IsAuthenticated already gates this action; the guard also narrows the
3203
+ # type for the membership lookup below.
3204
+ user = request.user
3205
+ if not (user and user.is_authenticated):
3206
+ return Response([], status=status.HTTP_200_OK)
3207
+
3208
+ raw_q = (request.query_params.get("q") or "").strip()
3209
+ if not raw_q:
3210
+ return Response([], status=status.HTTP_200_OK)
3211
+ # DoS guard: a pathological term can't force an unbounded trigram scan.
3212
+ q = raw_q[:100]
3213
+
3214
+ exclude_project = request.query_params.get("exclude_project")
3215
+
3216
+ # Member projects the caller can read, minus the picker's own project.
3217
+ # Readability is the D5 "read access to both tasks" rule; a non-readable
3218
+ # member project is dropped entirely (rather than redacted, as ``schedule``
3219
+ # does) because an unpickable task should not appear at all. A single
3220
+ # membership query resolves the whole program's readable set — the same
3221
+ # ``ProjectMembership`` predicate ``_membership_role`` applies per row, but
3222
+ # here in one pass rather than N per-project lookups.
3223
+ from trueppm_api.apps.projects.mcp_settings import mcp_excluded_project_ids
3224
+
3225
+ membership_qs = ProjectMembership.objects.filter(
3226
+ project__program=program,
3227
+ project__is_deleted=False,
3228
+ user=user,
3229
+ is_deleted=False,
3230
+ )
3231
+ # ADR-0678 T1 (#2482): the picker searches tasks across CHILD PROJECTS, which
3232
+ # the mixin's Program-row filter does not reach. An opted-out project is
3233
+ # dropped entirely — the same treatment a non-readable member project gets.
3234
+ _excluded = mcp_excluded_project_ids(request)
3235
+ if _excluded is not None:
3236
+ membership_qs = membership_qs.exclude(project_id__in=_excluded)
3237
+ readable_ids = set(membership_qs.values_list("project_id", flat=True))
3238
+ # (name, code) per readable project — the code is what lets a result row
3239
+ # carry a qualified_id (#2671); before this it was name-only and every
3240
+ # row fell back to the ambiguous compact form.
3241
+ readable: dict[str, tuple[str, str]] = {}
3242
+ # Drafts are excluded (#2962/#3128): "search result" is on the exclusion
3243
+ # list, and this picker is worse than a plain search — every row it offers
3244
+ # becomes a cross-project dependency, so gating committed work on a plan
3245
+ # nobody has agreed to would let a draft move a real project's dates.
3246
+ for row in visible_projects(
3247
+ Project.objects.filter(program=program, is_deleted=False, id__in=readable_ids)
3248
+ ).values("id", "name", "code"):
3249
+ pid = str(row["id"])
3250
+ if exclude_project is not None and pid == str(exclude_project):
3251
+ continue
3252
+ readable[pid] = (row["name"], row["code"] or "")
3253
+
3254
+ if not readable:
3255
+ return Response([], status=status.HTTP_200_OK)
3256
+
3257
+ qs = (
3258
+ Task.objects.filter(project_id__in=list(readable.keys()), is_deleted=False)
3259
+ .filter(Q(name__icontains=q) | Q(notes__icontains=q))
3260
+ # Title matches rank above description-only matches; project then name
3261
+ # are the stable tiebreaks so grouped results stay deterministic.
3262
+ .annotate(
3263
+ _name_match=Case(
3264
+ When(name__icontains=q, then=Value(0)),
3265
+ default=Value(1),
3266
+ output_field=IntegerField(),
3267
+ )
3268
+ )
3269
+ .order_by("_name_match", "project_id", "name")
3270
+ )
3271
+ # `.values()` after an `.annotate()` is typed by django-stubs as the
3272
+ # annotated Task row (carrying `_name_match`), not a plain dict, so the
3273
+ # index access below trips mypy. The projection genuinely yields dicts;
3274
+ # cast to reflect that.
3275
+ rows = cast(
3276
+ "list[dict[str, Any]]",
3277
+ list(qs.values("id", "name", "short_id", "project_id")[:200]),
3278
+ )
3279
+ results: list[dict[str, Any]] = []
3280
+ for task_row in rows:
3281
+ project_name, project_code = readable[str(task_row["project_id"])]
3282
+ # Same decode + qualify rule as TaskSerializer (#2430, ADR-1237) —
3283
+ # this row is hand-built rather than serialized through
3284
+ # TaskSerializer (the queryset above is a search projection, not a
3285
+ # Task instance list), so it must apply the rule itself rather
3286
+ # than inherit it.
3287
+ display = format_short_id_display(task_row["short_id"], "T")
3288
+ qualified = f"{project_code}-{display}" if project_code and display else display
3289
+ results.append(
3290
+ {
3291
+ "id": str(task_row["id"]),
3292
+ "name": task_row["name"],
3293
+ "short_id": task_row["short_id"],
3294
+ "short_id_display": display,
3295
+ "qualified_id": qualified,
3296
+ "project_id": str(task_row["project_id"]),
3297
+ "project_name": project_name,
3298
+ }
3299
+ )
3300
+ return Response(results, status=status.HTTP_200_OK)
3301
+
3302
+ @extend_schema(
3303
+ summary="Read or update the program risk & dependencies policy",
3304
+ responses={200: ProgramRiskPolicySerializer},
3305
+ )
3306
+ @action(detail=True, methods=["get", "patch"], url_path="risk-policy")
3307
+ def risk_policy(self, request: Request, pk: str | None = None) -> Response:
3308
+ """Read or update the program risk & deps policy (#529).
3309
+
3310
+ URL: ``GET|PATCH /api/v1/programs/{pk}/risk-policy/``
3311
+
3312
+ Permission split mirrors ``rollup_config`` (see ``get_permissions``):
3313
+ any member can read, only admins can write. Audit is automatic via
3314
+ the ``HistoricalRecords()`` already on Program — every successful
3315
+ PATCH creates a ``HistoricalProgram`` row with the field diff.
3316
+
3317
+ The 5×5 risk matrix surfaced on the same Settings page is
3318
+ intentionally out of scope here — those thresholds are workspace-
3319
+ wide and read-only at the program level.
3320
+ """
3321
+ program = self.get_object()
3322
+ if request.method == "GET":
3323
+ return Response(ProgramRiskPolicySerializer(program).data)
3324
+
3325
+ serializer = ProgramRiskPolicySerializer(program, data=request.data, partial=True)
3326
+ serializer.is_valid(raise_exception=True)
3327
+ serializer.save()
3328
+ return Response(ProgramRiskPolicySerializer(program).data)
3329
+
3330
+ @extend_schema(
3331
+ summary="Bulk-set inherited settings across multiple programs",
3332
+ request=BulkFieldsRequestSerializer,
3333
+ responses={
3334
+ 200: OpenApiResponse(
3335
+ description="Per-program id + new server_version, and the fields applied."
3336
+ )
3337
+ },
3338
+ )
3339
+ @action(detail=False, methods=["post"], url_path="bulk-fields")
3340
+ def bulk_fields(self, request: Request) -> Response:
3341
+ """Set inherited settings on a selection of programs in one call (ADR-0161, #1233).
3342
+
3343
+ URL: ``POST /api/v1/programs/bulk-fields/`` — the Workspace → Programs matrix scope.
3344
+
3345
+ Body ``{"ids": [<program uuid>...], "fields": {"methodology": "AGILE", ...}}``:
3346
+ only the named fields on the named programs change; every other program and every
3347
+ other field keeps inheriting. Workspace-admin only — the matrix is a
3348
+ workspace-settings surface. Each row is written via ``save()`` so ``server_version``
3349
+ bumps for offline sync and ``HistoricalProgram`` audits the diff. All-or-nothing.
3350
+ """
3351
+ envelope = BulkFieldsRequestSerializer(data=request.data)
3352
+ envelope.is_valid(raise_exception=True)
3353
+ with transaction.atomic():
3354
+ rows = apply_bulk_fields(
3355
+ field_serializer_cls=ProgramBulkFieldsSerializer,
3356
+ queryset=Program.objects.filter(is_deleted=False, is_closed=False),
3357
+ ids=envelope.validated_data["ids"],
3358
+ fields=envelope.validated_data["fields"],
3359
+ )
3360
+ return Response(build_bulk_response(rows, envelope.validated_data["fields"]))
3361
+
3362
+ @extend_schema(
3363
+ summary="Bulk-set inherited settings across this program's projects",
3364
+ request=BulkFieldsRequestSerializer,
3365
+ responses={
3366
+ 200: OpenApiResponse(
3367
+ description="Per-project id + new server_version, and the fields applied."
3368
+ )
3369
+ },
3370
+ )
3371
+ @action(detail=True, methods=["post"], url_path="bulk-project-fields")
3372
+ def bulk_project_fields(self, request: Request, pk: str | None = None) -> Response:
3373
+ """Set inherited settings on a selection of this program's projects (ADR-0161, #1233).
3374
+
3375
+ URL: ``POST /api/v1/programs/{pk}/bulk-project-fields/`` — the Program → Projects
3376
+ matrix scope.
3377
+
3378
+ Program-admin only. Targets are constrained to this program's own non-archived
3379
+ projects, so the program PK in the URL is the IDOR boundary — a project id from
3380
+ another program is rejected as out-of-scope (400), never silently skipped. Only the
3381
+ two benign, non-schedule inherited fields (methodology, iteration_label) ship in
3382
+ this slice; ``calendar`` is deferred (schedule-affecting, no bulk recalc path yet).
3383
+ """
3384
+ from trueppm_api.apps.projects.config_notice import (
3385
+ capture_project_surface,
3386
+ collect_project_surface_change,
3387
+ notify_surface_changes,
3388
+ )
3389
+ from trueppm_api.apps.workspace.models import Workspace
3390
+
3391
+ program = self.get_object()
3392
+ envelope = BulkFieldsRequestSerializer(data=request.data)
3393
+ envelope.is_valid(raise_exception=True)
3394
+ targets = Project.objects.filter(program_id=program.pk, is_deleted=False, is_archived=False)
3395
+ with transaction.atomic():
3396
+ # Snapshot the preset/visibility of every target BEFORE the apply.
3397
+ # This route is the *other* way a methodology preset gets switched
3398
+ # (ADR-0161's settings matrix), and a team whose board was re-shaped
3399
+ # from the program matrix has exactly the same right to be told as one
3400
+ # whose PM used the project settings page (#2972). The extra read is
3401
+ # bounded by MAX_BULK_TARGETS and hoists the workspace singleton so it
3402
+ # is not reloaded per row.
3403
+ #
3404
+ # Locked on the way in, for the same reason the board PUT locks its
3405
+ # baseline: `apply_bulk_fields` takes `select_for_update` on these rows
3406
+ # a moment later, so an unlocked read here could snapshot a preset a
3407
+ # concurrent write is about to replace — and the notice would then name
3408
+ # a "from" preset that was never the one this call changed.
3409
+ workspace = Workspace.load()
3410
+ before = {
3411
+ row.pk: capture_project_surface(row, workspace=workspace)
3412
+ for row in targets.filter(
3413
+ pk__in=[str(i) for i in envelope.validated_data["ids"]]
3414
+ ).select_for_update()
3415
+ }
3416
+ rows = apply_bulk_fields(
3417
+ field_serializer_cls=ProjectBulkFieldsSerializer,
3418
+ queryset=targets,
3419
+ ids=envelope.validated_data["ids"],
3420
+ fields=envelope.validated_data["fields"],
3421
+ )
3422
+ changes = []
3423
+ for row in rows:
3424
+ snapshot = before.get(row.pk)
3425
+ if snapshot is None:
3426
+ continue
3427
+ change = collect_project_surface_change(row, before=snapshot, workspace=workspace)
3428
+ if change is None:
3429
+ continue
3430
+ changes.append(change)
3431
+ # This path has never broadcast, which was survivable while it was only
3432
+ # a settings write. It is not survivable now: the notice tells the team
3433
+ # their views moved, so an open client that never hears `project_updated`
3434
+ # keeps rendering the old surface and makes the notice look wrong
3435
+ # (#2972). Only projects whose surface actually moved are broadcast — a
3436
+ # pure `iteration_label` edit stays silent on both channels.
3437
+ #
3438
+ # ONE callback for the whole batch, on both channels. Registering a
3439
+ # callback per project would put up to MAX_BULK_TARGETS separate
3440
+ # entries on the on-commit queue for one request.
3441
+ broadcast_ids = [change.project_id for change in changes]
3442
+ if broadcast_ids:
3443
+ transaction.on_commit(partial(_broadcast_projects_updated, broadcast_ids))
3444
+ notify_surface_changes(changes, actor=request.user)
3445
+ return Response(build_bulk_response(rows, envelope.validated_data["fields"]))