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,1749 @@
1
+ """DRF ViewSets for the resources app."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from decimal import Decimal
7
+ from typing import Any, cast
8
+
9
+ from django.db import models, transaction
10
+ from django.db.models import DateField, ProtectedError, QuerySet
11
+ from django.db.models.functions import Coalesce
12
+ from drf_spectacular.types import OpenApiTypes
13
+ from drf_spectacular.utils import (
14
+ OpenApiParameter,
15
+ OpenApiResponse,
16
+ extend_schema,
17
+ extend_schema_view,
18
+ )
19
+ from rest_framework import filters, status, viewsets
20
+ from rest_framework.decorators import action
21
+ from rest_framework.exceptions import PermissionDenied, ValidationError
22
+ from rest_framework.permissions import BasePermission, IsAuthenticated
23
+ from rest_framework.request import Request
24
+ from rest_framework.response import Response
25
+ from rest_framework.serializers import BaseSerializer
26
+ from rest_framework.throttling import UserRateThrottle
27
+
28
+ from trueppm_api.apps.access.models import ProjectMembership, Role
29
+ from trueppm_api.apps.access.permissions import (
30
+ CanAssignResource,
31
+ IsOrgAdmin,
32
+ IsOrgScheduler,
33
+ IsProjectMember,
34
+ IsProjectNotArchived,
35
+ ProjectScopedViewSet,
36
+ _membership_role,
37
+ assert_project_not_archived,
38
+ )
39
+ from trueppm_api.apps.idempotency.mixins import IdempotencyMixin
40
+ from trueppm_api.apps.projects.models import Project, Task, TaskActivityEventType
41
+ from trueppm_api.apps.projects.utilization import (
42
+ Allocation,
43
+ peak_concurrent_units,
44
+ resolve_working_calendar,
45
+ )
46
+ from trueppm_api.apps.resources.capacity import resource_effective_units
47
+ from trueppm_api.apps.resources.models import (
48
+ Proficiency,
49
+ ProjectResource,
50
+ Resource,
51
+ ResourceSkill,
52
+ Skill,
53
+ TaskResource,
54
+ TaskSkillRequirement,
55
+ )
56
+ from trueppm_api.apps.resources.serializers import (
57
+ ProjectResourceSerializer,
58
+ ResourceAssignmentSerializer,
59
+ ResourceSerializer,
60
+ ResourceSkillSerializer,
61
+ SkillSerializer,
62
+ TaskResourceSerializer,
63
+ TaskSkillRequirementSerializer,
64
+ )
65
+ from trueppm_api.apps.resources.services import (
66
+ ensure_project_resource,
67
+ record_assignment_event,
68
+ task_is_summary,
69
+ )
70
+ from trueppm_api.apps.scheduling.services import enqueue_recalculate as _enqueue_recalculate
71
+ from trueppm_api.apps.workspace.permissions import IsWorkspaceAdminStrict, is_workspace_admin
72
+ from trueppm_api.core.protect_conflict import protected_error_response
73
+
74
+ # Shared 404 detail — matches DRF's default NotFound detail so a missing or
75
+ # soft-deleted lookup reads identically across the resource actions below.
76
+ _NOT_FOUND_DETAIL = "Not found."
77
+
78
+ #: Refusal shipped when a skill is still tagged on a resource or required by a task.
79
+ #: Both FKs into ``Skill`` are ``on_delete=PROTECT`` (``ResourceSkill.skill``,
80
+ #: ``TaskSkillRequirement.skill``) so deleting a catalog entry cannot silently strip
81
+ #: the skill from every resource that carries it or every task that requires it.
82
+ #: Django reports the refusal as ``ProtectedError``, which is not an ``APIException``
83
+ #: and escaped as an unhandled 500 until #2364.
84
+ _SKILL_IN_USE_DETAIL = "This skill is still in use and cannot be deleted."
85
+
86
+ # ---------------------------------------------------------------------------
87
+ # Skill catalog
88
+ # ---------------------------------------------------------------------------
89
+
90
+
91
+ def _skill_reference_describer(user: Any) -> Callable[[models.Model], dict[str, str]]:
92
+ """Build a describer that names a skill's blockers without leaking task names.
93
+
94
+ ``ResourceSkill`` and ``TaskSkillRequirement`` are join tables the user never
95
+ sees and which have no ``name`` of their own; echoing them back would produce a
96
+ list of opaque UUIDs. What the caller can act on is the resource to retag or the
97
+ task whose requirement to drop.
98
+
99
+ **Task names are membership-scoped, and this endpoint's gate is not.**
100
+ ``IsOrgScheduler`` only proves the caller holds SCHEDULER+ on *some* project, so
101
+ a naive describer would let anyone with one project turn repeated delete attempts
102
+ into an oracle for task names across every project in the install — and a task
103
+ name describes actual work, unlike a resource name. Tasks in projects the caller
104
+ is not a member of are therefore reported by type and id only, with the name
105
+ withheld; ``reference_count`` still reflects the true total, so the refusal stays
106
+ honest about how much is blocking even when it cannot say what.
107
+
108
+ Resource names are *not* filtered: the resource catalog is org-shared and already
109
+ readable by any authenticated user (see :class:`ResourceViewSet`), so naming one
110
+ here discloses nothing the caller could not list directly.
111
+ """
112
+ visible_project_ids = set(
113
+ ProjectMembership.objects.filter(user=user, is_deleted=False).values_list(
114
+ "project_id", flat=True
115
+ )
116
+ )
117
+
118
+ def describe(obj: models.Model) -> dict[str, str]:
119
+ if isinstance(obj, ResourceSkill):
120
+ return {"type": "resource", "id": str(obj.resource_id), "name": obj.resource.name}
121
+ if isinstance(obj, TaskSkillRequirement):
122
+ entry = {"type": "task", "id": str(obj.task_id)}
123
+ if obj.task.project_id in visible_project_ids:
124
+ entry["name"] = obj.task.name
125
+ return entry
126
+ return {"type": obj._meta.model_name or "", "id": str(obj.pk), "name": str(obj)}
127
+
128
+ return describe
129
+
130
+
131
+ @extend_schema_view(
132
+ create=extend_schema(
133
+ summary="Create a skill, or return the existing one",
134
+ description=(
135
+ "Adds a skill to the org-level catalog.\n\n"
136
+ "Names are de-duplicated case-insensitively on `normalized_name`, so "
137
+ "posting a name that already exists is not an error: the existing row is "
138
+ "returned with `200` instead of `201`. Callers that need to know whether "
139
+ "they added the skill must read the status code — the body is identical "
140
+ "either way."
141
+ ),
142
+ responses={
143
+ 200: OpenApiResponse(
144
+ response=SkillSerializer,
145
+ description=(
146
+ "A skill with this normalized name already existed; it is returned unchanged."
147
+ ),
148
+ ),
149
+ 201: OpenApiResponse(
150
+ response=SkillSerializer,
151
+ description="Skill created.",
152
+ ),
153
+ },
154
+ ),
155
+ destroy=extend_schema(
156
+ summary="Delete a skill",
157
+ description=(
158
+ "Deletes a skill from the org-level catalog.\n\n"
159
+ "A skill that is still tagged on a resource or required by a task cannot "
160
+ "be deleted — removing it would silently strip the tag from every resource "
161
+ "that carries it and drop the requirement from every task that needs it. "
162
+ "That is refused with `409`, and the body names the resources and tasks "
163
+ "still using it so the caller can detach them first."
164
+ ),
165
+ responses={
166
+ 204: OpenApiResponse(description="Skill deleted."),
167
+ 409: OpenApiResponse(
168
+ response=OpenApiTypes.OBJECT,
169
+ description=(
170
+ "Skill is still tagged on a resource or required by a task. Body "
171
+ "carries `reference_count` and a `references` sample naming the "
172
+ "resources and tasks to detach first."
173
+ ),
174
+ ),
175
+ },
176
+ ),
177
+ )
178
+ class SkillViewSet(IdempotencyMixin, viewsets.ModelViewSet[Skill]):
179
+ """CRUD for the org-level skill catalog.
180
+
181
+ Any authenticated user may read. Writes require ``SCHEDULER+`` on at least
182
+ one project (#254 — IsProjectMember alone would not gate writes here
183
+ because the route is not project-nested). Skill creation normalises the
184
+ name and returns the existing row if the normalised name already exists
185
+ (de-dup by normalized_name unique constraint).
186
+ """
187
+
188
+ queryset = Skill.objects.filter(is_deleted=False).order_by("name")
189
+ serializer_class = SkillSerializer
190
+ filter_backends = [filters.SearchFilter, filters.OrderingFilter]
191
+ search_fields = ["name", "category"]
192
+ ordering_fields = ["name"]
193
+
194
+ def get_permissions(self) -> list[BasePermission]:
195
+ """Read open to any authenticated user; writes require SCHEDULER+ on any project."""
196
+ if self.request.method in ("GET", "HEAD", "OPTIONS"):
197
+ return [IsAuthenticated()]
198
+ return [IsAuthenticated(), IsOrgScheduler()]
199
+
200
+ def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:
201
+ """Delete the skill, or 409 when a resource or task still uses it.
202
+
203
+ Overrides ``destroy`` rather than ``perform_destroy`` because the refusal body
204
+ carries an integer ``reference_count``, and DRF coerces every value in an
205
+ ``APIException`` detail to ``ErrorDetail`` (a ``str`` subclass) — raising would
206
+ ship the count as ``"3"``. Returning is safe: ``ProtectedError`` is raised
207
+ while the collector walks the FKs, *before* any DELETE is issued, so there is
208
+ no partial state for ``ATOMIC_REQUESTS`` to roll back.
209
+ """
210
+ instance = self.get_object()
211
+ try:
212
+ instance.delete()
213
+ except ProtectedError as exc:
214
+ return protected_error_response(
215
+ exc.protected_objects,
216
+ detail=_SKILL_IN_USE_DETAIL,
217
+ code="skill_in_use",
218
+ describe=_skill_reference_describer(request.user),
219
+ )
220
+ return Response(status=status.HTTP_204_NO_CONTENT)
221
+
222
+ def create(self, request: Request, *args: object, **kwargs: object) -> Response:
223
+ """Create the skill (201), or return the existing row on a de-dup hit (200).
224
+
225
+ The status comes from the ``get_or_create`` flag the serializer records,
226
+ not from an inspection of the saved row. Nothing on a saved ``Skill``
227
+ distinguishes a fresh insert from a de-dup hit, so any re-derived flag is
228
+ a guess: this used to probe ``server_version=0``, which
229
+ ``VersionedModel.save`` never leaves behind (it stamps 1 on insert), so
230
+ the endpoint answered 200 for every create (#3573).
231
+ """
232
+ # ``get_serializer`` is typed as ``BaseSerializer[Skill]``; this viewset
233
+ # never swaps ``serializer_class``, so the concrete type is exact.
234
+ serializer = cast("SkillSerializer", self.get_serializer(data=request.data))
235
+ serializer.is_valid(raise_exception=True)
236
+ skill = serializer.save()
237
+ http_status = status.HTTP_201_CREATED if serializer.created else status.HTTP_200_OK
238
+ return Response(
239
+ self.get_serializer(skill).data,
240
+ status=http_status,
241
+ headers=self.get_success_headers(serializer.data),
242
+ )
243
+
244
+
245
+ # ---------------------------------------------------------------------------
246
+ # Resource skills
247
+ # ---------------------------------------------------------------------------
248
+
249
+
250
+ @extend_schema_view(
251
+ list=extend_schema(
252
+ parameters=[
253
+ OpenApiParameter(
254
+ name="resource",
255
+ type=OpenApiTypes.UUID,
256
+ location=OpenApiParameter.QUERY,
257
+ required=False,
258
+ description="Filter to skill tags for this resource.",
259
+ ),
260
+ ],
261
+ ),
262
+ )
263
+ class ResourceSkillViewSet(IdempotencyMixin, viewsets.ModelViewSet[ResourceSkill]):
264
+ """CRUD for skill tags on resources.
265
+
266
+ Read: any authenticated user (resource catalog is org-shared).
267
+ Write: SCHEDULER+ on at least one active project (``IsOrgScheduler``). The
268
+ route is not project-nested so ``IsProjectMember`` alone would not gate writes.
269
+ The docstring here claimed an ADMIN+ floor via ``IsOrgAdmin``; the code has
270
+ returned ``IsOrgScheduler`` since #254. Corrected to the code, not the reverse
271
+ — skill tagging is curation, which is what the SCHEDULER floor is for.
272
+ """
273
+
274
+ serializer_class = ResourceSkillSerializer
275
+ filter_backends = [filters.OrderingFilter]
276
+ queryset = ResourceSkill.objects.active().select_related("skill").filter(is_deleted=False)
277
+
278
+ def get_permissions(self) -> list[BasePermission]:
279
+ if self.request.method in ("GET", "HEAD", "OPTIONS"):
280
+ return [IsAuthenticated()]
281
+ return [IsAuthenticated(), IsOrgScheduler()]
282
+
283
+ def get_queryset(self) -> QuerySet[ResourceSkill]:
284
+ # ``.active()`` (#3572): the resource row itself is admin-only once
285
+ # deactivated (``?include_deleted=true`` on the catalog), so listing its
286
+ # skill tags to every authenticated user leaked the tail of a record the
287
+ # catalog had already withdrawn. Admins reach a deactivated resource's
288
+ # skills through the catalog's expanded ``skills`` instead.
289
+ qs = ResourceSkill.objects.active().select_related("skill").filter(is_deleted=False)
290
+ resource_id = self.request.query_params.get("resource")
291
+ if resource_id:
292
+ qs = qs.filter(resource_id=resource_id)
293
+ return qs
294
+
295
+
296
+ # ---------------------------------------------------------------------------
297
+ # Project roster
298
+ # ---------------------------------------------------------------------------
299
+
300
+
301
+ @extend_schema_view(
302
+ list=extend_schema(
303
+ parameters=[
304
+ OpenApiParameter(
305
+ name="project",
306
+ type=OpenApiTypes.UUID,
307
+ location=OpenApiParameter.QUERY,
308
+ required=False,
309
+ description="Filter the roster to this project.",
310
+ ),
311
+ ],
312
+ ),
313
+ create=extend_schema(
314
+ responses={
315
+ 201: ProjectResourceSerializer,
316
+ 403: OpenApiResponse(
317
+ description=(
318
+ "Caller lacks the Resource Manager role on the target project, or that "
319
+ "project is archived (#3414). The project is named only in the request "
320
+ "body here, so the refusal comes from the view rather than a permission "
321
+ "class — the status and body are the same either way."
322
+ )
323
+ ),
324
+ },
325
+ ),
326
+ destroy=extend_schema(
327
+ parameters=[
328
+ OpenApiParameter(
329
+ name="force",
330
+ type=OpenApiTypes.BOOL,
331
+ location=OpenApiParameter.QUERY,
332
+ required=False,
333
+ description=(
334
+ "When 'true', cascade-delete the resource's TaskResource rows on "
335
+ "this project and trigger a CPM recalculation. Without it, a 409 "
336
+ "is returned if the resource has live task assignments."
337
+ ),
338
+ ),
339
+ ],
340
+ responses={
341
+ 200: OpenApiResponse(
342
+ response=OpenApiTypes.OBJECT,
343
+ description=(
344
+ "Resource removed from the roster. Body carries "
345
+ "`cascaded_assignment_count` — the number of TaskResource rows "
346
+ "severed, `0` when the resource had no live assignments."
347
+ ),
348
+ ),
349
+ 409: OpenApiResponse(
350
+ response=OpenApiTypes.OBJECT,
351
+ description=(
352
+ "The resource still has live task assignments on this project and "
353
+ "`force=true` was not passed. Body carries `code: "
354
+ '"roster_has_assignments"`, `affected_tasks`, `task_names`, and '
355
+ "`assignment_count`. Distinct from the task-restructure "
356
+ "`has_assignments` warning documented on the errors page — this is "
357
+ "the roster-removal refusal."
358
+ ),
359
+ ),
360
+ },
361
+ ),
362
+ )
363
+ class ProjectResourceViewSet(ProjectScopedViewSet, viewsets.ModelViewSet[ProjectResource]):
364
+ """CRUD for a project's resource roster.
365
+
366
+ Read: any project member (VIEWER+).
367
+ Write: SCHEDULER+ on the project.
368
+ Delete: SCHEDULER+; with ?force=true cascades to TaskResource rows and
369
+ triggers CPM recalculation (ADR-0027). Without force=true returns 409 if
370
+ live task assignments exist.
371
+ """
372
+
373
+ permission_classes = [IsAuthenticated, IsProjectMember, CanAssignResource, IsProjectNotArchived]
374
+ resolves_scope_in_body = {
375
+ "create": (
376
+ "Flat route: the project arrives in the body, so `CanAssignResource."
377
+ "has_permission` cannot scope the write and `has_object_permission` does "
378
+ "not run on a create. `perform_create` resolves the body's project and "
379
+ "applies the same Scheduler+ floor before saving (#3767)."
380
+ )
381
+ }
382
+ serializer_class = ProjectResourceSerializer
383
+ filter_backends = [filters.OrderingFilter]
384
+ queryset = (
385
+ ProjectResource.objects.active()
386
+ .select_related("resource", "resource__calendar")
387
+ .prefetch_related("resource__skills__skill")
388
+ )
389
+
390
+ def get_queryset(self) -> QuerySet[ProjectResource]:
391
+ user_pk = self.request.user.pk
392
+ assert user_pk is not None
393
+ member_project_ids = ProjectMembership.objects.filter(
394
+ user_id=user_pk, is_deleted=False
395
+ ).values_list("project_id", flat=True)
396
+ # ``.active()`` (#3572) is ``is_deleted=False`` on the roster row AND on the
397
+ # resource behind it. The roster row is the surface an off-boarding is
398
+ # measured on: a deactivated person left the catalog but kept a full
399
+ # ``resource_detail`` on every project's Team tab.
400
+ qs = (
401
+ ProjectResource.objects.active()
402
+ .select_related("resource", "resource__calendar")
403
+ .prefetch_related("resource__skills__skill")
404
+ .filter(project_id__in=member_project_ids)
405
+ .order_by("resource__name")
406
+ )
407
+ project_id = self.request.query_params.get("project")
408
+ if project_id:
409
+ qs = qs.filter(project_id=project_id)
410
+ return qs
411
+
412
+ def perform_create(self, serializer: BaseSerializer[ProjectResource]) -> None:
413
+ """Verify SCHEDULER+ role and a live project before adding to roster.
414
+
415
+ The archived check is here, not left to ``IsProjectNotArchived`` on the class,
416
+ because this route is top-level (``POST /api/v1/project-resources/``) and names
417
+ the project only in the request BODY (#3414). ``has_permission`` finds no
418
+ ``project_pk`` kwarg and stands down, and DRF never calls
419
+ ``has_object_permission`` on a create — there is no object yet. The declared
420
+ permission class therefore reads as gating in review and enforces nothing on
421
+ exactly the request that creates a row, which is how roster adds (and the CPM
422
+ recalculation they enqueue) reached archived projects.
423
+ """
424
+ project = serializer.validated_data.get("project")
425
+ if project:
426
+ role = _membership_role(self.request, str(project.pk))
427
+ if role is None or role < Role.SCHEDULER:
428
+ raise PermissionDenied(
429
+ "You need at least Resource Manager role to manage the roster."
430
+ )
431
+ assert_project_not_archived(project.pk)
432
+ instance = serializer.save()
433
+
434
+ # Mirror the destroy() path: a roster add is invisible to connected
435
+ # clients until a refetch without this broadcast.
436
+ project_id = str(instance.project_id)
437
+ resource_id = str(instance.resource_id)
438
+
439
+ def _on_commit() -> None:
440
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
441
+
442
+ broadcast_board_event(
443
+ project_id,
444
+ "roster_changed",
445
+ {"resource_id": resource_id},
446
+ )
447
+
448
+ transaction.on_commit(_on_commit)
449
+
450
+ def perform_update(self, serializer: BaseSerializer[ProjectResource]) -> None:
451
+ """Persist an allocation/notes edit and broadcast the roster change.
452
+
453
+ The SCHEDULER+ floor for detail mutations is enforced declaratively by
454
+ ``CanAssignResource.has_object_permission``; this hook only adds the
455
+ missing real-time signal (#1359) so peers see an allocation or note
456
+ change without a manual refetch — mirroring perform_create/destroy.
457
+ """
458
+ instance = serializer.save()
459
+
460
+ project_id = str(instance.project_id)
461
+ resource_id = str(instance.resource_id)
462
+
463
+ def _on_commit() -> None:
464
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
465
+
466
+ broadcast_board_event(
467
+ project_id,
468
+ "roster_changed",
469
+ {"resource_id": resource_id},
470
+ )
471
+
472
+ transaction.on_commit(_on_commit)
473
+
474
+ def destroy(self, request: Request, *args: object, **kwargs: object) -> Response:
475
+ """Remove a resource from the roster.
476
+
477
+ If the resource has live TaskResource rows on this project and
478
+ force=true is not passed, returns 409 with code "roster_has_assignments".
479
+ With force=true, cascades the deletion and triggers CPM recalculation for
480
+ affected tasks. The code is distinct from the "has_assignments" 2xx
481
+ warning that task-restructure endpoints (indent/outdent/reparent/group)
482
+ return — that is an advisory on a write that succeeded; this is a hard
483
+ refusal of the roster removal itself.
484
+ """
485
+ instance: ProjectResource = self.get_object()
486
+ project_id = str(instance.project_id)
487
+ resource_id = instance.resource_id
488
+
489
+ live_assignments = list(
490
+ TaskResource.objects.filter(
491
+ resource_id=resource_id,
492
+ task__project_id=project_id,
493
+ task__is_deleted=False,
494
+ ).select_related("task")
495
+ )
496
+
497
+ if live_assignments and request.query_params.get("force") != "true":
498
+ task_names = [a.task.name for a in live_assignments[:5]]
499
+ return Response(
500
+ {
501
+ "code": "roster_has_assignments",
502
+ "detail": (
503
+ f"{instance.resource.name} is assigned to "
504
+ f"{len(live_assignments)} task(s) in this project. "
505
+ f"Pass ?force=true to remove and unassign."
506
+ ),
507
+ "affected_tasks": [
508
+ {"id": str(a.task_id), "name": a.task.name} for a in live_assignments[:10]
509
+ ],
510
+ "task_names": task_names,
511
+ "assignment_count": len(live_assignments),
512
+ },
513
+ status=status.HTTP_409_CONFLICT,
514
+ )
515
+
516
+ affected_task_ids = [str(a.task_id) for a in live_assignments]
517
+
518
+ # Cascade: delete TaskResource rows, then the ProjectResource row.
519
+ # Wrapped in atomic() so a mid-sequence failure cannot leave orphaned
520
+ # TaskResource rows without a corresponding ProjectResource (🔴-8).
521
+ with transaction.atomic():
522
+ TaskResource.objects.filter(
523
+ resource_id=resource_id,
524
+ task__project_id=project_id,
525
+ ).delete()
526
+ instance.delete()
527
+
528
+ # The roster shrank regardless of whether the removed resource had any
529
+ # live assignments — a zero-assignment removal is the most common case
530
+ # (#1359). Broadcast roster_changed unconditionally so connected clients
531
+ # refetch the roster; only enqueue a CPM recalc when assignments were
532
+ # actually severed (no schedule input changed otherwise).
533
+ def _on_commit() -> None:
534
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
535
+
536
+ if affected_task_ids:
537
+ _enqueue_recalculate(project_id)
538
+ broadcast_board_event(
539
+ project_id,
540
+ "roster_changed",
541
+ {"resource_id": str(resource_id)},
542
+ )
543
+
544
+ transaction.on_commit(_on_commit)
545
+
546
+ return Response(
547
+ {
548
+ "detail": "Resource removed from project.",
549
+ "cascaded_assignment_count": len(live_assignments),
550
+ },
551
+ status=status.HTTP_200_OK,
552
+ )
553
+
554
+
555
+ # ---------------------------------------------------------------------------
556
+ # Task skill requirements
557
+ # ---------------------------------------------------------------------------
558
+
559
+
560
+ @extend_schema_view(
561
+ list=extend_schema(
562
+ parameters=[
563
+ OpenApiParameter(
564
+ name="task",
565
+ type=OpenApiTypes.UUID,
566
+ location=OpenApiParameter.QUERY,
567
+ required=False,
568
+ description="Filter to skill requirements for this task.",
569
+ ),
570
+ ],
571
+ ),
572
+ create=extend_schema(
573
+ responses={
574
+ 201: TaskSkillRequirementSerializer,
575
+ 403: OpenApiResponse(
576
+ description=(
577
+ "Caller lacks the Resource Manager role on the target task's project, "
578
+ "or that project is archived (#3570). The project is reached only "
579
+ "through the body's task here, so the refusal comes from the view "
580
+ "rather than a permission class — the status and body are the same "
581
+ "either way."
582
+ )
583
+ ),
584
+ },
585
+ ),
586
+ )
587
+ class TaskSkillRequirementViewSet(IdempotencyMixin, viewsets.ModelViewSet[TaskSkillRequirement]):
588
+ """CRUD for skill requirements on tasks.
589
+
590
+ Read: authenticated users scoped to their member projects.
591
+ Write: SCHEDULER+ **on the target task's own project**, and the target task's
592
+ project must not be archived — both enforced per-write by
593
+ :meth:`_require_scheduler_on_task`.
594
+
595
+ This surface is project-scoped, not org-global: every row belongs to exactly
596
+ one task, which belongs to exactly one project. It carried ``IsOrgScheduler``
597
+ as a class gate, which was strictly redundant — anyone passing the real
598
+ per-target check necessarily holds SCHEDULER+ on some project and so passed
599
+ the org gate too. Redundant is not free: it kept a project-scoped endpoint
600
+ inside the blast radius of the self-grantable org derivation (#3569), and it
601
+ made the endpoint's true rule harder to read. Dropped in favour of the check
602
+ that was already doing the work. The archived-project floor (#3570) is the
603
+ same story: enforced inline against the *target* task's project, not via a
604
+ class-level ``IsProjectNotArchived`` that could only ever check the object
605
+ DRF already resolved.
606
+ """
607
+
608
+ serializer_class = TaskSkillRequirementSerializer
609
+ filter_backends = [filters.OrderingFilter]
610
+ queryset = TaskSkillRequirement.objects.select_related("skill", "task").filter(is_deleted=False)
611
+
612
+ def get_permissions(self) -> list[BasePermission]:
613
+ # Writes are authorized against the *target task's* project — both role
614
+ # and archived-state — in perform_create / perform_update /
615
+ # perform_destroy; see _require_scheduler_on_task. No class-level org or
616
+ # archived gate: either could only ever admit a superset of what that
617
+ # check admits.
618
+ return [IsAuthenticated()]
619
+
620
+ def _require_scheduler_on_task(self, task: Task) -> None:
621
+ # This is the *only* authorization on writes (#3569 removed the redundant
622
+ # IsOrgScheduler class gate above it). DRF never runs
623
+ # has_object_permission on create, so without a per-target check a
624
+ # SCHEDULER on project A could annotate a task in project B they've never
625
+ # joined (IDOR, #995). The membership-scoped get_queryset closes the
626
+ # non-member case on update/delete, but a low-role (Member/Viewer) member
627
+ # of the target project would still be a member — so the SCHEDULER floor
628
+ # is enforced on every write, against the *target task's* project.
629
+ role = _membership_role(self.request, str(task.project_id))
630
+ if role is None or role < Role.SCHEDULER:
631
+ # "Resource Manager" is the label for ``Role.SCHEDULER``; "Scheduler"
632
+ # is the code name and appears on no surface, so a refusal naming it
633
+ # sends the reader looking for a role that does not exist (#3503).
634
+ # Matches ``IsProjectScheduler.message``.
635
+ raise PermissionDenied(
636
+ "You need at least Resource Manager role on the target task's project."
637
+ )
638
+ # Archived is lifecycle state, not authority, so it is checked after the role
639
+ # floor and against the same target project. There is no class-level
640
+ # ``IsProjectNotArchived`` here (#3569 dropped the class-level org gate this
641
+ # method sits beside, for the same reason): this route is top-level, so on a
642
+ # create there is no object for ``has_object_permission`` to resolve, and on an
643
+ # update that repoints ``task`` the object DRF would check is the OLD row,
644
+ # whose project may be live while the destination is archived (#3570).
645
+ assert_project_not_archived(task.project_id)
646
+
647
+ def perform_create(self, serializer: BaseSerializer[TaskSkillRequirement]) -> None:
648
+ self._require_scheduler_on_task(serializer.validated_data["task"])
649
+ super().perform_create(serializer)
650
+
651
+ def perform_update(self, serializer: BaseSerializer[TaskSkillRequirement]) -> None:
652
+ # Guard both the current row's project and any repointed ``task`` so an
653
+ # update can neither mutate a row on a project the actor lacks SCHEDULER
654
+ # on, nor move a requirement onto a task in such a project.
655
+ instance = serializer.instance
656
+ if instance is not None:
657
+ self._require_scheduler_on_task(instance.task)
658
+ new_task = serializer.validated_data.get("task")
659
+ if new_task is not None:
660
+ self._require_scheduler_on_task(new_task)
661
+ super().perform_update(serializer)
662
+
663
+ def perform_destroy(self, instance: TaskSkillRequirement) -> None:
664
+ self._require_scheduler_on_task(instance.task)
665
+ super().perform_destroy(instance)
666
+
667
+ def get_queryset(self) -> QuerySet[TaskSkillRequirement]:
668
+ # Scope to tasks in projects where the requesting user is a member.
669
+ from typing import cast
670
+
671
+ from django.contrib.auth.models import User
672
+
673
+ user = cast(User, self.request.user)
674
+ member_project_ids = ProjectMembership.objects.filter(
675
+ user=user, is_deleted=False
676
+ ).values_list("project_id", flat=True)
677
+ # select_related("task") avoids N+1 queries in perform_update and
678
+ # perform_destroy, both of which call _require_scheduler_on_task(instance.task)
679
+ # and therefore load task.project_id (R1).
680
+ qs = TaskSkillRequirement.objects.select_related("skill", "task").filter(
681
+ is_deleted=False,
682
+ task__project_id__in=member_project_ids,
683
+ )
684
+ task_id = self.request.query_params.get("task")
685
+ if task_id:
686
+ qs = qs.filter(task_id=task_id)
687
+ return qs
688
+
689
+
690
+ # ---------------------------------------------------------------------------
691
+ # Resource with skill-fit annotation
692
+ # ---------------------------------------------------------------------------
693
+
694
+
695
+ class _WorkspaceAdminEmailSearchFilter(filters.SearchFilter):
696
+ """SearchFilter that only lets a workspace admin search the catalog by email (#892).
697
+
698
+ The catalog is readable by any authenticated user, and email is stripped from
699
+ payloads below workspace ADMIN (#891). But a static
700
+ ``search_fields = ["name", "email"]`` still let anyone else probe email existence
701
+ via ``?search=<email-substring>`` (a hit narrows the candidate set even though the
702
+ value is never echoed). This backend gates the searchable fields on the same check
703
+ the serializer uses: workspace admins search name + email; everyone else searches
704
+ name only.
705
+
706
+ Raised from the org-admin derivation to the stored workspace role in #3569 — the
707
+ org-admin check it used to call was reachable by any account that created a
708
+ throwaway project, which made the #891 harvest control decorative.
709
+ """
710
+
711
+ def get_search_fields(self, view: object, request: Request) -> list[str]:
712
+ if _request_is_workspace_admin(request):
713
+ return ["name", "email"]
714
+ return ["name"]
715
+
716
+
717
+ def _request_is_workspace_admin(request: Request) -> bool:
718
+ """Return True if the requesting user holds workspace ADMIN or above.
719
+
720
+ A request-shaped wrapper over
721
+ :func:`~trueppm_api.apps.workspace.permissions.is_workspace_admin`, which is the
722
+ single definition — do not re-derive the role test here. This one exists because
723
+ a ``SearchFilter`` backend has no permission class to hang the check on. Gates
724
+ email visibility in search (#892) and the ``?include_deleted=true`` deactivated
725
+ pool (#1374), matching :class:`IsWorkspaceAdminStrict` on the sibling actions.
726
+
727
+ This used to derive admin authority from holding ADMIN+ on any project, in
728
+ lockstep with ``IsOrgAdmin``. That derivation is self-grantable in two requests
729
+ (#3569): nothing gates ``POST /projects/`` and ``perform_create`` makes the caller
730
+ Owner. ``WorkspaceMembership`` is granted only by an existing workspace admin or
731
+ by SSO provisioning, so it is not reachable that way.
732
+ """
733
+ return is_workspace_admin(getattr(request, "user", None))
734
+
735
+
736
+ def _caller_is_project_member(request: Request, project_id: Any) -> bool:
737
+ """Return True when the caller holds an active membership on ``project_id``.
738
+
739
+ Gates the catalog list's project-scoped query parameters (#3571). The resource
740
+ catalog is readable by any authenticated user (ADR-0034), so a parameter that
741
+ reaches *through* that open read into one project's data — its roster, its
742
+ tasks' skill requirements — has to carry its own membership check; the
743
+ endpoint's permission class cannot supply one, because the endpoint is not
744
+ project-scoped.
745
+
746
+ A malformed id is deliberately *not* pre-validated here: letting it reach the
747
+ UUID column keeps the install-wide malformed-uuid contract
748
+ (``core.exception_handlers`` maps it to 400 for a query param), rather than
749
+ quietly downgrading a typo to an ignored parameter.
750
+ """
751
+ return _membership_role(request, project_id) is not None
752
+
753
+
754
+ def _caller_may_read_task(request: Request, task_id: Any) -> bool:
755
+ """Return True when the caller is a member of the project owning ``task_id``.
756
+
757
+ The ``?task=`` skill-fit annotation echoes a task's full requirement set back
758
+ through the open catalog read, so those rows need the same project scoping
759
+ :meth:`TaskSkillRequirementViewSet.get_queryset` already applies to them
760
+ (#3571). An unknown task id and a foreign one are equally un-annotated, so the
761
+ parameter cannot be used to confirm that a task id exists. A malformed id is
762
+ left to the install-wide malformed-uuid contract (400), as above.
763
+ """
764
+ project_id = Task.objects.filter(pk=task_id).values_list("project_id", flat=True).first()
765
+ if project_id is None:
766
+ return False
767
+ return _membership_role(request, project_id) is not None
768
+
769
+
770
+ class ResourceCatalogThrottle(UserRateThrottle):
771
+ """Per-user rate limit on the org-wide resource catalog (#891).
772
+
773
+ Mirrors the ``user_search`` throttle added for UserSearchView in #815: the
774
+ catalog is readable by any authenticated user, so even with email stripped a
775
+ single account could still page through it to enumerate the workforce. A
776
+ per-user 60/min cap bounds bulk scraping while staying well above any
777
+ interactive picker (AddToRosterCombobox) usage. The rate is set inline so no
778
+ settings entry is required.
779
+ """
780
+
781
+ scope = "resource_catalog"
782
+ rate = "60/min"
783
+
784
+
785
+ def _compute_skill_fit(
786
+ resource: Resource, requirements: list[TaskSkillRequirement]
787
+ ) -> tuple[str, list[dict[str, object]]]:
788
+ """Return (skill_fit, missing_skills) for a resource against task requirements.
789
+
790
+ skill_fit is 'exact' | 'partial' | 'missing'.
791
+ missing_skills is a list of dicts with skill_id, skill_name, required, actual.
792
+ """
793
+ if not requirements:
794
+ return "exact", []
795
+
796
+ resource_skills: dict[str, int] = {
797
+ str(rs.skill_id): rs.proficiency for rs in resource.skills.all()
798
+ }
799
+
800
+ matched = 0
801
+ missing = []
802
+ for req in requirements:
803
+ sid = str(req.skill_id)
804
+ actual = resource_skills.get(sid, 0)
805
+ if actual >= req.min_proficiency:
806
+ matched += 1
807
+ else:
808
+ missing.append(
809
+ {
810
+ "skill_id": sid,
811
+ "skill_name": req.skill.name,
812
+ "required": req.min_proficiency,
813
+ "required_label": req.get_min_proficiency_display(),
814
+ "actual": actual,
815
+ "actual_label": Proficiency(actual).label if actual else "not tagged",
816
+ }
817
+ )
818
+
819
+ if not missing:
820
+ return "exact", []
821
+ if matched > 0:
822
+ return "partial", missing
823
+ return "missing", missing
824
+
825
+
826
+ # Default fractional allocation assumed for a bare-assignee task with no
827
+ # TaskResource row (see the fallback in _check_overallocation below). Mirrors
828
+ # TaskResource.units' own model default — "assigned" without a tracked
829
+ # fraction is treated as full-time, the same assumption Task.assignee already
830
+ # encodes everywhere else it is read as a "who owns this" signal.
831
+ _BARE_ASSIGNEE_DEFAULT_UNITS = Decimal("1.0")
832
+
833
+
834
+ def _check_overallocation(resource: Resource, project_id: str) -> list[dict[str, str]]:
835
+ """Return a warnings list if the resource is overallocated on active tasks.
836
+
837
+ Overallocation is the **peak units the resource holds on any single working
838
+ day** across non-COMPLETE, committed tasks in the project, compared against the
839
+ resource's capacity **on this project** — the roster's ``units_override`` when
840
+ one is set, else ``resource.max_units`` (#3574). Comparing against the raw
841
+ default told a half-time person they were fine at 80% while the heat map one
842
+ click away read 160%. If the peak exceeds capacity a single warning entry is
843
+ returned so the caller can include it in the 201 response without blocking the
844
+ save (ADR-0028 — soft warning, not a hard error).
845
+
846
+ This was previously a project-lifetime ``Sum(units)`` with no date window at
847
+ all, so three 0.8-unit tasks that never share a calendar day reported as 240%
848
+ allocated — 18 of 41 real (resource, project) pairs on the seeded workspace
849
+ produced a warning with no calendar-day conflict anywhere (#3534). Every
850
+ sibling read — the heat map (``projects.utilization``), the board badge, the
851
+ weekly digest — already windows by day, so the write-time warning was the one
852
+ place in the product that did not ask whether the work overlaps. It now shares
853
+ the engine's own calendar resolution and ``peak_concurrent_units``, which means
854
+ "resource calendar wins" and non-working days are not conflicts here either.
855
+
856
+ A task whose only assignment signal is a bare ``Task.assignee`` (no
857
+ TaskResource row) previously contributed **zero** load here, silently
858
+ understating this resource's real allocation (#3047 — the read-side half
859
+ of the #2718/#2900 write/seed fixes). When ``resource.user`` links the
860
+ Resource to the User account ``Task.assignee`` points at, those tasks are
861
+ now folded in at ``_BARE_ASSIGNEE_DEFAULT_UNITS`` over their own span and
862
+ flagged with a separate ``assignment_not_unit_tracked`` warning, so the caller
863
+ knows the peak includes an estimate rather than a real ``TaskResource.units``
864
+ figure. Resources with no linked user account (teams, equipment, or legacy
865
+ rows predating the FK) cannot be correlated to ``Task.assignee`` and are
866
+ unaffected — same as before this fix.
867
+
868
+ Args:
869
+ resource: The Resource being assigned.
870
+ project_id: The project UUID to scope the utilisation peak.
871
+
872
+ Returns:
873
+ A list of warning dicts (overallocation and/or unit-tracking caveat),
874
+ or an empty list.
875
+ """
876
+ # Capacity check counts only committed delivery — BACKLOG and COMPLETE are
877
+ # excluded. BACKLOG via Task.committed (ADR-0057), COMPLETE via the
878
+ # historical exclude (units are no longer demanding capacity).
879
+ committed_tasks = Task.committed.filter(project_id=project_id).exclude(status="COMPLETE")
880
+
881
+ # Span, not remaining-work window: Coalesce(scheduled_start, early_start)
882
+ # .. early_finish, identical to the utilization engine (ADR-0752 / #2623).
883
+ # A task the CPM has never dated comes back as (None, None) and is folded in
884
+ # by peak_concurrent_units as an every-day baseline rather than dropped.
885
+ assignment_rows = list(
886
+ TaskResource.objects.filter(
887
+ resource=resource,
888
+ task_id__in=committed_tasks.values_list("pk", flat=True),
889
+ )
890
+ .annotate(
891
+ _span_start=Coalesce(
892
+ "task__scheduled_start", "task__early_start", output_field=DateField()
893
+ )
894
+ )
895
+ .values_list("task_id", "units", "_span_start", "task__early_finish")
896
+ )
897
+ allocations = [
898
+ Allocation(units=units, start=span_start, end=span_end)
899
+ for _task_id, units, span_start, span_end in assignment_rows
900
+ ]
901
+
902
+ warnings: list[dict[str, str]] = []
903
+
904
+ # Bare-assignee fallback: only resources linked to a user account can be
905
+ # correlated to Task.assignee at all.
906
+ bare_assignee_rows: list[tuple[object, object, object]] = []
907
+ if resource.user_id is not None:
908
+ unit_tracked_task_ids = {row[0] for row in assignment_rows}
909
+ bare_assignee_rows = list(
910
+ committed_tasks.filter(assignee_id=resource.user_id)
911
+ .exclude(pk__in=unit_tracked_task_ids)
912
+ .annotate(
913
+ _span_start=Coalesce("scheduled_start", "early_start", output_field=DateField())
914
+ )
915
+ .values_list("pk", "_span_start", "early_finish")
916
+ )
917
+
918
+ if bare_assignee_rows:
919
+ allocations.extend(
920
+ Allocation(
921
+ units=_BARE_ASSIGNEE_DEFAULT_UNITS,
922
+ start=span_start, # type: ignore[arg-type]
923
+ end=span_end, # type: ignore[arg-type]
924
+ )
925
+ for _pk, span_start, span_end in bare_assignee_rows
926
+ )
927
+ warnings.append(
928
+ {
929
+ "code": "assignment_not_unit_tracked",
930
+ "resource_id": str(resource.pk),
931
+ "resource_name": resource.name,
932
+ "detail": (
933
+ f"{resource.name} is assigned to {len(bare_assignee_rows)} "
934
+ "task(s) with no tracked allocation units; the capacity "
935
+ "figures below assume full-time allocation for those tasks."
936
+ ),
937
+ "task_ids": ",".join(str(pk) for pk, _s, _e in bare_assignee_rows),
938
+ }
939
+ )
940
+
941
+ project = (
942
+ Project.objects.select_related("calendar")
943
+ .prefetch_related("calendar__exceptions")
944
+ .filter(pk=project_id)
945
+ .first()
946
+ )
947
+ mask, exception_ranges = resolve_working_calendar(resource, project)
948
+ peak, peak_day = peak_concurrent_units(allocations, mask, exception_ranges)
949
+
950
+ capacity = resource_effective_units(project_id, resource)
951
+
952
+ if peak > capacity:
953
+ # Name the day when there is one. A peak carried entirely by undated
954
+ # tasks has no day to point at, only a floor that applies to every day.
955
+ when = f"on {peak_day.isoformat()}" if peak_day is not None else "on their busiest day"
956
+ warnings.append(
957
+ {
958
+ "code": "resource_overallocated",
959
+ "resource_id": str(resource.pk),
960
+ "resource_name": resource.name,
961
+ "detail": (
962
+ f"{resource.name} is allocated {peak:.0%} {when} (capacity: {capacity:.0%})."
963
+ ),
964
+ }
965
+ )
966
+ return warnings
967
+
968
+
969
+ @extend_schema_view(
970
+ list=extend_schema(
971
+ parameters=[
972
+ OpenApiParameter(
973
+ name="exclude_project",
974
+ type=OpenApiTypes.UUID,
975
+ location=OpenApiParameter.QUERY,
976
+ required=False,
977
+ description=(
978
+ "Exclude resources already in this project's roster. Only "
979
+ "honoured for members of that project; ignored otherwise."
980
+ ),
981
+ ),
982
+ OpenApiParameter(
983
+ name="task",
984
+ type=OpenApiTypes.UUID,
985
+ location=OpenApiParameter.QUERY,
986
+ required=False,
987
+ description=(
988
+ "Annotate each resource with skill_fit (exact/partial/missing) "
989
+ "against this task's skill requirements and group results "
990
+ "accordingly. Only honoured for members of the task's project; "
991
+ "ignored otherwise."
992
+ ),
993
+ ),
994
+ OpenApiParameter(
995
+ name="include_deleted",
996
+ type=OpenApiTypes.BOOL,
997
+ location=OpenApiParameter.QUERY,
998
+ required=False,
999
+ description=(
1000
+ "When 'true', include soft-deleted (deactivated) resources. Only "
1001
+ "honoured for callers holding workspace Admin or above; silently ignored "
1002
+ "for everyone else."
1003
+ ),
1004
+ ),
1005
+ ],
1006
+ ),
1007
+ )
1008
+ class ResourceViewSet(IdempotencyMixin, viewsets.ModelViewSet[Resource]):
1009
+ """CRUD for the org-level resource catalog (issue #155).
1010
+
1011
+ Permission model (ADR-0034):
1012
+ Read (GET/HEAD/OPTIONS): any authenticated user — supports self-view
1013
+ for team members and the AddToRosterCombobox picker.
1014
+ Write (POST/PATCH/PUT): IsOrgAdmin — any user with PM (ADMIN) or Owner
1015
+ role on at least one *active* project (#3569). ``email`` is an exception:
1016
+ ``ResourceSerializer.validate`` rejects it below the stored workspace ADMIN
1017
+ role (#3625) — this view-level gate alone was self-grantable and left
1018
+ writing the field wide open even after #3569 raised reading it.
1019
+ DELETE, ``restore``, ``assignments``, and ``?include_deleted=true``:
1020
+ IsWorkspaceAdminStrict (stored workspace ADMIN role). Raised in #3569 —
1021
+ these reach across every project in the install, and the org-admin
1022
+ derivation they used to sit behind is self-grantable by creating a
1023
+ throwaway project.
1024
+
1025
+ DELETE is a soft-delete ("deactivate"): it sets is_deleted=True, soft-deletes
1026
+ the resource's live ProjectResource roster row in every project, and enqueues a
1027
+ schedule recalculation for every project that has open TaskResource rows for the
1028
+ deactivated resource. TaskResource assignment rows are deliberately retained so
1029
+ assignment history survives an off-boarding; every roster, capacity, and skill
1030
+ read filters the deactivated resource out instead. The resource record is never
1031
+ hard-deleted, and POST /resources/{id}/restore/ reverses both halves — including
1032
+ the roster rows, but not a membership that was already removed by hand.
1033
+
1034
+ Query params:
1035
+ ?search= — filter by name/email (DRF SearchFilter); email is
1036
+ searchable only for org admins (#892)
1037
+ ?exclude_project= — exclude resources already in a project's roster;
1038
+ only honoured for members of that project (#3571)
1039
+ ?task= — annotate with skill_fit against the task's skill
1040
+ requirements; groups results into exact/partial/missing.
1041
+ Only honoured for members of the task's project (#3571)
1042
+ ?include_deleted=true — include soft-deleted (deactivated) resources;
1043
+ only honoured for workspace Admin or above
1044
+ ?ordering= — order by name (DRF OrderingFilter)
1045
+
1046
+ Every parameter that names a project- or task-scoped id is gated on the
1047
+ caller's membership of that project. The catalog read itself is open, so a
1048
+ parameter is the only place a project boundary can be crossed here; an
1049
+ unauthorized id is treated as absent rather than refused, so no parameter
1050
+ doubles as an existence oracle.
1051
+ """
1052
+
1053
+ queryset = (
1054
+ Resource.objects.select_related("calendar")
1055
+ .prefetch_related("skills__skill")
1056
+ .order_by("name")
1057
+ )
1058
+ serializer_class = ResourceSerializer
1059
+ # Email search is gated on the stored workspace ADMIN role via the custom backend
1060
+ # (#892, raised from org-admin in #3569): everyone else searches by name only, so
1061
+ # they cannot probe email existence with ?search=.
1062
+ filter_backends = [_WorkspaceAdminEmailSearchFilter, filters.OrderingFilter]
1063
+ search_fields = ["name", "email"] # workspace admins; backend narrows to ["name"]
1064
+ ordering_fields = ["name"]
1065
+ # Per-user cap on the harvest-prone read path (#891, mirrors #815).
1066
+ throttle_classes = [ResourceCatalogThrottle]
1067
+
1068
+ #: Actions that reach past the catalog's own row data — into other projects'
1069
+ #: task names, or into the deactivated pool — and therefore take the **stored**
1070
+ #: workspace ADMIN role rather than the self-grantable org-admin derivation
1071
+ #: (#3569).
1072
+ #:
1073
+ #: * ``assignments`` — task and project names for one person across every
1074
+ #: project in the install (ADR-0499). Exfiltration.
1075
+ #: * ``destroy`` — soft-deletes a shared resource and fans a CPM recalc plus a
1076
+ #: ``roster_changed`` broadcast to every project holding an assignment,
1077
+ #: including projects the caller cannot see. Destruction.
1078
+ #: * ``restore`` — the inverse of ``destroy``, kept on the same floor so the
1079
+ #: deactivation lifecycle has one principal. Splitting it would leave an
1080
+ #: admin able to reactivate rows they can neither list
1081
+ #: (``?include_deleted=true`` is on the same floor) nor deactivate.
1082
+ _WORKSPACE_ADMIN_ACTIONS: frozenset[str] = frozenset({"assignments", "destroy", "restore"})
1083
+
1084
+ def get_permissions(self) -> list[BasePermission]:
1085
+ """Split read vs write permissions.
1086
+
1087
+ Safe HTTP methods open to any authenticated user; ordinary catalog writes
1088
+ (create, update) restricted to org admins (PM or Owner role on any *active*
1089
+ project). The deactivation lifecycle and the cross-project ``assignments``
1090
+ view require workspace ADMIN — see :attr:`_WORKSPACE_ADMIN_ACTIONS`.
1091
+
1092
+ ``IsWorkspaceAdminStrict`` rather than ``IsWorkspaceOperator``: the defect in
1093
+ #3569 is that org authority was read out of a *self-grantable* project role,
1094
+ and the fix is a **stored** principal, not necessarily the install superuser.
1095
+ ``WorkspaceMembership`` is granted only by an existing workspace admin or by
1096
+ SSO provisioning — creating a project grants none — so ADMIN is unreachable
1097
+ by the exploit path while staying an in-app role a workspace owner can hand
1098
+ out. Superusers keep access through ``workspace_role_for_user``'s implicit
1099
+ OWNER bootstrap. ``IsWorkspaceAdminStrict`` (#1724) gates ADMIN on reads as
1100
+ well as writes, which is what ``assignments`` needs.
1101
+ """
1102
+ # `assignments` is a GET that must NOT inherit the base catalog read's open
1103
+ # IsAuthenticated gate: it carries task/project names across project
1104
+ # boundaries, so an open gate is a cross-project IDOR. It sits in the
1105
+ # workspace-admin set rather than being special-cased here.
1106
+ if getattr(self, "action", None) in self._WORKSPACE_ADMIN_ACTIONS:
1107
+ return [IsAuthenticated(), IsWorkspaceAdminStrict()]
1108
+ if self.request.method in ("GET", "HEAD", "OPTIONS"):
1109
+ return [IsAuthenticated()]
1110
+ return [IsAuthenticated(), IsOrgAdmin()]
1111
+
1112
+ def get_queryset(self) -> QuerySet[Resource]:
1113
+ qs = (
1114
+ Resource.objects.select_related("calendar")
1115
+ .prefetch_related("skills__skill")
1116
+ .order_by("name")
1117
+ )
1118
+
1119
+ # Deactivated resources are hidden by default. A workspace admin may opt in
1120
+ # via ?include_deleted=true to manage the deactivated pool. The param is
1121
+ # honored only at that floor (#1374, raised from org-admin in #3569):
1122
+ # anyone else passing it is silently ignored so soft-deleted resource
1123
+ # records stay hidden — defense-in-depth for the deactivated-pool contract
1124
+ # the docstring already claimed, and it keeps the pool's three verbs
1125
+ # (list/delete/restore) on one principal.
1126
+ include_deleted = self.request.query_params.get(
1127
+ "include_deleted", ""
1128
+ ).lower() == "true" and _request_is_workspace_admin(self.request)
1129
+ if not include_deleted:
1130
+ qs = qs.filter(is_deleted=False)
1131
+
1132
+ # ?exclude_project= reaches through the open catalog read into one
1133
+ # project's roster: diffing the filtered list against the bare one names
1134
+ # every resource on that roster. Honour it only for members of that
1135
+ # project (#3571). A non-member's parameter is ignored rather than
1136
+ # refused, which is exactly the response they get by omitting it, so the
1137
+ # parameter confirms nothing about the project id either — the same
1138
+ # treatment ?include_deleted= gets for non-admins above.
1139
+ exclude_project = self.request.query_params.get("exclude_project")
1140
+ if exclude_project and _caller_is_project_member(self.request, exclude_project):
1141
+ already_in = ProjectResource.objects.filter(
1142
+ project_id=exclude_project, is_deleted=False
1143
+ ).values_list("resource_id", flat=True)
1144
+ qs = qs.exclude(pk__in=already_in)
1145
+
1146
+ return qs
1147
+
1148
+ def perform_destroy(self, instance: Resource) -> None:
1149
+ """Soft-delete: hide from the catalog, drop off every roster, recalc schedules.
1150
+
1151
+ Deactivation is **catalog-only on the assignment rows** (#3572). Hard delete is
1152
+ intentionally unavailable from this endpoint, and the ``TaskResource`` rows are
1153
+ deliberately left in place: historical task assignments and capacity data
1154
+ reference this resource and must remain intact for audit trails — an
1155
+ off-boarding is precisely the moment that record matters most.
1156
+
1157
+ What deactivation *does* end is the person's presence in the team:
1158
+
1159
+ 1. Every live ``ProjectResource`` roster row is soft-deleted and stamped
1160
+ ``deactivated_with_resource`` so :meth:`restore` can put back exactly these
1161
+ and not a membership someone ended by hand.
1162
+ 2. Every capacity, roster, and skill read filters the resource out through
1163
+ ``ResourceScopedManager.active()`` — the retained assignment rows stop
1164
+ contributing load and stop contributing capacity to the denominator.
1165
+
1166
+ The CPM recalculation fan-out below stays coherent under (2): it is not
1167
+ undoing the assignments (they still hold their tasks and their units), it is
1168
+ re-running the schedule for projects whose *reported* team just changed, so the
1169
+ heat map, the allocation timeline, and the Overview utilization card agree with
1170
+ the roster on the very next read rather than on the next unrelated write.
1171
+ """
1172
+ # Wrap the soft-delete save, the roster cascade, and the per-project
1173
+ # recalculation fan-out in a single atomic block so a crash partway through
1174
+ # cannot leave the resource deactivated without the roster cascade or the CPM
1175
+ # recalcs (R3). The _enqueue_recalculate calls use the transactional outbox
1176
+ # pattern (ADR-0027), so they are durable against broker failures.
1177
+ with transaction.atomic():
1178
+ instance.is_deleted = True
1179
+ instance.server_version = (instance.server_version or 0) + 1
1180
+ instance.deleted_version = instance.server_version
1181
+ instance.save(update_fields=["is_deleted", "server_version", "deleted_version"])
1182
+
1183
+ # Roster cascade. Only rows that are live *right now* are stamped, so any
1184
+ # roster row soft-deleted by some other path keeps
1185
+ # deactivated_with_resource=False and restore leaves it alone — see the
1186
+ # field's own comment for why that matters. Bulk ``update()`` rather than per-row
1187
+ # ``soft_delete()``: ProjectResource is outside the sync union (nothing
1188
+ # reads its sync_seq), so there is no tombstone to publish and no reason
1189
+ # to spend a query per roster row on an off-boarding.
1190
+ #
1191
+ # The F() version bump replicates what VersionedModel.soft_delete would
1192
+ # have recorded, following cascade_project_children_soft_delete's
1193
+ # precedent: within one UPDATE every F() reads the pre-update column, so
1194
+ # deleted_version lands equal to the new server_version. It is not
1195
+ # decorative — server_version is the X-Base-Version optimistic-lock token
1196
+ # ProjectResourceSerializer publishes, so skipping it would let a client
1197
+ # holding a pre-deactivation copy pass the lock check on a row that had
1198
+ # since been deactivated and restored.
1199
+ #
1200
+ # Deliberately NOT excluding archived projects: deactivation is an
1201
+ # org-wide off-boarding and must not be left partially applied because
1202
+ # one project happens to be archived. The roster row of an archived
1203
+ # project is a historical record either way, and restore's symmetric
1204
+ # filter keeps the two halves reversible.
1205
+ cascade_rows = ProjectResource.objects.filter(resource_id=instance.pk, is_deleted=False)
1206
+ # Snapshot the project ids before the UPDATE clears the predicate that
1207
+ # selects them, so the broadcast set is exactly the rows this call
1208
+ # cascaded — not every row a previous, never-restored deactivation left
1209
+ # stamped.
1210
+ cascaded_project_ids = list(cascade_rows.values_list("project_id", flat=True))
1211
+ cascade_rows.update(
1212
+ is_deleted=True,
1213
+ deactivated_with_resource=True,
1214
+ server_version=models.F("server_version") + 1,
1215
+ deleted_version=models.F("server_version") + 1,
1216
+ )
1217
+
1218
+ # Fan out a schedule recalculation to every project with open
1219
+ # task assignments for this resource. Uses the transactional outbox
1220
+ # pattern (ADR-0027) so a broker-down event doesn't lose the request.
1221
+ affected_project_ids = list(
1222
+ TaskResource.objects.filter(resource_id=instance.pk)
1223
+ .values_list("task__project_id", flat=True)
1224
+ .distinct()
1225
+ )
1226
+ for project_id in affected_project_ids:
1227
+ _enqueue_recalculate(str(project_id))
1228
+
1229
+ # The roster cascade above reaches projects the assignment fan-out does not:
1230
+ # a resource can sit on a roster carrying no tasks at all, which is exactly
1231
+ # the person an off-boarding is most likely to leave behind. So the broadcast
1232
+ # set is the union of both, not just the projects that carried assignments.
1233
+ #
1234
+ # Fan a roster_changed broadcast out to every affected project so peers
1235
+ # viewing the roster see the deactivation live, not on the next poll
1236
+ # (#1359). Deferred to commit and snapshotted to plain strings; mirrors
1237
+ # the per-project recalc fan-out above.
1238
+ resource_id = str(instance.pk)
1239
+ broadcast_project_ids = sorted(
1240
+ {str(p) for p in affected_project_ids} | {str(p) for p in cascaded_project_ids}
1241
+ )
1242
+
1243
+ def _on_commit() -> None:
1244
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
1245
+
1246
+ for project_id in broadcast_project_ids:
1247
+ broadcast_board_event(
1248
+ project_id,
1249
+ "roster_changed",
1250
+ {"resource_id": resource_id},
1251
+ )
1252
+
1253
+ transaction.on_commit(_on_commit)
1254
+
1255
+ # Reactivation is carried by the URL alone — the body is never read. Without
1256
+ # ``request=None`` the schema fell back to serializer_class and published a
1257
+ # *required* ResourceRequest body (the full write shape) on this no-body
1258
+ # endpoint, so a generated client demanded a whole resource payload to
1259
+ # un-deactivate one (#2840). Sibling restore actions on Task/Project already
1260
+ # publish no body; this one was the outlier.
1261
+ @extend_schema(
1262
+ summary="Restore a deactivated resource",
1263
+ request=None,
1264
+ responses={
1265
+ 200: ResourceSerializer,
1266
+ 400: OpenApiResponse(description="Resource is not deactivated."),
1267
+ 404: OpenApiResponse(description="Resource not found."),
1268
+ },
1269
+ )
1270
+ @action(detail=True, methods=["post"], url_path="restore")
1271
+ def restore(self, request: Request, pk: str | None = None) -> Response:
1272
+ """Restore a soft-deleted resource back to active status.
1273
+
1274
+ Requires IsWorkspaceAdminStrict (checked in get_permissions since this is a
1275
+ write action; raised from IsOrgAdmin in #3569 so the whole deactivation
1276
+ lifecycle sits on one principal). Fetches from the unfiltered queryset so
1277
+ soft-deleted records are reachable; the standard get_object() path
1278
+ excludes them.
1279
+
1280
+ Reverses **both** halves of :meth:`perform_destroy` (#3572). The catalog flag
1281
+ alone is not enough: deactivation also soft-deleted the resource's roster
1282
+ rows, and a one-way cascade would leave a reactivated person visible in the
1283
+ catalog but silently absent from every team they were on — a second bug in
1284
+ the shape of the first.
1285
+
1286
+ Only rows stamped ``deactivated_with_resource`` come back — restore states
1287
+ what it reverses rather than inferring it from ``is_deleted``. Roster removal
1288
+ through the API is a hard delete, so the cascade is currently the only
1289
+ product path that leaves a soft-deleted roster row; the stamp is what keeps
1290
+ that an assertion rather than an assumption, so a row soft-deleted by an
1291
+ import, a management command, or a data repair is never silently adopted
1292
+ into somebody's reactivation. See ``ProjectResource.deactivated_with_resource``.
1293
+ """
1294
+ if pk is None:
1295
+ return Response({"detail": _NOT_FOUND_DETAIL}, status=status.HTTP_404_NOT_FOUND)
1296
+ try:
1297
+ resource = Resource.objects.get(pk=pk)
1298
+ except Resource.DoesNotExist:
1299
+ return Response({"detail": _NOT_FOUND_DETAIL}, status=status.HTTP_404_NOT_FOUND)
1300
+ if not resource.is_deleted:
1301
+ return Response(
1302
+ {"detail": "Resource is not deactivated."},
1303
+ status=status.HTTP_400_BAD_REQUEST,
1304
+ )
1305
+
1306
+ # Atomic so the catalog flag and the roster rows cannot disagree: a crash
1307
+ # between them would leave the resource selectable but off every roster,
1308
+ # which is the exact asymmetry this action exists to prevent.
1309
+ with transaction.atomic():
1310
+ resource.is_deleted = False
1311
+ resource.deleted_version = None
1312
+ resource.server_version = (resource.server_version or 0) + 1
1313
+ resource.save(update_fields=["is_deleted", "deleted_version", "server_version"])
1314
+
1315
+ # Read the project ids before the update clears the stamp.
1316
+ restored_project_ids = list(
1317
+ ProjectResource.objects.filter(
1318
+ resource_id=resource.pk, deactivated_with_resource=True
1319
+ ).values_list("project_id", flat=True)
1320
+ )
1321
+ # Symmetric to the cascade: same F() version bump, so a client holding
1322
+ # a pre-deactivation copy of a restored roster row cannot pass the
1323
+ # X-Base-Version optimistic-lock check on it.
1324
+ ProjectResource.objects.filter(
1325
+ resource_id=resource.pk, deactivated_with_resource=True
1326
+ ).update(
1327
+ is_deleted=False,
1328
+ deleted_version=None,
1329
+ deactivated_with_resource=False,
1330
+ server_version=models.F("server_version") + 1,
1331
+ )
1332
+
1333
+ # Reactivation puts the resource back on every roster the deactivation took
1334
+ # it off, plus every project it still has assignments on — broadcast
1335
+ # roster_changed so those projects' clients refetch the roster live (#1359),
1336
+ # mirroring the soft-delete fan-out.
1337
+ affected_project_ids = sorted(
1338
+ {
1339
+ str(p)
1340
+ for p in TaskResource.objects.filter(resource_id=resource.pk)
1341
+ .values_list("task__project_id", flat=True)
1342
+ .distinct()
1343
+ }
1344
+ | {str(p) for p in restored_project_ids}
1345
+ )
1346
+ resource_id = str(resource.pk)
1347
+
1348
+ def _on_commit() -> None:
1349
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
1350
+
1351
+ for project_id in affected_project_ids:
1352
+ broadcast_board_event(
1353
+ project_id,
1354
+ "roster_changed",
1355
+ {"resource_id": resource_id},
1356
+ )
1357
+
1358
+ transaction.on_commit(_on_commit)
1359
+
1360
+ serializer = self.get_serializer(resource)
1361
+ return Response(serializer.data)
1362
+
1363
+ @extend_schema(
1364
+ responses=ResourceAssignmentSerializer(many=True),
1365
+ description=(
1366
+ "Cross-project task assignments for one resource — the org catalog's "
1367
+ "'what is this person working on' view (#2047). Requires the workspace "
1368
+ "Admin role because it carries task/project names across "
1369
+ "project boundaries. "
1370
+ "Soft-deleted tasks are excluded; a deactivated resource still returns "
1371
+ "its assignments. Ordered by project then task."
1372
+ ),
1373
+ )
1374
+ @action(detail=True, methods=["get"], url_path="assignments")
1375
+ def assignments(self, request: Request, pk: str | None = None) -> Response:
1376
+ """Return every task the resource is assigned to, across all projects.
1377
+
1378
+ Gated on ``IsWorkspaceAdminStrict`` in ``get_permissions`` (this GET must not
1379
+ inherit the base catalog read's open gate — see the note there). Unlike
1380
+ ``/task-resources/?resource=`` this is NOT scoped to the caller's member
1381
+ projects: it returns the full cross-project set.
1382
+
1383
+ ADR-0499 gated it on ``IsOrgAdmin`` and reasoned that "the RBAC gate is
1384
+ what makes that safe". It did not — that gate is self-grantable in two
1385
+ requests (#3569), so the complete picture was readable by any account. The
1386
+ stored workspace ADMIN role is not reachable that way. A resource manager who
1387
+ needs their own projects' view uses ``/task-resources/?resource=``, which is
1388
+ membership-scoped.
1389
+
1390
+ The resource is looked up from the unfiltered manager so a deactivated
1391
+ resource's detail panel still resolves (mirrors ``restore``). Soft-deleted
1392
+ tasks are filtered out; completed tasks are included and sectioned client
1393
+ side. ``select_related('task__project')`` keeps this a single query
1394
+ regardless of assignment count (no N+1).
1395
+ """
1396
+ if pk is None or not Resource.objects.filter(pk=pk).exists():
1397
+ return Response({"detail": _NOT_FOUND_DETAIL}, status=status.HTTP_404_NOT_FOUND)
1398
+
1399
+ assignments_qs = (
1400
+ TaskResource.objects.filter(resource_id=pk, task__is_deleted=False)
1401
+ .select_related("task__project")
1402
+ .order_by("task__project__name", "task__name")
1403
+ )
1404
+
1405
+ # Use the paginator directly rather than self.paginate_queryset(): the
1406
+ # latter is typed to the viewset's Resource model, but this action returns
1407
+ # TaskResource rows. The set is intrinsically bounded (one person's
1408
+ # assignments) — pagination is a belt-and-suspenders guard.
1409
+ paginator = self.paginator
1410
+ if paginator is not None:
1411
+ page = paginator.paginate_queryset(assignments_qs, request, view=self)
1412
+ if page is not None:
1413
+ serializer = ResourceAssignmentSerializer(page, many=True)
1414
+ return paginator.get_paginated_response(serializer.data)
1415
+ serializer = ResourceAssignmentSerializer(assignments_qs, many=True)
1416
+ return Response(serializer.data)
1417
+
1418
+ def list(self, request: Request, *args: object, **kwargs: object) -> Response:
1419
+ """List resources, optionally annotated with skill_fit for a task."""
1420
+ task_id = request.query_params.get("task")
1421
+ requirements: list[TaskSkillRequirement] = []
1422
+ # missing_skills[] echoes skill_name/required/required_label for every
1423
+ # requirement on the task, so an unscoped ?task= published a foreign
1424
+ # project's requirement set through a read any authenticated user may
1425
+ # make. Annotate only for members of the task's project (#3571) — the
1426
+ # same scoping TaskSkillRequirementViewSet.get_queryset applies to these
1427
+ # rows. A non-member gets the plain, un-annotated catalog.
1428
+ if task_id and _caller_may_read_task(request, task_id):
1429
+ requirements = list(
1430
+ TaskSkillRequirement.objects.filter(
1431
+ task_id=task_id, is_deleted=False
1432
+ ).select_related("skill")
1433
+ )
1434
+
1435
+ queryset = self.filter_queryset(self.get_queryset())
1436
+ page = self.paginate_queryset(queryset)
1437
+ resources = page if page is not None else queryset
1438
+
1439
+ serializer = self.get_serializer(resources, many=True)
1440
+ data = serializer.data
1441
+
1442
+ if requirements:
1443
+ resource_map = {str(r.pk): r for r in resources}
1444
+ fit_order = {"exact": 0, "partial": 1, "missing": 2}
1445
+ annotated = []
1446
+ for item in data:
1447
+ resource = resource_map.get(item["id"])
1448
+ if resource is not None:
1449
+ fit, missing = _compute_skill_fit(resource, requirements)
1450
+ item = dict(item)
1451
+ item["skill_fit"] = fit
1452
+ item["missing_skills"] = missing
1453
+ annotated.append(item)
1454
+ annotated.sort(key=lambda x: fit_order.get(x.get("skill_fit", "missing"), 2))
1455
+ data = annotated
1456
+
1457
+ if page is not None:
1458
+ return self.get_paginated_response(data)
1459
+ return Response(data)
1460
+
1461
+
1462
+ # ---------------------------------------------------------------------------
1463
+ # Task-resource assignments (extended with skill_mismatch warning)
1464
+ # ---------------------------------------------------------------------------
1465
+
1466
+
1467
+ @extend_schema_view(
1468
+ list=extend_schema(
1469
+ parameters=[
1470
+ OpenApiParameter(
1471
+ name="task",
1472
+ type=OpenApiTypes.UUID,
1473
+ location=OpenApiParameter.QUERY,
1474
+ required=False,
1475
+ description="Filter to assignments for this task.",
1476
+ ),
1477
+ OpenApiParameter(
1478
+ name="resource",
1479
+ type=OpenApiTypes.UUID,
1480
+ location=OpenApiParameter.QUERY,
1481
+ required=False,
1482
+ description="Filter to assignments for this resource.",
1483
+ ),
1484
+ ],
1485
+ ),
1486
+ create=extend_schema(
1487
+ responses={
1488
+ 201: TaskResourceSerializer,
1489
+ 403: OpenApiResponse(
1490
+ description=(
1491
+ "Caller lacks the Resource Manager role on the target project, or that "
1492
+ "project is archived (#3414). The project is named only in the request "
1493
+ "body here, so the refusal comes from the view rather than a permission "
1494
+ "class — the status and body are the same either way."
1495
+ )
1496
+ ),
1497
+ },
1498
+ ),
1499
+ )
1500
+ class TaskResourceViewSet(ProjectScopedViewSet, viewsets.ModelViewSet[TaskResource]):
1501
+ """CRUD for task-resource assignments.
1502
+
1503
+ Permission model:
1504
+ - Read (GET/HEAD/OPTIONS): any project member (Viewer+) via IsProjectMember.
1505
+ - Write (POST/PATCH/DELETE): Resource Manager (2) or above via CanAssignResource.
1506
+ The create path additionally checks role in perform_create because has_object_permission
1507
+ is not called before the object exists.
1508
+
1509
+ IDOR protection:
1510
+ ProjectScopedViewSet does not recognise the task→project FK path on TaskResource,
1511
+ so get_queryset explicitly scopes to the user's member projects rather than relying
1512
+ on the mixin fallthrough.
1513
+ """
1514
+
1515
+ permission_classes = [IsAuthenticated, IsProjectMember, CanAssignResource, IsProjectNotArchived]
1516
+ resolves_scope_in_body = {
1517
+ "create": (
1518
+ "Flat route: the project is reached only through the body's `task`, so "
1519
+ "`CanAssignResource.has_permission` cannot scope the write and "
1520
+ "`has_object_permission` does not run on a create. `perform_create` "
1521
+ "resolves `task.project_id` and applies the Scheduler+ floor there (#3767)."
1522
+ )
1523
+ }
1524
+ serializer_class = TaskResourceSerializer
1525
+ filter_backends = [filters.OrderingFilter]
1526
+ queryset = TaskResource.objects.select_related("task__project", "resource")
1527
+
1528
+ def get_queryset(self) -> QuerySet[TaskResource]:
1529
+ # IsAuthenticated guarantees pk is set; assert narrows the type for mypy.
1530
+ user_pk = self.request.user.pk
1531
+ assert user_pk is not None
1532
+ member_project_ids = ProjectMembership.objects.filter(
1533
+ user_id=user_pk,
1534
+ is_deleted=False,
1535
+ ).values_list("project_id", flat=True)
1536
+ # select_related("task__project") avoids N+1 queries in perform_create
1537
+ # and perform_update, both of which call ensure_project_resource(obj.task.project, ...)
1538
+ # and therefore load the full Project object (R2).
1539
+ #
1540
+ # Deliberately NOT ``.active()`` (#3572), unlike its two siblings in this
1541
+ # file. This is the assignment list, not a capacity read: when somebody is
1542
+ # deactivated their assignment rows are kept precisely so a PM can still see
1543
+ # the orphaned work and reassign it. Hiding them here would make the tasks
1544
+ # look unowned with no way to find out who had them. The rows carry no load
1545
+ # anywhere else — every capacity surface filters them out.
1546
+ qs = (
1547
+ TaskResource.objects.select_related("task__project", "resource")
1548
+ .filter(task__project_id__in=member_project_ids)
1549
+ .order_by("task__project_id", "task_id", "resource__name")
1550
+ )
1551
+ task_id = self.request.query_params.get("task")
1552
+ if task_id:
1553
+ qs = qs.filter(task_id=task_id)
1554
+ resource_id = self.request.query_params.get("resource")
1555
+ if resource_id:
1556
+ qs = qs.filter(resource_id=resource_id)
1557
+ return qs
1558
+
1559
+ def create(self, request: Request, *args: object, **kwargs: object) -> Response:
1560
+ """Create a task-resource assignment and return any warnings.
1561
+
1562
+ Returns overallocation and skill_mismatch warnings in the 201 response.
1563
+ The assignment is always saved regardless of warnings — these are soft
1564
+ alerts, not hard blocks (ADR-0028, ADR-0033).
1565
+ """
1566
+ serializer = self.get_serializer(data=request.data)
1567
+ serializer.is_valid(raise_exception=True)
1568
+ self.perform_create(serializer)
1569
+ headers = self.get_success_headers(serializer.data)
1570
+ obj: TaskResource = serializer.instance # type: ignore[assignment]
1571
+ project_id = str(obj.task.project_id)
1572
+ # Fetch the resource (with skills prefetched) once and reuse it for both
1573
+ # the overallocation check and the skill-fit check, instead of lazy-loading
1574
+ # obj.resource and then re-fetching the same row with prefetch (#821).
1575
+ # select_related/prefetch the resource calendar too: _check_overallocation
1576
+ # resolves the resource's working days (ADR-0031 "resource calendar wins"),
1577
+ # which would otherwise be two lazy queries per POST.
1578
+ resource_with_skills = (
1579
+ Resource.objects.select_related("calendar")
1580
+ .prefetch_related("skills__skill", "calendar__exceptions")
1581
+ .get(pk=obj.resource_id)
1582
+ )
1583
+ warnings: list[dict[str, object]] = [
1584
+ dict(w) for w in _check_overallocation(resource_with_skills, project_id)
1585
+ ]
1586
+
1587
+ # Skill mismatch check — only when the task has requirements.
1588
+ requirements = list(
1589
+ TaskSkillRequirement.objects.filter(
1590
+ task_id=obj.task_id, is_deleted=False
1591
+ ).select_related("skill")
1592
+ )
1593
+ _fit, missing = _compute_skill_fit(resource_with_skills, requirements)
1594
+ if missing:
1595
+ missing_labels = ", ".join(
1596
+ f"{m['skill_name']} ({m['required_label']})" for m in missing[:3]
1597
+ )
1598
+ warnings.append(
1599
+ {
1600
+ "code": "skill_mismatch",
1601
+ "detail": f"Task requires: {missing_labels}.",
1602
+ "missing_skills": missing,
1603
+ }
1604
+ )
1605
+
1606
+ data = dict(serializer.data)
1607
+ data["warnings"] = warnings
1608
+ return Response(data, status=status.HTTP_201_CREATED, headers=headers)
1609
+
1610
+ def perform_create(self, serializer: BaseSerializer[TaskResource]) -> None:
1611
+ """Block assignment creation for summary tasks, then trigger CPM and broadcast.
1612
+
1613
+ Role check: Resource Manager (2) or above is required. has_object_permission is
1614
+ not called for create (no object exists yet), so the role is verified here against
1615
+ the task's project before the row is written.
1616
+
1617
+ Summary tasks roll up from children — direct resource assignments on
1618
+ them create ambiguous scheduling semantics (ADR-0024).
1619
+ """
1620
+ task = serializer.validated_data.get("task")
1621
+ if task:
1622
+ role = _membership_role(self.request, str(task.project_id))
1623
+ if role is None or role < Role.SCHEDULER:
1624
+ raise PermissionDenied(
1625
+ "You need at least Resource Manager role to assign resources."
1626
+ )
1627
+ # Same shape as the role check above, and for the same structural reason
1628
+ # (#3414): the route is top-level, the project is reached only through the
1629
+ # body's ``task``, and ``has_object_permission`` does not run on a create —
1630
+ # so the class-level ``IsProjectNotArchived`` cannot see this write.
1631
+ assert_project_not_archived(task.project_id)
1632
+ if task and task_is_summary(task):
1633
+ raise ValidationError({"task": "Cannot assign resources to a summary task."})
1634
+ obj = serializer.save()
1635
+ project_id = str(obj.task.project_id)
1636
+ task_id = str(obj.task.pk)
1637
+ assignment_id = str(obj.pk)
1638
+
1639
+ # Auto-roster: assigning a resource to a task implicitly adds them to
1640
+ # the project roster so they appear in Team → Roster / Heatmap.
1641
+ ensure_project_resource(obj.task.project, obj.resource)
1642
+
1643
+ # Task-activity audit row (ADR-0394, #1886): written synchronously in the
1644
+ # request transaction so it commits/rolls back with the assignment itself.
1645
+ record_assignment_event(
1646
+ task_id=obj.task_id,
1647
+ event_type=TaskActivityEventType.ASSIGNEE_ADDED,
1648
+ resource=obj.resource,
1649
+ actor=self.request.user,
1650
+ units_to=obj.units,
1651
+ )
1652
+
1653
+ def _on_commit() -> None:
1654
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
1655
+
1656
+ _enqueue_recalculate(project_id)
1657
+ broadcast_board_event(
1658
+ project_id,
1659
+ "assignment_created",
1660
+ {"id": assignment_id, "task_id": task_id},
1661
+ )
1662
+
1663
+ transaction.on_commit(_on_commit)
1664
+
1665
+ def perform_update(self, serializer: BaseSerializer[TaskResource]) -> None:
1666
+ """Save the updated assignment and trigger CPM recalculation and broadcast."""
1667
+ # Capture pre-save state so the audit row can distinguish a resource re-point
1668
+ # (remove old + add new) from an allocation-only change (ADR-0394, #1886).
1669
+ pre = serializer.instance
1670
+ old_resource = pre.resource if pre is not None else None
1671
+ old_units = pre.units if pre is not None else None
1672
+
1673
+ obj = serializer.save()
1674
+ project_id = str(obj.task.project_id)
1675
+ task_id = str(obj.task.pk)
1676
+ assignment_id = str(obj.pk)
1677
+
1678
+ # Re-pointing an assignment to a different resource must roster the new
1679
+ # one — otherwise editing assignee leaves them invisible in Team views (#241).
1680
+ ensure_project_resource(obj.task.project, obj.resource)
1681
+
1682
+ # Task-activity audit (ADR-0394, #1886), synchronous in-transaction:
1683
+ # a resource swap is an unassign+reassign; a units-only edit is a re-allocation.
1684
+ if old_resource is not None and old_resource.pk != obj.resource_id:
1685
+ record_assignment_event(
1686
+ task_id=obj.task_id,
1687
+ event_type=TaskActivityEventType.ASSIGNEE_REMOVED,
1688
+ resource=old_resource,
1689
+ actor=self.request.user,
1690
+ units_to=old_units,
1691
+ )
1692
+ record_assignment_event(
1693
+ task_id=obj.task_id,
1694
+ event_type=TaskActivityEventType.ASSIGNEE_ADDED,
1695
+ resource=obj.resource,
1696
+ actor=self.request.user,
1697
+ units_to=obj.units,
1698
+ )
1699
+ elif old_units != obj.units:
1700
+ record_assignment_event(
1701
+ task_id=obj.task_id,
1702
+ event_type=TaskActivityEventType.ASSIGNEE_UNITS_CHANGED,
1703
+ resource=obj.resource,
1704
+ actor=self.request.user,
1705
+ units_from=old_units,
1706
+ units_to=obj.units,
1707
+ )
1708
+
1709
+ def _on_commit() -> None:
1710
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
1711
+
1712
+ _enqueue_recalculate(project_id)
1713
+ broadcast_board_event(
1714
+ project_id,
1715
+ "assignment_updated",
1716
+ {"id": assignment_id, "task_id": task_id},
1717
+ )
1718
+
1719
+ transaction.on_commit(_on_commit)
1720
+
1721
+ def perform_destroy(self, instance: TaskResource) -> None:
1722
+ """Delete the assignment and trigger CPM recalculation and broadcast."""
1723
+ project_id = str(instance.task.project_id)
1724
+ task_id = str(instance.task.pk)
1725
+ assignment_id = str(instance.pk)
1726
+
1727
+ # Task-activity audit row (ADR-0394, #1886) before the hard delete, while the
1728
+ # resource/units are still readable; the task FK survives (only the assignment
1729
+ # row is removed). Synchronous in-transaction, like the risk-link precedent.
1730
+ record_assignment_event(
1731
+ task_id=instance.task_id,
1732
+ event_type=TaskActivityEventType.ASSIGNEE_REMOVED,
1733
+ resource=instance.resource,
1734
+ actor=self.request.user,
1735
+ units_to=instance.units,
1736
+ )
1737
+ instance.delete()
1738
+
1739
+ def _on_commit() -> None:
1740
+ from trueppm_api.apps.sync.broadcast import broadcast_board_event
1741
+
1742
+ _enqueue_recalculate(project_id)
1743
+ broadcast_board_event(
1744
+ project_id,
1745
+ "assignment_deleted",
1746
+ {"id": assignment_id, "task_id": task_id},
1747
+ )
1748
+
1749
+ transaction.on_commit(_on_commit)