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