Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(properties): share a personal tag with the team (#5410)

gbirmana3bb0a28d042
diff --git a/.sqlx/query-528bbe4df0e7071e2a0745a92fdbc55cd77553ffb68d2afe6833f653b7d4baab.json b/.sqlx/query-528bbe4df0e7071e2a0745a92fdbc55cd77553ffb68d2afe6833f653b7d4baab.json
new file mode 100644
index 0000000000..a72360cbff
--- /dev/null
+++ b/.sqlx/query-528bbe4df0e7071e2a0745a92fdbc55cd77553ffb68d2afe6833f653b7d4baab.json
@@ -0,0 +1,65 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id,\n property_definition_id,\n display_order,\n number_value,\n string_value,\n color,\n created_at,\n updated_at\n FROM property_options\n WHERE id = $1 AND property_definition_id = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "property_definition_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "display_order",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 3,
+ "name": "number_value",
+ "type_info": "Float8"
+ },
+ {
+ "ordinal": 4,
+ "name": "string_value",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "color",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "528bbe4df0e7071e2a0745a92fdbc55cd77553ffb68d2afe6833f653b7d4baab"
+}
diff --git a/.sqlx/query-58cd7976a97a33c2adf0720fd3f17b6ae46476eaf83e1886db10ee3a799855c9.json b/.sqlx/query-58cd7976a97a33c2adf0720fd3f17b6ae46476eaf83e1886db10ee3a799855c9.json
new file mode 100644
index 0000000000..01375e14c2
--- /dev/null
+++ b/.sqlx/query-58cd7976a97a33c2adf0720fd3f17b6ae46476eaf83e1886db10ee3a799855c9.json
@@ -0,0 +1,105 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT\n source.id,\n source.entity_id,\n source.entity_type,\n $4,\n jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))\n FROM UNNEST($1::uuid[], $2::text[], $3::property_entity_type[])\n AS source(id, entity_id, entity_type)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET\n values = CASE\n WHEN entity_properties.values ->> 'type' = 'SelectOption'\n AND entity_properties.values -> 'value' @> jsonb_build_array($5::text)\n THEN entity_properties.values\n WHEN entity_properties.values ->> 'type' = 'SelectOption'\n THEN jsonb_set(\n entity_properties.values,\n '{value}',\n (entity_properties.values -> 'value') || jsonb_build_array($5::text)\n )\n ELSE jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))\n END,\n updated_at = NOW()\n RETURNING\n id,\n entity_id,\n entity_type as \"entity_type: EntityType\",\n property_definition_id,\n values as \"value: serde_json::Value\",\n created_at,\n updated_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "entity_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "entity_type: EntityType",
+ "type_info": {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK",
+ "CALL_RECORD",
+ "CALENDAR_EVENT"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 3,
+ "name": "property_definition_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "value: serde_json::Value",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "TextArray",
+ {
+ "Custom": {
+ "name": "property_entity_type[]",
+ "kind": {
+ "Array": {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK",
+ "CALL_RECORD",
+ "CALENDAR_EVENT"
+ ]
+ }
+ }
+ }
+ }
+ }
+ },
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "58cd7976a97a33c2adf0720fd3f17b6ae46476eaf83e1886db10ee3a799855c9"
+}
diff --git a/.sqlx/query-6b548846ffa651fd1956a59878840929721945db0225009f27f8b97567efce6a.json b/.sqlx/query-6b548846ffa651fd1956a59878840929721945db0225009f27f8b97567efce6a.json
new file mode 100644
index 0000000000..e1de035b6f
--- /dev/null
+++ b/.sqlx/query-6b548846ffa651fd1956a59878840929721945db0225009f27f8b97567efce6a.json
@@ -0,0 +1,65 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE property_options\n SET property_definition_id = $2,\n display_order = COALESCE(\n (\n SELECT MAX(display_order) + 1\n FROM property_options\n WHERE property_definition_id = $2\n ),\n 0\n ),\n updated_at = NOW()\n WHERE id = $1\n RETURNING\n id,\n property_definition_id,\n display_order,\n number_value,\n string_value,\n color,\n created_at,\n updated_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "property_definition_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "display_order",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 3,
+ "name": "number_value",
+ "type_info": "Float8"
+ },
+ {
+ "ordinal": 4,
+ "name": "string_value",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "color",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "6b548846ffa651fd1956a59878840929721945db0225009f27f8b97567efce6a"
+}
diff --git a/.sqlx/query-a941261a6ffe89c2759c51f101302e8ea9c710ace7d2dff7e614d4e2933f3569.json b/.sqlx/query-a941261a6ffe89c2759c51f101302e8ea9c710ace7d2dff7e614d4e2933f3569.json
new file mode 100644
index 0000000000..1bde31e64c
--- /dev/null
+++ b/.sqlx/query-a941261a6ffe89c2759c51f101302e8ea9c710ace7d2dff7e614d4e2933f3569.json
@@ -0,0 +1,47 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT entity_id, entity_type as \"entity_type: EntityType\"\n FROM entity_properties\n WHERE property_definition_id = $1\n AND values ->> 'type' = 'SelectOption'\n AND values -> 'value' @> jsonb_build_array($2::text)\n ORDER BY entity_id, entity_type\n FOR UPDATE\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "entity_type: EntityType",
+ "type_info": {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK",
+ "CALL_RECORD",
+ "CALENDAR_EVENT"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "a941261a6ffe89c2759c51f101302e8ea9c710ace7d2dff7e614d4e2933f3569"
+}
diff --git a/.sqlx/query-ab0d7d90e31f65606dabe97d0975c8fb1efbd21fcebdf1c9abe762c73b01d33c.json b/.sqlx/query-ab0d7d90e31f65606dabe97d0975c8fb1efbd21fcebdf1c9abe762c73b01d33c.json
new file mode 100644
index 0000000000..1404bb00f8
--- /dev/null
+++ b/.sqlx/query-ab0d7d90e31f65606dabe97d0975c8fb1efbd21fcebdf1c9abe762c73b01d33c.json
@@ -0,0 +1,65 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id,\n property_definition_id,\n display_order,\n number_value,\n string_value,\n color,\n created_at,\n updated_at\n FROM property_options\n WHERE property_definition_id = $1\n AND string_value IS NOT NULL\n AND LOWER(BTRIM(string_value)) = LOWER(BTRIM($2))\n ORDER BY display_order, id\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "property_definition_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "display_order",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 3,
+ "name": "number_value",
+ "type_info": "Float8"
+ },
+ {
+ "ordinal": 4,
+ "name": "string_value",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "color",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "ab0d7d90e31f65606dabe97d0975c8fb1efbd21fcebdf1c9abe762c73b01d33c"
+}
diff --git a/.sqlx/query-baddcdef7a1d5aa92702bc02627746e6a719b84c400ad9e60d5068122ba59834.json b/.sqlx/query-baddcdef7a1d5aa92702bc02627746e6a719b84c400ad9e60d5068122ba59834.json
new file mode 100644
index 0000000000..b44db8d4e5
--- /dev/null
+++ b/.sqlx/query-baddcdef7a1d5aa92702bc02627746e6a719b84c400ad9e60d5068122ba59834.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT id FROM property_definitions WHERE id = $1 FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "baddcdef7a1d5aa92702bc02627746e6a719b84c400ad9e60d5068122ba59834"
+}
diff --git a/.sqlx/query-d3889ca37f9a82476c6f4b6d81c7780447e7bec6bd066caf3d31e1218c69dfb1.json b/.sqlx/query-d3889ca37f9a82476c6f4b6d81c7780447e7bec6bd066caf3d31e1218c69dfb1.json
new file mode 100644
index 0000000000..1ddc5c2678
--- /dev/null
+++ b/.sqlx/query-d3889ca37f9a82476c6f4b6d81c7780447e7bec6bd066caf3d31e1218c69dfb1.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE entity_properties\n SET values = jsonb_set(\n values,\n '{value}',\n COALESCE(\n (\n SELECT jsonb_agg(elem)\n FROM jsonb_array_elements(values -> 'value') AS elem\n WHERE elem <> to_jsonb($2::text)\n ),\n '[]'::jsonb\n )\n ),\n updated_at = NOW()\n WHERE property_definition_id = $1\n AND values ->> 'type' = 'SelectOption'\n AND values -> 'value' @> jsonb_build_array($2::text)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "d3889ca37f9a82476c6f4b6d81c7780447e7bec6bd066caf3d31e1218c69dfb1"
+}
diff --git a/apps/web/src/lib/service-clients/service-properties/generated/schemas/mergeTagRequest.ts b/apps/web/src/lib/service-clients/service-properties/generated/schemas/mergeTagRequest.ts
new file mode 100644
index 0000000000..edb3144802
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-properties/generated/schemas/mergeTagRequest.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * properties_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Request to replace a personal label with an existing team label.
+ */
+export interface MergeTagRequest {
+ /** The personal label to retire. */
+ option_id: string;
+ /** The team label every entity carrying `option_id` is retagged with. */
+ target_option_id: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-properties/generated/schemas/promoteTagRequest.ts b/apps/web/src/lib/service-clients/service-properties/generated/schemas/promoteTagRequest.ts
new file mode 100644
index 0000000000..d7f6eeb511
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-properties/generated/schemas/promoteTagRequest.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * properties_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Request to share one of the caller's personal labels with their team.
+ */
+export interface PromoteTagRequest {
+ /** The personal label to move into the team tag set. */
+ option_id: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-properties/generated/schemas/tagPromotionConflictResponse.ts b/apps/web/src/lib/service-clients/service-properties/generated/schemas/tagPromotionConflictResponse.ts
new file mode 100644
index 0000000000..a85c85e4f4
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-properties/generated/schemas/tagPromotionConflictResponse.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * properties_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PropertyOptionResponse } from './propertyOptionResponse';
+
+/**
+ * Body returned when a promotion collides with a label the team already has.
+The caller confirms with the user, then calls the merge endpoint with
+`conflicting_option.id` as the target.
+ */
+export interface TagPromotionConflictResponse {
+ /** The team label that already uses this name. */
+ conflicting_option: PropertyOptionResponse;
+ /** Human-readable description of the collision. */
+ message: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-properties/generated/zod.ts b/apps/web/src/lib/service-clients/service-properties/generated/zod.ts
index 8702c3bf66..b785442244 100644
--- a/apps/web/src/lib/service-clients/service-properties/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-properties/generated/zod.ts
@@ -1899,3 +1899,101 @@ export const ensureTagSetResponse = zod
.describe(
'A tag set the caller can use. `definition` is absent until the set is provisioned\n(on first label create), in which case `options` is empty.'
);
+
+/**
+ * Every entity carrying the personal label is retagged with the team label
+(deduped if it already has both) and the personal label is deleted. The team
+label's name and color win. This is the confirmation step after the promote
+endpoint reports a name collision.
+ * @summary Replace one of the caller's personal labels with an existing team label.
+ */
+export const mergeTagBody = zod
+ .object({
+ option_id: zod.uuid().describe('The personal label to retire.'),
+ target_option_id: zod
+ .uuid()
+ .describe(
+ 'The team label every entity carrying `option_id` is retagged with.'
+ ),
+ })
+ .describe('Request to replace a personal label with an existing team label.');
+
+export const mergeTagResponse = zod
+ .object({
+ color: zod.string().nullish(),
+ displayOrder: zod.number(),
+ id: zod.uuid(),
+ propertyDefinitionId: zod.uuid(),
+ value: zod
+ .union([
+ zod
+ .object({
+ type: zod.enum(['string']),
+ value: zod
+ .string()
+ .describe('String value for SelectString properties'),
+ })
+ .describe('String value for SelectString properties'),
+ zod
+ .object({
+ type: zod.enum(['number']),
+ value: zod
+ .number()
+ .describe('Number value for SelectNumber properties'),
+ })
+ .describe('Number value for SelectNumber properties'),
+ ])
+ .describe(
+ 'The value of a property option - either a string or a number.'
+ ),
+ })
+ .describe('Property option response (API representation).');
+
+/**
+ * The label moves into the team tag set keeping its option id, so every entity
+already carrying it keeps the label — it just becomes visible to, and usable
+by, the whole team. A 409 means the team already has a label with that name;
+its body carries that label, and confirming the replacement is a call to the
+merge endpoint with `conflicting_option.id` as `target_option_id`.
+ * @summary Share one of the caller's personal labels with their team.
+ */
+export const promoteTagBody = zod
+ .object({
+ option_id: zod
+ .uuid()
+ .describe('The personal label to move into the team tag set.'),
+ })
+ .describe(
+ "Request to share one of the caller's personal labels with their team."
+ );
+
+export const promoteTagResponse = zod
+ .object({
+ color: zod.string().nullish(),
+ displayOrder: zod.number(),
+ id: zod.uuid(),
+ propertyDefinitionId: zod.uuid(),
+ value: zod
+ .union([
+ zod
+ .object({
+ type: zod.enum(['string']),
+ value: zod
+ .string()
+ .describe('String value for SelectString properties'),
+ })
+ .describe('String value for SelectString properties'),
+ zod
+ .object({
+ type: zod.enum(['number']),
+ value: zod
+ .number()
+ .describe('Number value for SelectNumber properties'),
+ })
+ .describe('Number value for SelectNumber properties'),
+ ])
+ .describe(
+ 'The value of a property option - either a string or a number.'
+ ),
+ })
+ .describe('Property option response (API representation).');
diff --git a/apps/web/src/lib/service-clients/service-properties/openapi.json b/apps/web/src/lib/service-clients/service-properties/openapi.json
index 7abced117d..a71d891cdf 100644
--- a/apps/web/src/lib/service-clients/service-properties/openapi.json
+++ b/apps/web/src/lib/service-clients/service-properties/openapi.json
@@ -855,6 +855,97 @@
}
}
}
+ },
+ "/properties/tags/merge": {
+ "post": {
+ "tags": ["Properties"],
+ "summary": "Replace one of the caller's personal labels with an existing team label.",
+ "description": "Every entity carrying the personal label is retagged with the team label\n(deduped if it already has both) and the personal label is deleted. The team\nlabel's name and color win. This is the confirmation step after the promote\nendpoint reports a name collision.",
+ "operationId": "merge_tag",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/MergeTagRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Label merged into the team label",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PropertyOptionResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid request"
+ },
+ "403": {
+ "description": "Team membership required"
+ },
+ "404": {
+ "description": "Either label was not found in the expected tag set"
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ }
+ }
+ },
+ "/properties/tags/promote": {
+ "post": {
+ "tags": ["Properties"],
+ "summary": "Share one of the caller's personal labels with their team.",
+ "description": "The label moves into the team tag set keeping its option id, so every entity\nalready carrying it keeps the label — it just becomes visible to, and usable\nby, the whole team. A 409 means the team already has a label with that name;\nits body carries that label, and confirming the replacement is a call to the\nmerge endpoint with `conflicting_option.id` as `target_option_id`.",
+ "operationId": "promote_tag",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PromoteTagRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Label moved to the team tag set",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PropertyOptionResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Team membership required"
+ },
+ "404": {
+ "description": "Label not found in the caller's tag set"
+ },
+ "409": {
+ "description": "The team already has a label with that name",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TagPromotionConflictResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ }
+ }
}
},
"components": {
@@ -1362,6 +1453,35 @@
}
}
},
+ "MergeTagRequest": {
+ "type": "object",
+ "description": "Request to replace a personal label with an existing team label.",
+ "required": ["option_id", "target_option_id"],
+ "properties": {
+ "option_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The personal label to retire."
+ },
+ "target_option_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The team label every entity carrying `option_id` is retagged with."
+ }
+ }
+ },
+ "PromoteTagRequest": {
+ "type": "object",
+ "description": "Request to share one of the caller's personal labels with their team.",
+ "required": ["option_id"],
+ "properties": {
+ "option_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The personal label to move into the team tag set."
+ }
+ }
+ },
"PropertyDataType": {
"oneOf": [
{
@@ -2157,6 +2277,21 @@
],
"description": "Type-safe enum for setting entity property values - provides compile-time validation."
},
+ "TagPromotionConflictResponse": {
+ "type": "object",
+ "description": "Body returned when a promotion collides with a label the team already has.\nThe caller confirms with the user, then calls the merge endpoint with\n`conflicting_option.id` as the target.",
+ "required": ["message", "conflicting_option"],
+ "properties": {
+ "conflicting_option": {
+ "$ref": "#/components/schemas/PropertyOptionResponse",
+ "description": "The team label that already uses this name."
+ },
+ "message": {
+ "type": "string",
+ "description": "Human-readable description of the collision."
+ }
+ }
+ },
"TagScope": {
"type": "string",
"description": "Which owner a tag set belongs to.",
diff --git a/crates/properties/README.md b/crates/properties/README.md
index d74ef930a0..5b0c09f307 100644
--- a/crates/properties/README.md
+++ b/crates/properties/README.md
@@ -32,7 +32,7 @@ nested model specifies otherwise.
| `property.created` | A property definition is persisted. A newly created TAG definition from `ensure_tag_set` also emits this event; the get-existing path does not. | `property_definition_id`, `actor_user_id`, `owner`, `display_name`, `data_type`, `is_multi_select`, `specific_entity_type`, `created_at` |
| `property.deleted` | A property definition is deleted. | `property_definition_id`, `actor_user_id`, `owner`, `display_name`, `data_type` |
| `property_option.created` | An option is added to a SELECT or TAG definition. | `option_id`, `property_definition_id`, `actor_user_id`, `value`, `color`, `display_order` |
-| `property_option.updated` | An option is renamed, recolored, or reordered. The metadata is the full post-update state, not a delta. | `option_id`, `property_definition_id`, `actor_user_id`, `value`, `color`, `display_order` |
+| `property_option.updated` | An option is renamed, recolored, reordered, or moved to another definition by a tag promotion. The metadata is the full post-update state, not a delta, so `property_definition_id` is the definition that owns the option *after* the change. | `option_id`, `property_definition_id`, `actor_user_id`, `value`, `color`, `display_order` |
| `property_option.deleted` | An option is deleted. `value` is the pre-delete snapshot. | `option_id`, `property_definition_id`, `actor_user_id`, `value` |
| `entity_property.updated` | An entity value is set, replaced, attached with a null value, or changed by an option add/remove. Bulk operations emit one event for each actual `(entity, property_definition)` mutation. | `entity_property_id`, `entity_id`, `entity_type`, `property_definition_id`, `actor_user_id`, `value`, `updated_at` |
| `entity_property.deleted` | One entity-property row is deleted. | `entity_property_id`, `entity_id`, `entity_type`, `property_definition_id`, `actor_user_id` |
@@ -117,6 +117,24 @@ Consumers maintaining derived state must apply these implications. Definition
and entity records use different keys, so the lack of cross-key ordering also
applies while handling these cascades.
+Sharing a personal label with a team (`POST /properties/tags/promote` and
+`POST /properties/tags/merge`) moves entity values between two TAG definitions
+in one transaction, and reports that as a label event plus one
+`entity_property.updated` per retagged entity:
+
+- A promotion keeps the option id and emits `property_option.updated` whose
+ `property_definition_id` is the *team* definition. An option changing its
+ owning definition is the only case where that field moves; consumers keyed on
+ the previous definition must re-read rather than assume it is stable.
+- A merge emits `property_option.deleted` for the retired personal option, with
+ the same "stripped from every entity value" implication as any option
+ deletion.
+- Both emit one `entity_property.updated` per affected entity, carrying the
+ entity's team-definition row. There is no event for the personal-definition
+ row the option was stripped from; the entity event is enough for consumers
+ that rebuild an entity's whole property set (`soup_realtime` and the search
+ properties indexer both do).
+
Parent Task and Subtasks writes update reciprocal task relationships in the
same transaction. Version 1 emits `entity_property.updated` only for the entity
targeted by the API call; it omits a separate event for each reciprocally
diff --git a/crates/properties/src/domain/error.rs b/crates/properties/src/domain/error.rs
index dd6a788d2c..aad0c7342c 100644
--- a/crates/properties/src/domain/error.rs
+++ b/crates/properties/src/domain/error.rs
@@ -1,5 +1,6 @@
//! Domain error types for properties.
+use models_properties::service::property_option::PropertyOption;
use thiserror::Error;
/// Domain error type for property operations.
@@ -33,6 +34,12 @@ pub enum PropertiesErr {
#[error("An option with that value already exists")]
DuplicateOptionValue,
+ /// Promoting a personal label would collide with an existing team label -
+ /// maps to 409. Carries the team label so the caller can offer to merge
+ /// into it instead.
+ #[error("A team label with that name already exists")]
+ ConflictingTeamLabel(Box<PropertyOption>),
+
/// System properties cannot be modified - maps to 403
#[error("Cannot modify system properties")]
SystemPropertyNotModifiable,
diff --git a/crates/properties/src/domain/model.rs b/crates/properties/src/domain/model.rs
index 6d7abcd650..7fa6f91cda 100644
--- a/crates/properties/src/domain/model.rs
+++ b/crates/properties/src/domain/model.rs
@@ -186,6 +186,28 @@ pub struct TagSet {
pub options: Vec<PropertyOption>,
}
+/// The persisted result of moving a personal label into a team tag set.
+#[derive(Debug, Clone)]
+pub struct TagRemapOutcome {
+ /// The team-owned option the label resolves to after the remap.
+ pub option: PropertyOption,
+ /// One post-commit snapshot per entity whose team tag value was rewritten,
+ /// used to publish the entity-property events that drive search and Soup.
+ pub mutations: Vec<EntityPropertyMutationSnapshot>,
+}
+
+/// Result of promoting a personal label into the caller's team tag set.
+#[derive(Debug, Clone)]
+pub enum TagPromotionOutcome {
+ /// The label moved to the team tag set, keeping its option id so every
+ /// entity already carrying it keeps resolving to the same label.
+ Promoted(TagRemapOutcome),
+ /// The team already has a label with that name (compared case-insensitively
+ /// on the trimmed value). Carries that team label so the caller can offer to
+ /// merge into it instead.
+ Conflict(PropertyOption),
+}
+
/// One property's requested option changes in a bulk selection update.
///
/// The change is expressed as a delta (options to add, options to remove) rather
diff --git a/crates/properties/src/domain/ports.rs b/crates/properties/src/domain/ports.rs
index 6fcb4152bd..987259ec8b 100644
--- a/crates/properties/src/domain/ports.rs
+++ b/crates/properties/src/domain/ports.rs
@@ -23,7 +23,8 @@ use uuid::Uuid;
use super::model::{
EditReceipt, EntityPropertiesKey, EntityPropertyInfo, EntityPropertyMutationSnapshot,
EntityPropertyOptionSelection, EntityPropertyOptionUpdate, GetOrCreateTagDefinitionResult,
- PropertyDefinitionOwner, TaskAssignedNotification, UpdatePropertyOptionOutcome, ViewReceipt,
+ PropertyDefinitionOwner, TagPromotionOutcome, TagRemapOutcome, TaskAssignedNotification,
+ UpdatePropertyOptionOutcome, ViewReceipt,
};
/// Repository trait for property operations.
@@ -155,6 +156,36 @@ pub trait PropertiesRepo: Send + Sync + 'static {
owner: PropertyDefinitionOwner<'a>,
) -> impl Future<Output = Result<GetOrCreateTagDefinitionResult, Self::Err>> + Send;
+ /// Move a personal tag option into a team tag definition, keeping the option
+ /// id, and rewrite every entity value that referenced it so the label now
+ /// hangs off the team definition.
+ ///
+ /// The whole move is one transaction that first locks the target definition,
+ /// so two callers promoting the same label name into one team serialize and
+ /// the loser sees the winner's label as a
+ /// [`TagPromotionOutcome::Conflict`] instead of creating a duplicate.
+ /// Names are compared case-insensitively on the trimmed value.
+ fn promote_tag_option(
+ &self,
+ option_id: Uuid,
+ source_definition_id: Uuid,
+ target_definition_id: Uuid,
+ ) -> impl Future<Output = Result<TagPromotionOutcome, Self::Err>> + Send;
+
+ /// Replace a personal tag option with an existing team option: every entity
+ /// carrying the personal label is retagged with the team label (deduped if
+ /// it already has it), then the personal option is deleted.
+ ///
+ /// Returns `None` when `target_option_id` does not belong to
+ /// `target_definition_id`, which the caller reports as a missing option.
+ fn merge_tag_option(
+ &self,
+ source_option_id: Uuid,
+ source_definition_id: Uuid,
+ target_option_id: Uuid,
+ target_definition_id: Uuid,
+ ) -> impl Future<Output = Result<Option<TagRemapOutcome>, Self::Err>> + Send;
+
/// Count how many of the provided option IDs exist for the property definition.
fn count_valid_property_options(
&self,
diff --git a/crates/properties/src/domain/service.rs b/crates/properties/src/domain/service.rs
index 359f0f8d1f..6123ae17c3 100644
--- a/crates/properties/src/domain/service.rs
+++ b/crates/properties/src/domain/service.rs
@@ -256,6 +256,37 @@ pub trait PropertiesService: Send + Sync + 'static {
scope: TagScope,
) -> impl Future<Output = Result<TagSet, PropertiesErr>> + Send;
+ /// Share one of the caller's personal labels with their team by moving it
+ /// into the team tag set, provisioning that set if the team has none yet.
+ ///
+ /// The option id survives the move, so every entity already carrying the
+ /// label keeps resolving to it. Fails with
+ /// [`PropertiesErr::ConflictingTeamLabel`] when the team already has a label
+ /// of that name (trimmed, case-insensitive), carrying that label so the
+ /// caller can offer [`Self::merge_tag_option`] instead. Requires the option
+ /// to be a label in the caller's own tag set and the caller to be on a team.
+ fn promote_tag_option(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ team: Option<&TeamReceipt>,
+ option_id: Uuid,
+ ) -> impl Future<Output = Result<PropertyOption, PropertiesErr>> + Send;
+
+ /// Replace one of the caller's personal labels with an existing team label:
+ /// every entity carrying the personal label is retagged with the team label
+ /// (deduped if it already has both), then the personal label is deleted.
+ ///
+ /// The team label's name and color win. Requires the source option to be a
+ /// label in the caller's own tag set and the target to be a label in their
+ /// team's tag set.
+ fn merge_tag_option(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ team: Option<&TeamReceipt>,
+ option_id: Uuid,
+ target_option_id: Uuid,
+ ) -> impl Future<Output = Result<PropertyOption, PropertiesErr>> + Send;
+
/// Get an entity's stored properties with definitions, values, and options,
/// sorted by display name. Personal tag properties of other users are
/// filtered out. Does not include computed metadata properties
diff --git a/crates/properties/src/domain/service_impl/mod.rs b/crates/properties/src/domain/service_impl/mod.rs
index 850e442686..4a66710822 100644
--- a/crates/properties/src/domain/service_impl/mod.rs
+++ b/crates/properties/src/domain/service_impl/mod.rs
@@ -39,8 +39,8 @@ use super::metadata;
use super::model::{
EditReceipt, EntityOptionUpdateOutcome, EntityPropertyInfo, EntityPropertyOptionSelection,
EntityPropertyOptionUpdate, PropertyAccessReceiptExt, PropertyDefinitionOwner,
- PropertyTargetKey, ResolvedPropertySubject, TagScope, TagSet, UpdatePropertyOptionOutcome,
- ViewReceipt,
+ PropertyTargetKey, ResolvedPropertySubject, TagPromotionOutcome, TagRemapOutcome, TagScope,
+ TagSet, UpdatePropertyOptionOutcome, ViewReceipt,
};
use super::ports::{NotificationService, PermissionService, PropertiesRepo};
use super::service::{PropertiesService, TeamReceipt, team_id_from_receipt};
@@ -322,6 +322,78 @@ where
.ok_or(PropertiesErr::NotFound)
}
+ /// Resolve the personal tag definition that owns `option_id`, rejecting
+ /// options the caller does not own and options that are not labels.
+ async fn owned_personal_tag_option(
+ &self,
+ option_id: Uuid,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> Result<(PropertyOption, PropertyDefinition), PropertiesErr>
+ where
+ anyhow::Error: From<R::Err>,
+ {
+ let option = self
+ .repository
+ .get_property_option(option_id)
+ .await
+ .map_err(anyhow::Error::from)?
+ .ok_or(PropertiesErr::OptionNotFound)?;
+
+ let definition = self
+ .repository
+ .get_tag_definition(PropertyDefinitionOwner::User(user_id))
+ .await
+ .map_err(anyhow::Error::from)?
+ .ok_or(PropertiesErr::OptionNotFound)?;
+
+ if option.property_definition_id != definition.id {
+ return Err(PropertiesErr::OptionNotFound);
+ }
+
+ Ok((option, definition))
+ }
+
+ /// Provision the team tag set the caller is sharing a label into.
+ async fn target_team_tag_definition(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ team: Option<&TeamReceipt>,
+ ) -> Result<PropertyDefinition, PropertiesErr>
+ where
+ anyhow::Error: From<R::Err>,
+ {
+ let team_id = team_id_from_receipt(team).ok_or(PropertiesErr::TeamMembershipRequired)?;
+ let result = self
+ .repository
+ .get_or_create_tag_definition(PropertyDefinitionOwner::Team(team_id))
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ if result.created {
+ self.publish_property_event(Self::property_created_event(&result.definition, user_id));
+ }
+
+ Ok(result.definition)
+ }
+
+ /// Publish one entity-property event per entity the remap rewrote, so the
+ /// search index and Soup rebuild those entities from the committed rows.
+ fn publish_tag_remap_events(&self, remap: &TagRemapOutcome, actor: &MacroUserIdStr<'_>) {
+ for mutation in &remap.mutations {
+ self.publish_property_event(PropertyMacroEvent::entity_property_updated(
+ EntityPropertyUpdatedMetadata {
+ entity_property_id: mutation.property.id,
+ entity_id: mutation.property.entity_id.clone(),
+ entity_type: mutation.property.entity_type,
+ property_definition_id: mutation.property.property_definition_id,
+ actor_user_id: Some(actor.clone().into_owned()),
+ value: mutation.value.clone(),
+ updated_at: mutation.property.updated_at,
+ },
+ ));
+ }
+ }
+
/// Resolve a tag set's options. A missing definition yields an empty set.
async fn build_tag_set(
&self,
@@ -1321,6 +1393,87 @@ where
self.build_tag_set(scope, Some(result.definition)).await
}
+ #[tracing::instrument(skip(self, team), err)]
+ async fn promote_tag_option(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ team: Option<&TeamReceipt>,
+ option_id: Uuid,
+ ) -> Result<PropertyOption, PropertiesErr> {
+ let (_, source_definition) = self.owned_personal_tag_option(option_id, user_id).await?;
+ let target_definition = self.target_team_tag_definition(user_id, team).await?;
+
+ let outcome = self
+ .repository
+ .promote_tag_option(option_id, source_definition.id, target_definition.id)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ let remap = match outcome {
+ TagPromotionOutcome::Promoted(remap) => remap,
+ TagPromotionOutcome::Conflict(conflict) => {
+ tracing::info!(
+ conflicting_option_id = %conflict.id,
+ "team already has a label with that name"
+ );
+ return Err(PropertiesErr::ConflictingTeamLabel(Box::new(conflict)));
+ }
+ };
+
+ tracing::info!(
+ entities_retagged = remap.mutations.len(),
+ "promoted personal label to the team tag set"
+ );
+
+ // The option keeps its id, so this reports the same label now hanging
+ // off the team definition rather than a newly created one.
+ self.publish_property_event(Self::property_option_updated_event(&remap.option, user_id));
+ self.publish_tag_remap_events(&remap, user_id);
+
+ Ok(remap.option)
+ }
+
+ #[tracing::instrument(skip(self, team), err)]
+ async fn merge_tag_option(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ team: Option<&TeamReceipt>,
+ option_id: Uuid,
+ target_option_id: Uuid,
+ ) -> Result<PropertyOption, PropertiesErr> {
+ if option_id == target_option_id {
+ return Err(PropertiesErr::Validation(
+ "cannot merge a label into itself".to_string(),
+ ));
+ }
+
+ let (source_option, source_definition) =
+ self.owned_personal_tag_option(option_id, user_id).await?;
+ let target_definition = self.target_team_tag_definition(user_id, team).await?;
+
+ let remap = self
+ .repository
+ .merge_tag_option(
+ option_id,
+ source_definition.id,
+ target_option_id,
+ target_definition.id,
+ )
+ .await
+ .map_err(anyhow::Error::from)?
+ .ok_or(PropertiesErr::OptionNotFound)?;
+
+ tracing::info!(
+ entities_retagged = remap.mutations.len(),
+ "merged personal label into an existing team label"
+ );
+
+ self.publish_property_event(Self::property_option_deleted_event(&source_option, user_id));
+ self.publish_tag_remap_events(&remap, user_id);
+
+ Ok(remap.option)
+ }
+
#[tracing::instrument(skip(self, access), fields(entity_id = %access.entity_id(), entity_type = ?access.entity_type()), err)]
async fn get_entity_properties_with_definitions(
&self,
diff --git a/crates/properties/src/domain/test.rs b/crates/properties/src/domain/test.rs
index 19108ca4f6..cc07bb1190 100644
--- a/crates/properties/src/domain/test.rs
+++ b/crates/properties/src/domain/test.rs
@@ -3872,3 +3872,416 @@ async fn test_bulk_update_entities_rejects_invalid_option_wholesale() {
crate::domain::error::PropertiesErr::Validation(_)
));
}
+
+// ===== Sharing a personal label with the team =====
+
+fn team_id() -> Uuid {
+ Uuid::from_u128(0x7EA3)
+}
+
+/// A team-membership receipt for the test caller, minted without a check.
+fn team_receipt() -> crate::domain::service::TeamReceipt {
+ crate::domain::service::TeamReceipt::dangerously_assert_authenticated_user(
+ caller_user_id(),
+ &team_id().to_string(),
+ AccessEntityType::Team,
+ )
+}
+
+fn tag_definition(id: Uuid, owner: PropertyOwner) -> PropertyDefinition {
+ let created_at = event_timestamp();
+ PropertyDefinition {
+ id,
+ owner,
+ display_name: "Tags".to_string(),
+ data_type: DataType::Tag,
+ is_multi_select: true,
+ specific_entity_type: None,
+ created_at,
+ updated_at: created_at,
+ is_system: false,
+ is_metadata: false,
+ }
+}
+
+fn personal_tag_definition(id: Uuid) -> PropertyDefinition {
+ tag_definition(
+ id,
+ PropertyOwner::User {
+ user_id: caller_user_id().to_string(),
+ },
+ )
+}
+
+fn team_tag_definition(id: Uuid) -> PropertyDefinition {
+ tag_definition(id, PropertyOwner::Team { team_id: team_id() })
+}
+
+/// Wire up the reads every promote/merge does before it touches the tag sets:
+/// the label being shared, the caller's tag set, and the team's.
+fn expect_tag_sets(
+ repo: &mut MockPropertiesRepo,
+ option: PropertyOption,
+ personal: PropertyDefinition,
+ team: PropertyDefinition,
+) {
+ repo.expect_get_property_option()
+ .return_once(move |_| Box::pin(async move { Ok(Some(option)) }));
+ repo.expect_get_tag_definition()
+ .return_once(move |_| Box::pin(async move { Ok(Some(personal)) }));
+ repo.expect_get_or_create_tag_definition()
+ .return_once(move |_| {
+ Box::pin(async move {
+ Ok(GetOrCreateTagDefinitionResult {
+ definition: team,
+ created: false,
+ })
+ })
+ });
+}
+
+#[tokio::test]
+async fn promote_tag_publishes_the_moved_option_and_every_retagged_entity() {
+ let personal_definition_id = Uuid::from_u128(0x7A01);
+ let team_definition_id = Uuid::from_u128(0x7A02);
+ let option_id = Uuid::from_u128(0x7A03);
+
+ let personal_option = property_option_for_event(
+ option_id,
+ personal_definition_id,
+ 0,
+ PropertyOptionValue::String("bug-report".to_string()),
+ Some("#ff0000"),
+ );
+ // The move keeps the option id and hands it to the team definition.
+ let promoted_option = property_option_for_event(
+ option_id,
+ team_definition_id,
+ 3,
+ PropertyOptionValue::String("bug-report".to_string()),
+ Some("#ff0000"),
+ );
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_tag_sets(
+ &mut repo,
+ personal_option,
+ personal_tag_definition(personal_definition_id),
+ team_tag_definition(team_definition_id),
+ );
+ let expected_option = promoted_option.clone();
+ repo.expect_promote_tag_option()
+ .return_once(move |_, _, _| {
+ Box::pin(async move {
+ Ok(crate::domain::model::TagPromotionOutcome::Promoted(
+ crate::domain::model::TagRemapOutcome {
+ option: expected_option,
+ mutations: vec![
+ entity_property_mutation(
+ "doc1",
+ EntityType::Document,
+ team_definition_id,
+ Some(PropertyValue::SelectOption(vec![option_id])),
+ ),
+ entity_property_mutation(
+ "thread1",
+ EntityType::Thread,
+ team_definition_id,
+ Some(PropertyValue::SelectOption(vec![option_id])),
+ ),
+ ],
+ },
+ ))
+ })
+ });
+
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let option = service
+ .promote_tag_option(&caller_user_id(), Some(&team_receipt()), option_id)
+ .await
+ .unwrap();
+ assert_eq!(option.property_definition_id, team_definition_id);
+
+ let events = event_broker.events();
+ let event_types: Vec<_> = events
+ .iter()
+ .map(|event| event.envelope["event_type"].as_str().unwrap().to_string())
+ .collect();
+ assert_eq!(
+ event_types,
+ vec![
+ "property_option.updated",
+ "entity_property.updated",
+ "entity_property.updated",
+ ],
+ "search and Soup rebuild from one entity event per retagged entity"
+ );
+ assert_eq!(
+ events[1].envelope["metadata"]["entity_id"], "doc1",
+ "the entity events carry the entities, not the label"
+ );
+ assert_eq!(events[2].envelope["metadata"]["entity_id"], "thread1");
+}
+
+#[tokio::test]
+async fn promote_tag_reports_the_colliding_team_label() {
+ let personal_definition_id = Uuid::from_u128(0x7B01);
+ let team_definition_id = Uuid::from_u128(0x7B02);
+ let option_id = Uuid::from_u128(0x7B03);
+ let conflict_id = Uuid::from_u128(0x7B04);
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_tag_sets(
+ &mut repo,
+ property_option_for_event(
+ option_id,
+ personal_definition_id,
+ 0,
+ PropertyOptionValue::String("Urgent".to_string()),
+ Some("#ff0000"),
+ ),
+ personal_tag_definition(personal_definition_id),
+ team_tag_definition(team_definition_id),
+ );
+ repo.expect_promote_tag_option()
+ .return_once(move |_, _, _| {
+ Box::pin(async move {
+ Ok(crate::domain::model::TagPromotionOutcome::Conflict(
+ property_option_for_event(
+ conflict_id,
+ team_definition_id,
+ 1,
+ PropertyOptionValue::String("urgent".to_string()),
+ Some("#00ff00"),
+ ),
+ ))
+ })
+ });
+
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let err = service
+ .promote_tag_option(&caller_user_id(), Some(&team_receipt()), option_id)
+ .await
+ .unwrap_err();
+
+ let PropertiesErr::ConflictingTeamLabel(conflict) = err else {
+ panic!("expected the conflicting team label, got {err:?}");
+ };
+ assert_eq!(conflict.id, conflict_id);
+ assert!(
+ event_broker.events().is_empty(),
+ "a rejected promotion changed nothing to publish"
+ );
+}
+
+#[tokio::test]
+async fn promote_tag_requires_a_team() {
+ let personal_definition_id = Uuid::from_u128(0x7C01);
+ let option_id = Uuid::from_u128(0x7C02);
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_option().return_once(move |_| {
+ Box::pin(async move {
+ Ok(Some(property_option_for_event(
+ option_id,
+ personal_definition_id,
+ 0,
+ PropertyOptionValue::String("bug-report".to_string()),
+ Some("#ff0000"),
+ )))
+ })
+ });
+ repo.expect_get_tag_definition().return_once(move |_| {
+ Box::pin(async move { Ok(Some(personal_tag_definition(personal_definition_id))) })
+ });
+ repo.expect_promote_tag_option().never();
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ None::<MockPermissionService>,
+ None::<MockNotificationService>,
+ );
+
+ let err = service
+ .promote_tag_option(&caller_user_id(), None, option_id)
+ .await
+ .unwrap_err();
+ assert!(matches!(err, PropertiesErr::TeamMembershipRequired));
+}
+
+#[tokio::test]
+async fn promote_tag_rejects_a_label_from_another_tag_set() {
+ let option_id = Uuid::from_u128(0x7D01);
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_option().return_once(move |_| {
+ Box::pin(async move {
+ Ok(Some(property_option_for_event(
+ option_id,
+ // Somebody else's tag definition.
+ Uuid::from_u128(0x7D02),
+ 0,
+ PropertyOptionValue::String("not-mine".to_string()),
+ Some("#ff0000"),
+ )))
+ })
+ });
+ repo.expect_get_tag_definition().return_once(move |_| {
+ Box::pin(async move { Ok(Some(personal_tag_definition(Uuid::from_u128(0x7D03)))) })
+ });
+ repo.expect_promote_tag_option().never();
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ None::<MockPermissionService>,
+ None::<MockNotificationService>,
+ );
+
+ let err = service
+ .promote_tag_option(&caller_user_id(), Some(&team_receipt()), option_id)
+ .await
+ .unwrap_err();
+ assert!(matches!(err, PropertiesErr::OptionNotFound));
+}
+
+#[tokio::test]
+async fn merge_tag_publishes_the_retired_label_and_every_retagged_entity() {
+ let personal_definition_id = Uuid::from_u128(0x7E01);
+ let team_definition_id = Uuid::from_u128(0x7E02);
+ let option_id = Uuid::from_u128(0x7E03);
+ let target_option_id = Uuid::from_u128(0x7E04);
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_tag_sets(
+ &mut repo,
+ property_option_for_event(
+ option_id,
+ personal_definition_id,
+ 0,
+ PropertyOptionValue::String("Urgent".to_string()),
+ Some("#ff0000"),
+ ),
+ personal_tag_definition(personal_definition_id),
+ team_tag_definition(team_definition_id),
+ );
+ repo.expect_merge_tag_option()
+ .return_once(move |_, _, _, _| {
+ Box::pin(async move {
+ Ok(Some(crate::domain::model::TagRemapOutcome {
+ option: property_option_for_event(
+ target_option_id,
+ team_definition_id,
+ 1,
+ PropertyOptionValue::String("urgent".to_string()),
+ Some("#00ff00"),
+ ),
+ mutations: vec![entity_property_mutation(
+ "doc1",
+ EntityType::Document,
+ team_definition_id,
+ Some(PropertyValue::SelectOption(vec![target_option_id])),
+ )],
+ }))
+ })
+ });
+
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let option = service
+ .merge_tag_option(
+ &caller_user_id(),
+ Some(&team_receipt()),
+ option_id,
+ target_option_id,
+ )
+ .await
+ .unwrap();
+ assert_eq!(option.id, target_option_id, "the team label wins");
+
+ let events = event_broker.events();
+ let event_types: Vec<_> = events
+ .iter()
+ .map(|event| event.envelope["event_type"].as_str().unwrap().to_string())
+ .collect();
+ assert_eq!(
+ event_types,
+ vec!["property_option.deleted", "entity_property.updated"]
+ );
+ assert_eq!(
+ events[0].envelope["metadata"]["option_id"],
+ option_id.to_string(),
+ "the retired label is the personal one"
+ );
+}
+
+#[tokio::test]
+async fn merge_tag_rejects_a_target_outside_the_team_tag_set() {
+ let personal_definition_id = Uuid::from_u128(0x7F01);
+ let team_definition_id = Uuid::from_u128(0x7F02);
+ let option_id = Uuid::from_u128(0x7F03);
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_tag_sets(
+ &mut repo,
+ property_option_for_event(
+ option_id,
+ personal_definition_id,
+ 0,
+ PropertyOptionValue::String("Urgent".to_string()),
+ Some("#ff0000"),
+ ),
+ personal_tag_definition(personal_definition_id),
+ team_tag_definition(team_definition_id),
+ );
+ repo.expect_merge_tag_option()
+ .return_once(move |_, _, _, _| Box::pin(async move { Ok(None) }));
+
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let err = service
+ .merge_tag_option(
+ &caller_user_id(),
+ Some(&team_receipt()),
+ option_id,
+ Uuid::from_u128(0x7F04),
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(err, PropertiesErr::OptionNotFound));
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn merge_tag_rejects_merging_a_label_into_itself() {
+ let option_id = Uuid::from_u128(0x8003);
+
+ // The guard runs before anything is read, so provisioning a team tag set
+ // is not a side effect of a request that was never going to work.
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_option().never();
+ repo.expect_get_or_create_tag_definition().never();
+ repo.expect_merge_tag_option().never();
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ None::<MockPermissionService>,
+ None::<MockNotificationService>,
+ );
+
+ let err = service
+ .merge_tag_option(
+ &caller_user_id(),
+ Some(&team_receipt()),
+ option_id,
+ option_id,
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(err, PropertiesErr::Validation(_)));
+}
diff --git a/crates/properties/src/inbound/axum_router.rs b/crates/properties/src/inbound/axum_router.rs
index ef166395f2..b97c7106f7 100644
--- a/crates/properties/src/inbound/axum_router.rs
+++ b/crates/properties/src/inbound/axum_router.rs
@@ -90,7 +90,9 @@ pub fn properties_err_status(e: &PropertiesErr) -> StatusCode {
PropertiesErr::NotFound
| PropertiesErr::OptionNotFound
| PropertiesErr::EntityPropertyNotFound => StatusCode::NOT_FOUND,
- PropertiesErr::DuplicateOptionValue => StatusCode::CONFLICT,
+ PropertiesErr::DuplicateOptionValue | PropertiesErr::ConflictingTeamLabel(_) => {
+ StatusCode::CONFLICT
+ }
PropertiesErr::PermissionDenied
| PropertiesErr::SystemPropertyNotModifiable
| PropertiesErr::RequiredProperty
@@ -135,6 +137,10 @@ where
"/tags",
get(tags::list_tags::<S, A, Auth>).post(tags::ensure_tag_set::<S, A, Auth>),
)
+ // Share a personal label with the team, and the merge that resolves a
+ // name collision reported by the promote endpoint
+ .route("/tags/promote", post(tags::promote_tag::<S, A, Auth>))
+ .route("/tags/merge", post(tags::merge_tag::<S, A, Auth>))
// Entity Property Operations
// GET allows anonymous access for public entities
.route(
diff --git a/crates/properties/src/inbound/axum_router/tags.rs b/crates/properties/src/inbound/axum_router/tags.rs
index 2860a0e56c..6a4cbb0084 100644
--- a/crates/properties/src/inbound/axum_router/tags.rs
+++ b/crates/properties/src/inbound/axum_router/tags.rs
@@ -3,6 +3,7 @@
use axum::{
Json,
extract::State,
+ http::StatusCode,
response::{IntoResponse, Response},
};
use entity_access::domain::ports::EntityAccessService;
@@ -11,6 +12,7 @@ use models_properties::api::{PropertyDefinitionDetailResponse, PropertyOptionRes
use serde::{Deserialize, Serialize};
use thiserror::Error;
use utoipa::ToSchema;
+use uuid::Uuid;
use super::{PropertiesRouterState, PropertyTeamExtractor, properties_err_status};
use crate::domain::error::PropertiesErr;
@@ -71,6 +73,33 @@ pub struct EnsureTagSetRequest {
pub scope: TagScope,
}
+/// Request to share one of the caller's personal labels with their team.
+#[derive(Debug, Deserialize, ToSchema)]
+pub struct PromoteTagRequest {
+ /// The personal label to move into the team tag set.
+ pub option_id: Uuid,
+}
+
+/// Request to replace a personal label with an existing team label.
+#[derive(Debug, Deserialize, ToSchema)]
+pub struct MergeTagRequest {
+ /// The personal label to retire.
+ pub option_id: Uuid,
+ /// The team label every entity carrying `option_id` is retagged with.
+ pub target_option_id: Uuid,
+}
+
+/// Body returned when a promotion collides with a label the team already has.
+/// The caller confirms with the user, then calls the merge endpoint with
+/// `conflicting_option.id` as the target.
+#[derive(Debug, Serialize, ToSchema)]
+pub struct TagPromotionConflictResponse {
+ /// Human-readable description of the collision.
+ pub message: String,
+ /// The team label that already uses this name.
+ pub conflicting_option: PropertyOptionResponse,
+}
+
#[derive(Debug, Error)]
pub enum TagsError {
#[error(transparent)]
@@ -79,6 +108,19 @@ pub enum TagsError {
impl IntoResponse for TagsError {
fn into_response(self) -> Response {
+ // The conflict carries the colliding label, so it answers with JSON the
+ // caller can act on rather than the plain-text body of the other errors.
+ if let TagsError::Properties(PropertiesErr::ConflictingTeamLabel(conflict)) = &self {
+ return (
+ StatusCode::CONFLICT,
+ Json(TagPromotionConflictResponse {
+ message: self.to_string(),
+ conflicting_option: conflict.as_ref().clone().into(),
+ }),
+ )
+ .into_response();
+ }
+
let status_code = match &self {
TagsError::Properties(e) => properties_err_status(e),
};
@@ -157,3 +199,95 @@ pub async fn ensure_tag_set<
Ok(Json(set.into()))
}
+
+/// Share one of the caller's personal labels with their team.
+///
+/// The label moves into the team tag set keeping its option id, so every entity
+/// already carrying it keeps the label — it just becomes visible to, and usable
+/// by, the whole team. A 409 means the team already has a label with that name;
+/// its body carries that label, and confirming the replacement is a call to the
+/// merge endpoint with `conflicting_option.id` as `target_option_id`.
+#[utoipa::path(
+ post,
+ path = "/properties/tags/promote",
+ request_body = PromoteTagRequest,
+ responses(
+ (status = 200, description = "Label moved to the team tag set", body = PropertyOptionResponse),
+ (status = 403, description = "Team membership required"),
+ (status = 404, description = "Label not found in the caller's tag set"),
+ (status = 409, description = "The team already has a label with that name", body = TagPromotionConflictResponse),
+ (status = 500, description = "Internal server error")
+ ),
+ tag = "Properties"
+)]
+#[tracing::instrument(skip(state, user, team), fields(option_id = %request.option_id), err)]
+pub async fn promote_tag<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+ team: PropertyTeamExtractor<A, Auth>,
+ Json(request): Json<PromoteTagRequest>,
+) -> Result<Json<PropertyOptionResponse>, TagsError> {
+ let user = user.authorization.user.macro_user_id;
+ let option = state
+ .properties_service
+ .promote_tag_option(
+ &user,
+ team.entity_access_receipt.as_ref(),
+ request.option_id,
+ )
+ .await?;
+
+ Ok(Json(option.into()))
+}
+
+/// Replace one of the caller's personal labels with an existing team label.
+///
+/// Every entity carrying the personal label is retagged with the team label
+/// (deduped if it already has both) and the personal label is deleted. The team
+/// label's name and color win. This is the confirmation step after the promote
+/// endpoint reports a name collision.
+#[utoipa::path(
+ post,
+ path = "/properties/tags/merge",
+ request_body = MergeTagRequest,
+ responses(
+ (status = 200, description = "Label merged into the team label", body = PropertyOptionResponse),
+ (status = 400, description = "Invalid request"),
+ (status = 403, description = "Team membership required"),
+ (status = 404, description = "Either label was not found in the expected tag set"),
+ (status = 500, description = "Internal server error")
+ ),
+ tag = "Properties"
+)]
+#[tracing::instrument(
+ skip(state, user, team),
+ fields(option_id = %request.option_id, target_option_id = %request.target_option_id),
+ err
+)]
+pub async fn merge_tag<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+ team: PropertyTeamExtractor<A, Auth>,
+ Json(request): Json<MergeTagRequest>,
+) -> Result<Json<PropertyOptionResponse>, TagsError> {
+ let user = user.authorization.user.macro_user_id;
+ let option = state
+ .properties_service
+ .merge_tag_option(
+ &user,
+ team.entity_access_receipt.as_ref(),
+ request.option_id,
+ request.target_option_id,
+ )
+ .await?;
+
+ Ok(Json(option.into()))
+}
diff --git a/crates/properties/src/inbound/axum_router/test.rs b/crates/properties/src/inbound/axum_router/test.rs
index c772bf4e7a..4d7397bdaa 100644
--- a/crates/properties/src/inbound/axum_router/test.rs
+++ b/crates/properties/src/inbound/axum_router/test.rs
@@ -67,9 +67,22 @@ enum AccessCall {
#[derive(Clone, Debug, Default)]
struct FakeEntityAccessService {
calls: Arc<Mutex<Vec<AccessCall>>>,
+ team: Option<UserTeamInfo>,
}
impl FakeEntityAccessService {
+ /// A service whose caller belongs to `team_id`, for the endpoints that
+ /// require team membership.
+ fn on_team(team_id: Uuid) -> Self {
+ Self {
+ calls: Arc::default(),
+ team: Some(UserTeamInfo {
+ team_id,
+ role: TeamRole::Member,
+ }),
+ }
+ }
+
fn calls(&self) -> Vec<AccessCall> {
self.calls.lock().expect("calls lock poisoned").clone()
}
@@ -200,7 +213,7 @@ impl EntityAccessService for FakeEntityAccessService {
self.record(AccessCall::UserTeam {
user_id: user_id.as_ref().to_string(),
});
- Ok(None)
+ Ok(self.team)
}
}
@@ -569,3 +582,234 @@ async fn bulk_options_across_entities_skips_denied_and_applies_granted() {
assert_eq!(results[1]["status"], "applied");
assert_eq!(results[1]["option_ids"], serde_json::json!([option_id]));
}
+
+/// A tag definition owned by `owner`, for the promote/merge endpoint tests.
+fn tag_def(
+ id: Uuid,
+ owner: models_properties::PropertyOwner,
+) -> models_properties::service::property_definition::PropertyDefinition {
+ models_properties::service::property_definition::PropertyDefinition {
+ id,
+ owner,
+ display_name: "Tags".to_string(),
+ data_type: models_properties::DataType::Tag,
+ is_multi_select: true,
+ specific_entity_type: None,
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ is_system: false,
+ is_metadata: false,
+ }
+}
+
+fn tag_option(
+ id: Uuid,
+ property_definition_id: Uuid,
+ value: &str,
+ color: &str,
+) -> models_properties::service::property_option::PropertyOption {
+ models_properties::service::property_option::PropertyOption {
+ id,
+ property_definition_id,
+ display_order: 0,
+ value: models_properties::service::property_option::PropertyOptionValue::String(
+ value.to_string(),
+ ),
+ color: Some(color.to_string()),
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ }
+}
+
+/// Wire a mock repo up to the reads promote makes before it writes.
+fn tag_promotion_repo(
+ personal_definition_id: Uuid,
+ team_definition_id: Uuid,
+ option_id: Uuid,
+) -> MockPropertiesRepo {
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_option().returning(move |_| {
+ Box::pin(async move {
+ Ok(Some(tag_option(
+ option_id,
+ personal_definition_id,
+ "Urgent",
+ "#ff0000",
+ )))
+ })
+ });
+ repo.expect_get_tag_definition().returning(move |_| {
+ Box::pin(async move {
+ Ok(Some(tag_def(
+ personal_definition_id,
+ models_properties::PropertyOwner::User {
+ user_id: VALID_USER_ID.to_string(),
+ },
+ )))
+ })
+ });
+ repo.expect_get_or_create_tag_definition()
+ .returning(move |_| {
+ Box::pin(async move {
+ Ok(crate::domain::model::GetOrCreateTagDefinitionResult {
+ definition: tag_def(
+ team_definition_id,
+ models_properties::PropertyOwner::Team {
+ team_id: Uuid::from_u128(0x7EA3),
+ },
+ ),
+ created: false,
+ })
+ })
+ });
+ repo
+}
+
+fn json_post(uri: &str, body: serde_json::Value) -> Request<Body> {
+ Request::builder()
+ .method("POST")
+ .uri(uri)
+ .header(header::AUTHORIZATION, "Bearer valid")
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(Body::from(body.to_string()))
+ .expect("request should be valid")
+}
+
+#[tokio::test]
+async fn promote_tag_conflict_returns_the_team_label_the_caller_can_merge_into() {
+ let personal_definition_id = Uuid::from_u128(0x9001);
+ let team_definition_id = Uuid::from_u128(0x9002);
+ let option_id = Uuid::from_u128(0x9003);
+ let conflict_id = Uuid::from_u128(0x9004);
+
+ let mut repo = tag_promotion_repo(personal_definition_id, team_definition_id, option_id);
+ repo.expect_promote_tag_option().returning(move |_, _, _| {
+ Box::pin(async move {
+ Ok(crate::domain::model::TagPromotionOutcome::Conflict(
+ tag_option(conflict_id, team_definition_id, "urgent", "#00ff00"),
+ ))
+ })
+ });
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ None::<MockPermissionService>,
+ None::<MockNotificationService>,
+ );
+ let router = properties_router(
+ service,
+ FakeEntityAccessService::on_team(Uuid::from_u128(0x7EA3)),
+ );
+
+ let response = router
+ .oneshot(json_post(
+ "/tags/promote",
+ serde_json::json!({ "option_id": option_id }),
+ ))
+ .await
+ .expect("request should complete");
+ assert_eq!(response.status(), StatusCode::CONFLICT);
+
+ // The front end prompts with this label, then confirms via /tags/merge.
+ let json: serde_json::Value =
+ serde_json::from_str(&response_body(response).await).expect("json body");
+ assert_eq!(json["conflicting_option"]["id"], conflict_id.to_string());
+ assert_eq!(
+ json["conflicting_option"]["value"],
+ serde_json::json!({"type": "string", "value": "urgent"})
+ );
+ assert_eq!(json["conflicting_option"]["color"], "#00ff00");
+ assert!(json["message"].is_string());
+}
+
+#[tokio::test]
+async fn promote_tag_returns_the_label_hanging_off_the_team_definition() {
+ let personal_definition_id = Uuid::from_u128(0x9101);
+ let team_definition_id = Uuid::from_u128(0x9102);
+ let option_id = Uuid::from_u128(0x9103);
+
+ let mut repo = tag_promotion_repo(personal_definition_id, team_definition_id, option_id);
+ repo.expect_promote_tag_option().returning(move |_, _, _| {
+ Box::pin(async move {
+ Ok(crate::domain::model::TagPromotionOutcome::Promoted(
+ crate::domain::model::TagRemapOutcome {
+ option: tag_option(option_id, team_definition_id, "Urgent", "#ff0000"),
+ mutations: Vec::new(),
+ },
+ ))
+ })
+ });
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ None::<MockPermissionService>,
+ None::<MockNotificationService>,
+ );
+ let router = properties_router(
+ service,
+ FakeEntityAccessService::on_team(Uuid::from_u128(0x7EA3)),
+ );
+
+ let response = router
+ .oneshot(json_post(
+ "/tags/promote",
+ serde_json::json!({ "option_id": option_id }),
+ ))
+ .await
+ .expect("request should complete");
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let json: serde_json::Value =
+ serde_json::from_str(&response_body(response).await).expect("json body");
+ assert_eq!(json["id"], option_id.to_string());
+ assert_eq!(
+ json["propertyDefinitionId"],
+ team_definition_id.to_string(),
+ "the option id survives, the owning definition is the team's"
+ );
+}
+
+#[tokio::test]
+async fn promote_tag_without_a_team_is_forbidden() {
+ let personal_definition_id = Uuid::from_u128(0x9201);
+ let option_id = Uuid::from_u128(0x9202);
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_option().returning(move |_| {
+ Box::pin(async move {
+ Ok(Some(tag_option(
+ option_id,
+ personal_definition_id,
+ "Urgent",
+ "#ff0000",
+ )))
+ })
+ });
+ repo.expect_get_tag_definition().returning(move |_| {
+ Box::pin(async move {
+ Ok(Some(tag_def(
+ personal_definition_id,
+ models_properties::PropertyOwner::User {
+ user_id: VALID_USER_ID.to_string(),
+ },
+ )))
+ })
+ });
+ repo.expect_promote_tag_option().never();
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ None::<MockPermissionService>,
+ None::<MockNotificationService>,
+ );
+ let router = properties_router(service, FakeEntityAccessService::default());
+
+ let response = router
+ .oneshot(json_post(
+ "/tags/promote",
+ serde_json::json!({ "option_id": option_id }),
+ ))
+ .await
+ .expect("request should complete");
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+}
diff --git a/crates/properties/src/outbound.rs b/crates/properties/src/outbound.rs
index 720bce5955..d2a94ba96c 100644
--- a/crates/properties/src/outbound.rs
+++ b/crates/properties/src/outbound.rs
@@ -16,6 +16,9 @@ pub mod permission_service;
pub mod properties_pg_repo;
pub mod property_definition_queries;
pub mod property_option_queries;
+pub mod tag_promotion_queries;
+#[cfg(test)]
+mod tag_promotion_test;
pub mod task_property_queries;
#[cfg(test)]
pub mod test;
diff --git a/crates/properties/src/outbound/entity_property_queries.rs b/crates/properties/src/outbound/entity_property_queries.rs
index c5af634460..7effd1620b 100644
--- a/crates/properties/src/outbound/entity_property_queries.rs
+++ b/crates/properties/src/outbound/entity_property_queries.rs
@@ -9,18 +9,18 @@ use crate::domain::model::{
EntityPropertyMutationSnapshot, EntityPropertyOptionSelection, EntityPropertyOptionUpdate,
};
-struct EntityPropertyMutationRow {
- id: Uuid,
- entity_id: String,
- entity_type: EntityType,
- property_definition_id: Uuid,
- value: Option<serde_json::Value>,
- created_at: chrono::DateTime<chrono::Utc>,
- updated_at: chrono::DateTime<chrono::Utc>,
+pub(super) struct EntityPropertyMutationRow {
+ pub(super) id: Uuid,
+ pub(super) entity_id: String,
+ pub(super) entity_type: EntityType,
+ pub(super) property_definition_id: Uuid,
+ pub(super) value: Option<serde_json::Value>,
+ pub(super) created_at: chrono::DateTime<chrono::Utc>,
+ pub(super) updated_at: chrono::DateTime<chrono::Utc>,
}
impl EntityPropertyMutationRow {
- fn into_snapshot(self) -> anyhow::Result<EntityPropertyMutationSnapshot> {
+ pub(super) fn into_snapshot(self) -> anyhow::Result<EntityPropertyMutationSnapshot> {
let value = match self.value {
Some(value) if !value.is_null() => Some(serde_json::from_value(value)?),
Some(_) | None => None,
diff --git a/crates/properties/src/outbound/properties_pg_repo.rs b/crates/properties/src/outbound/properties_pg_repo.rs
index caccb16cb8..4f85321828 100644
--- a/crates/properties/src/outbound/properties_pg_repo.rs
+++ b/crates/properties/src/outbound/properties_pg_repo.rs
@@ -11,11 +11,13 @@ use uuid::Uuid;
use super::{
entity_properties_get_query, entity_property_queries, metadata_queries,
- property_definition_queries, property_option_queries, task_property_queries,
+ property_definition_queries, property_option_queries, tag_promotion_queries,
+ task_property_queries,
};
use crate::domain::model::{
EntityPropertiesKey, EntityPropertyInfo, EntityPropertyMutationSnapshot,
- GetOrCreateTagDefinitionResult, PropertyDefinitionOwner, UpdatePropertyOptionOutcome,
+ GetOrCreateTagDefinitionResult, PropertyDefinitionOwner, TagPromotionOutcome, TagRemapOutcome,
+ UpdatePropertyOptionOutcome,
};
use crate::domain::ports::PropertiesRepo;
use models_properties::DataType;
@@ -233,6 +235,40 @@ impl PropertiesRepo for PropertiesPgRepo {
property_definition_queries::get_or_create_tag_definition(&self.pool, owner).await
}
+ #[tracing::instrument(skip(self))]
+ async fn promote_tag_option(
+ &self,
+ option_id: Uuid,
+ source_definition_id: Uuid,
+ target_definition_id: Uuid,
+ ) -> Result<TagPromotionOutcome, Self::Err> {
+ tag_promotion_queries::promote_tag_option(
+ &self.pool,
+ option_id,
+ source_definition_id,
+ target_definition_id,
+ )
+ .await
+ }
+
+ #[tracing::instrument(skip(self))]
+ async fn merge_tag_option(
+ &self,
+ source_option_id: Uuid,
+ source_definition_id: Uuid,
+ target_option_id: Uuid,
+ target_definition_id: Uuid,
+ ) -> Result<Option<TagRemapOutcome>, Self::Err> {
+ tag_promotion_queries::merge_tag_option(
+ &self.pool,
+ source_option_id,
+ source_definition_id,
+ target_option_id,
+ target_definition_id,
+ )
+ .await
+ }
+
#[tracing::instrument(skip(self))]
async fn count_valid_property_options(
&self,
diff --git a/crates/properties/src/outbound/tag_promotion_queries.rs b/crates/properties/src/outbound/tag_promotion_queries.rs
new file mode 100644
index 0000000000..34f6316d74
--- /dev/null
+++ b/crates/properties/src/outbound/tag_promotion_queries.rs
@@ -0,0 +1,370 @@
+//! Queries that move a personal label into a team tag set.
+//!
+//! Both operations rewrite the same two things atomically: which definition the
+//! label hangs off, and which option id every entity carrying it references.
+//! Promotion keeps the option id (so nothing else has to change), while a merge
+//! retargets entities onto an option the team already has.
+
+use models_properties::EntityType;
+use models_properties::db;
+use models_properties::service::property_option::PropertyOption;
+use sqlx::{Pool, Postgres, Transaction};
+use uuid::Uuid;
+
+use super::entity_property_queries::EntityPropertyMutationRow;
+use crate::domain::model::{TagPromotionOutcome, TagRemapOutcome};
+
+/// One entity holding the label being remapped.
+struct AffectedEntity {
+ entity_id: String,
+ entity_type: EntityType,
+}
+
+/// Move a personal tag option into a team tag definition, keeping its id.
+///
+/// The target definition row is locked first so concurrent promotions into the
+/// same team serialize: the second caller reads the first caller's label and
+/// gets a [`TagPromotionOutcome::Conflict`] rather than adding a duplicate.
+#[tracing::instrument(skip(pool), err)]
+pub async fn promote_tag_option(
+ pool: &Pool<Postgres>,
+ option_id: Uuid,
+ source_definition_id: Uuid,
+ target_definition_id: Uuid,
+) -> anyhow::Result<TagPromotionOutcome> {
+ let mut tx = pool.begin().await?;
+
+ lock_definition(&mut tx, target_definition_id).await?;
+
+ let Some(source) = load_option(&mut tx, option_id, source_definition_id).await? else {
+ anyhow::bail!("tag option {option_id} is not owned by definition {source_definition_id}");
+ };
+ let source_value = match &source.value {
+ models_properties::service::property_option::PropertyOptionValue::String(value) => {
+ value.clone()
+ }
+ models_properties::service::property_option::PropertyOptionValue::Number(_) => {
+ anyhow::bail!("tag option {option_id} does not hold a string value")
+ }
+ };
+
+ if let Some(conflict) =
+ find_option_by_name(&mut tx, target_definition_id, &source_value).await?
+ {
+ tx.rollback().await?;
+ return Ok(TagPromotionOutcome::Conflict(conflict));
+ }
+
+ // Append the label to the end of the team's set rather than carrying the
+ // personal display order over, which would collide with an existing team
+ // label at the same position.
+ let promoted = sqlx::query_as!(
+ db::PropertyOption,
+ r#"
+ UPDATE property_options
+ SET property_definition_id = $2,
+ display_order = COALESCE(
+ (
+ SELECT MAX(display_order) + 1
+ FROM property_options
+ WHERE property_definition_id = $2
+ ),
+ 0
+ ),
+ updated_at = NOW()
+ WHERE id = $1
+ RETURNING
+ id,
+ property_definition_id,
+ display_order,
+ number_value,
+ string_value,
+ color,
+ created_at,
+ updated_at
+ "#,
+ option_id,
+ target_definition_id,
+ )
+ .fetch_one(&mut *tx)
+ .await?;
+
+ let mutations = remap_entity_values(
+ &mut tx,
+ source_definition_id,
+ option_id,
+ target_definition_id,
+ option_id,
+ )
+ .await?;
+
+ tx.commit().await?;
+
+ Ok(TagPromotionOutcome::Promoted(TagRemapOutcome {
+ option: promoted.try_into()?,
+ mutations,
+ }))
+}
+
+/// Retag every entity carrying a personal label with an existing team label,
+/// then delete the personal option.
+///
+/// Returns `None` when the target option does not belong to the target
+/// definition, so the caller can report a missing option rather than remapping
+/// entities onto a label from another set.
+#[tracing::instrument(skip(pool), err)]
+pub async fn merge_tag_option(
+ pool: &Pool<Postgres>,
+ source_option_id: Uuid,
+ source_definition_id: Uuid,
+ target_option_id: Uuid,
+ target_definition_id: Uuid,
+) -> anyhow::Result<Option<TagRemapOutcome>> {
+ let mut tx = pool.begin().await?;
+
+ lock_definition(&mut tx, target_definition_id).await?;
+
+ let Some(target) = load_option(&mut tx, target_option_id, target_definition_id).await? else {
+ tx.rollback().await?;
+ return Ok(None);
+ };
+ if load_option(&mut tx, source_option_id, source_definition_id)
+ .await?
+ .is_none()
+ {
+ anyhow::bail!(
+ "tag option {source_option_id} is not owned by definition {source_definition_id}"
+ );
+ }
+
+ let mutations = remap_entity_values(
+ &mut tx,
+ source_definition_id,
+ source_option_id,
+ target_definition_id,
+ target_option_id,
+ )
+ .await?;
+
+ sqlx::query!(
+ "DELETE FROM property_options WHERE id = $1",
+ source_option_id
+ )
+ .execute(&mut *tx)
+ .await?;
+
+ tx.commit().await?;
+
+ Ok(Some(TagRemapOutcome {
+ option: target,
+ mutations,
+ }))
+}
+
+/// Take the definition-level lock that serializes writers competing for the
+/// same label name in one tag set.
+async fn lock_definition(
+ tx: &mut Transaction<'_, Postgres>,
+ definition_id: Uuid,
+) -> anyhow::Result<()> {
+ sqlx::query_scalar!(
+ "SELECT id FROM property_definitions WHERE id = $1 FOR UPDATE",
+ definition_id
+ )
+ .fetch_optional(&mut **tx)
+ .await?;
+ Ok(())
+}
+
+/// Read one option, scoped to the definition it must belong to.
+async fn load_option(
+ tx: &mut Transaction<'_, Postgres>,
+ option_id: Uuid,
+ definition_id: Uuid,
+) -> anyhow::Result<Option<PropertyOption>> {
+ let row = sqlx::query_as!(
+ db::PropertyOption,
+ r#"
+ SELECT
+ id,
+ property_definition_id,
+ display_order,
+ number_value,
+ string_value,
+ color,
+ created_at,
+ updated_at
+ FROM property_options
+ WHERE id = $1 AND property_definition_id = $2
+ "#,
+ option_id,
+ definition_id,
+ )
+ .fetch_optional(&mut **tx)
+ .await?;
+
+ Ok(row.map(TryInto::try_into).transpose()?)
+}
+
+/// Find a label in the set whose name matches `value`, compared the way a
+/// person reads label names: trimmed and case-insensitive.
+async fn find_option_by_name(
+ tx: &mut Transaction<'_, Postgres>,
+ definition_id: Uuid,
+ value: &str,
+) -> anyhow::Result<Option<PropertyOption>> {
+ let row = sqlx::query_as!(
+ db::PropertyOption,
+ r#"
+ SELECT
+ id,
+ property_definition_id,
+ display_order,
+ number_value,
+ string_value,
+ color,
+ created_at,
+ updated_at
+ FROM property_options
+ WHERE property_definition_id = $1
+ AND string_value IS NOT NULL
+ AND LOWER(BTRIM(string_value)) = LOWER(BTRIM($2))
+ ORDER BY display_order, id
+ LIMIT 1
+ "#,
+ definition_id,
+ value,
+ )
+ .fetch_optional(&mut **tx)
+ .await?;
+
+ Ok(row.map(TryInto::try_into).transpose()?)
+}
+
+/// Move every entity's reference to `source_option_id` under
+/// `source_definition_id` onto `target_option_id` under
+/// `target_definition_id`, returning the post-write state of each target row.
+///
+/// The target rows are the ones search and Soup rebuild from, so only those are
+/// returned; the source rows are left attached with the option stripped, which
+/// is how [`super::property_option_queries::delete_property_option`] already
+/// leaves a removed option.
+async fn remap_entity_values(
+ tx: &mut Transaction<'_, Postgres>,
+ source_definition_id: Uuid,
+ source_option_id: Uuid,
+ target_definition_id: Uuid,
+ target_option_id: Uuid,
+) -> anyhow::Result<Vec<crate::domain::model::EntityPropertyMutationSnapshot>> {
+ // Lock the source rows in a stable order so two remaps touching the same
+ // entities can't deadlock against each other.
+ let affected = sqlx::query_as!(
+ AffectedEntity,
+ r#"
+ SELECT entity_id, entity_type as "entity_type: EntityType"
+ FROM entity_properties
+ WHERE property_definition_id = $1
+ AND values ->> 'type' = 'SelectOption'
+ AND values -> 'value' @> jsonb_build_array($2::text)
+ ORDER BY entity_id, entity_type
+ FOR UPDATE
+ "#,
+ source_definition_id,
+ source_option_id.to_string(),
+ )
+ .fetch_all(&mut **tx)
+ .await?;
+
+ if affected.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let row_ids: Vec<Uuid> = affected
+ .iter()
+ .map(|_| macro_uuid::generate_uuid_v7())
+ .collect();
+ let entity_ids: Vec<String> = affected
+ .iter()
+ .map(|entity| entity.entity_id.clone())
+ .collect();
+ let entity_types: Vec<EntityType> = affected.iter().map(|entity| entity.entity_type).collect();
+
+ // Attach the target label, merging into whatever the entity already has for
+ // the target definition instead of replacing it.
+ let rows = sqlx::query_as!(
+ EntityPropertyMutationRow,
+ r#"
+ INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
+ SELECT
+ source.id,
+ source.entity_id,
+ source.entity_type,
+ $4,
+ jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))
+ FROM UNNEST($1::uuid[], $2::text[], $3::property_entity_type[])
+ AS source(id, entity_id, entity_type)
+ ON CONFLICT (entity_id, entity_type, property_definition_id)
+ DO UPDATE SET
+ values = CASE
+ WHEN entity_properties.values ->> 'type' = 'SelectOption'
+ AND entity_properties.values -> 'value' @> jsonb_build_array($5::text)
+ THEN entity_properties.values
+ WHEN entity_properties.values ->> 'type' = 'SelectOption'
+ THEN jsonb_set(
+ entity_properties.values,
+ '{value}',
+ (entity_properties.values -> 'value') || jsonb_build_array($5::text)
+ )
+ ELSE jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))
+ END,
+ updated_at = NOW()
+ RETURNING
+ id,
+ entity_id,
+ entity_type as "entity_type: EntityType",
+ property_definition_id,
+ values as "value: serde_json::Value",
+ created_at,
+ updated_at
+ "#,
+ &row_ids,
+ &entity_ids,
+ &entity_types as &[EntityType],
+ target_definition_id,
+ target_option_id.to_string(),
+ )
+ .fetch_all(&mut **tx)
+ .await?;
+
+ // Drop the label from the set it came from. For a promotion the option id is
+ // unchanged, so this is what actually moves it between the two definitions.
+ sqlx::query!(
+ r#"
+ UPDATE entity_properties
+ SET values = jsonb_set(
+ values,
+ '{value}',
+ COALESCE(
+ (
+ SELECT jsonb_agg(elem)
+ FROM jsonb_array_elements(values -> 'value') AS elem
+ WHERE elem <> to_jsonb($2::text)
+ ),
+ '[]'::jsonb
+ )
+ ),
+ updated_at = NOW()
+ WHERE property_definition_id = $1
+ AND values ->> 'type' = 'SelectOption'
+ AND values -> 'value' @> jsonb_build_array($2::text)
+ "#,
+ source_definition_id,
+ source_option_id.to_string(),
+ )
+ .execute(&mut **tx)
+ .await?;
+
+ rows.into_iter()
+ .map(EntityPropertyMutationRow::into_snapshot)
+ .collect()
+}
diff --git a/crates/properties/src/outbound/tag_promotion_test.rs b/crates/properties/src/outbound/tag_promotion_test.rs
new file mode 100644
index 0000000000..38d9e2a44d
--- /dev/null
+++ b/crates/properties/src/outbound/tag_promotion_test.rs
@@ -0,0 +1,425 @@
+//! Integration tests for sharing a personal label with a team.
+
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use models_properties::service::property_option::PropertyOptionValue;
+use models_properties::service::property_value::PropertyValue;
+use models_properties::{DataType, EntityType};
+use sqlx::{Pool, Postgres};
+use uuid::Uuid;
+
+use super::properties_pg_repo::PropertiesPgRepo;
+use crate::domain::model::{PropertyDefinitionOwner, TagPromotionOutcome};
+use crate::domain::ports::PropertiesRepo;
+
+const USER1_TAG_DEFINITION: &str = "aa111111-1111-1111-1111-111111111111";
+const TEAM1_TAG_DEFINITION: &str = "aa222222-2222-2222-2222-222222222222";
+const USER1_BUG_REPORT: &str = "0aa11111-1111-1111-1111-111111111111";
+const USER1_MOBILE: &str = "0aa11111-1111-1111-1111-111111111112";
+const TEAM1_URGENT: &str = "0aa22222-2222-2222-2222-222222222222";
+
+fn uuid(value: &str) -> Uuid {
+ value.parse().unwrap()
+}
+
+/// The option ids stored on one entity's value for a property definition.
+async fn stored_option_ids(
+ pool: &Pool<Postgres>,
+ entity_id: &str,
+ definition_id: Uuid,
+) -> Vec<Uuid> {
+ let value = sqlx::query_scalar!(
+ r#"
+ SELECT values as "values: serde_json::Value"
+ FROM entity_properties
+ WHERE entity_id = $1 AND entity_type = 'DOCUMENT' AND property_definition_id = $2
+ "#,
+ entity_id,
+ definition_id,
+ )
+ .fetch_optional(pool)
+ .await
+ .unwrap()
+ .flatten();
+
+ match value.map(serde_json::from_value::<PropertyValue>) {
+ Some(Ok(PropertyValue::SelectOption(ids))) => ids,
+ _ => Vec::new(),
+ }
+}
+
+/// Attach `option_id` of `definition_id` to a document.
+async fn tag_document(
+ pool: &Pool<Postgres>,
+ entity_id: &str,
+ definition_id: Uuid,
+ option_ids: &[Uuid],
+) {
+ let value = serde_json::json!({
+ "type": "SelectOption",
+ "value": option_ids.iter().map(|id| id.to_string()).collect::<Vec<_>>(),
+ });
+ sqlx::query!(
+ r#"
+ INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
+ VALUES ($1, $2, 'DOCUMENT', $3, $4)
+ ON CONFLICT (entity_id, entity_type, property_definition_id)
+ DO UPDATE SET values = $4
+ "#,
+ macro_uuid::generate_uuid_v7(),
+ entity_id,
+ definition_id,
+ value,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties", "tags"))
+)]
+async fn promote_moves_label_and_retags_entities(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ let source = uuid(USER1_TAG_DEFINITION);
+ let target = uuid(TEAM1_TAG_DEFINITION);
+ let option = uuid(USER1_BUG_REPORT);
+
+ let TagPromotionOutcome::Promoted(remap) =
+ repo.promote_tag_option(option, source, target).await?
+ else {
+ panic!("expected the promotion to succeed");
+ };
+
+ // The option keeps its id, so entities that already carry it stay tagged.
+ assert_eq!(remap.option.id, option);
+ assert_eq!(remap.option.property_definition_id, target);
+ assert_eq!(
+ remap.option.value,
+ PropertyOptionValue::String("bug-report".to_string())
+ );
+ // Appended after the team's existing label rather than reusing its order.
+ assert_eq!(remap.option.display_order, 1);
+
+ // tagdoc1 already had the team's `urgent` label; the promoted one is added.
+ assert_eq!(
+ stored_option_ids(&pool, "tagdoc1", target).await,
+ vec![uuid(TEAM1_URGENT), option]
+ );
+ assert!(stored_option_ids(&pool, "tagdoc1", source).await.is_empty());
+
+ assert_eq!(remap.mutations.len(), 1);
+ assert_eq!(remap.mutations[0].property.entity_id, "tagdoc1");
+ assert_eq!(
+ remap.mutations[0].property.property_definition_id, target,
+ "events must point at the team definition search rebuilds from"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties", "tags"))
+)]
+async fn promote_attaches_the_team_property_when_absent(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ let source = uuid(USER1_TAG_DEFINITION);
+ let target = uuid(TEAM1_TAG_DEFINITION);
+ let option = uuid(USER1_MOBILE);
+
+ // A document tagged only with the personal label has no team tag row yet.
+ tag_document(&pool, "untagged-by-team", source, &[option]).await;
+
+ let TagPromotionOutcome::Promoted(remap) =
+ repo.promote_tag_option(option, source, target).await?
+ else {
+ panic!("expected the promotion to succeed");
+ };
+
+ assert_eq!(
+ stored_option_ids(&pool, "untagged-by-team", target).await,
+ vec![option]
+ );
+ assert!(
+ stored_option_ids(&pool, "untagged-by-team", source)
+ .await
+ .is_empty()
+ );
+ assert_eq!(remap.mutations.len(), 1);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties", "tags"))
+)]
+async fn promote_reports_a_case_insensitive_name_collision(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ let source = uuid(USER1_TAG_DEFINITION);
+ let target = uuid(TEAM1_TAG_DEFINITION);
+
+ let clashing = repo
+ .create_property_option(
+ source,
+ 2,
+ PropertyOptionValue::String(" URGENT ".to_string()),
+ Some("#00ff00".to_string()),
+ )
+ .await?;
+
+ let TagPromotionOutcome::Conflict(conflict) =
+ repo.promote_tag_option(clashing.id, source, target).await?
+ else {
+ panic!("expected a conflict with the team's `urgent` label");
+ };
+ assert_eq!(conflict.id, uuid(TEAM1_URGENT));
+
+ // The rejected promotion leaves both tag sets exactly as they were.
+ let promoted = repo.get_property_option(clashing.id).await?.unwrap();
+ assert_eq!(promoted.property_definition_id, source);
+ assert_eq!(repo.get_property_options(target).await?.len(), 1);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties", "tags"))
+)]
+async fn concurrent_promotions_of_one_name_produce_a_single_team_label(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ let target = uuid(TEAM1_TAG_DEFINITION);
+ let user1_definition = uuid(USER1_TAG_DEFINITION);
+ let user2_definition = uuid("aa333333-3333-3333-3333-333333333333");
+
+ // Two teammates each hold a personal label for the same thing, spelled
+ // differently, and share it at the same moment.
+ let first = repo
+ .create_property_option(
+ user1_definition,
+ 0,
+ PropertyOptionValue::String("Design Review".to_string()),
+ Some("#ff0000".to_string()),
+ )
+ .await?;
+ let second = repo
+ .create_property_option(
+ user2_definition,
+ 0,
+ PropertyOptionValue::String("design review".to_string()),
+ Some("#00ff00".to_string()),
+ )
+ .await?;
+
+ let (first_outcome, second_outcome) = tokio::join!(
+ repo.promote_tag_option(first.id, user1_definition, target),
+ repo.promote_tag_option(second.id, user2_definition, target),
+ );
+
+ // Whoever loses the race is told to merge instead of adding a duplicate.
+ let outcomes = [first_outcome?, second_outcome?];
+ let promoted: Vec<_> = outcomes
+ .iter()
+ .filter_map(|outcome| match outcome {
+ TagPromotionOutcome::Promoted(remap) => Some(remap.option.id),
+ TagPromotionOutcome::Conflict(_) => None,
+ })
+ .collect();
+ let conflicts: Vec<_> = outcomes
+ .iter()
+ .filter_map(|outcome| match outcome {
+ TagPromotionOutcome::Conflict(conflict) => Some(conflict.id),
+ TagPromotionOutcome::Promoted(_) => None,
+ })
+ .collect();
+
+ assert_eq!(promoted.len(), 1, "exactly one promotion may win");
+ assert_eq!(conflicts, promoted, "the loser is pointed at the winner");
+
+ let team_labels = repo.get_property_options(target).await?;
+ assert_eq!(
+ team_labels
+ .iter()
+ .filter(|label| matches!(
+ &label.value,
+ PropertyOptionValue::String(value) if value.eq_ignore_ascii_case("design review")
+ ))
+ .count(),
+ 1
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties", "tags"))
+)]
+async fn merge_retags_entities_onto_the_team_label(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ let source = uuid(USER1_TAG_DEFINITION);
+ let target = uuid(TEAM1_TAG_DEFINITION);
+ let personal = uuid(USER1_BUG_REPORT);
+ let team = uuid(TEAM1_URGENT);
+
+ // One document has only the personal label, one has both.
+ tag_document(&pool, "personal-only", source, &[personal]).await;
+
+ let remap = repo
+ .merge_tag_option(personal, source, team, target)
+ .await?
+ .expect("the team label exists");
+
+ assert_eq!(remap.option.id, team);
+ assert_eq!(
+ remap.option.value,
+ PropertyOptionValue::String("urgent".to_string()),
+ "the team label's name wins"
+ );
+
+ // The document that already had the team label is not double-tagged.
+ assert_eq!(
+ stored_option_ids(&pool, "tagdoc1", target).await,
+ vec![team]
+ );
+ assert_eq!(
+ stored_option_ids(&pool, "personal-only", target).await,
+ vec![team]
+ );
+ assert!(stored_option_ids(&pool, "tagdoc1", source).await.is_empty());
+ assert!(
+ stored_option_ids(&pool, "personal-only", source)
+ .await
+ .is_empty()
+ );
+
+ assert!(
+ repo.get_property_option(personal).await?.is_none(),
+ "the personal label is retired"
+ );
+ assert_eq!(remap.mutations.len(), 2);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties", "tags"))
+)]
+async fn merge_rejects_a_target_outside_the_team_tag_set(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ let source = uuid(USER1_TAG_DEFINITION);
+ let target = uuid(TEAM1_TAG_DEFINITION);
+ let personal = uuid(USER1_BUG_REPORT);
+ // Another user's personal label, which is not in the team's set.
+ let foreign = uuid("0aa33333-3333-3333-3333-333333333333");
+
+ assert!(
+ repo.merge_tag_option(personal, source, foreign, target)
+ .await?
+ .is_none()
+ );
+
+ assert!(repo.get_property_option(personal).await?.is_some());
+ assert_eq!(
+ stored_option_ids(&pool, "tagdoc1", source).await,
+ vec![personal],
+ "a rejected merge leaves the personal tagging alone"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties", "tags"))
+)]
+async fn promoted_label_reads_back_from_the_team_tag_set(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ let option = uuid(USER1_BUG_REPORT);
+
+ repo.promote_tag_option(
+ option,
+ uuid(USER1_TAG_DEFINITION),
+ uuid(TEAM1_TAG_DEFINITION),
+ )
+ .await?;
+
+ // user3 is on Team 1 but never had the personal label, so this asserts the
+ // whole point of promotion: the label is now theirs to see and use.
+ let user3 = macro_user_id::user_id::MacroUserIdStr::try_from("macro|[email protected]")?;
+ let visible = repo.get_caller_tag_definitions(user3.as_ref()).await?;
+ let team_labels = visible
+ .iter()
+ .find(|set| set.definition.id == uuid(TEAM1_TAG_DEFINITION))
+ .expect("user3 sees the team tag set");
+ assert!(
+ team_labels
+ .property_options
+ .iter()
+ .any(|label| label.id == option)
+ );
+
+ let tagged = repo
+ .get_entity_properties("tagdoc1", EntityType::Document, user3.as_ref())
+ .await?;
+ let team_tags = tagged
+ .iter()
+ .find(|property| {
+ property.data_type == DataType::Tag
+ && property.property_definition_id == uuid(TEAM1_TAG_DEFINITION)
+ })
+ .expect("the team tag property is attached to tagdoc1");
+ assert!(matches!(
+ &team_tags.value,
+ Some(PropertyValue::SelectOption(ids)) if ids.contains(&option)
+ ));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties", "tags"))
+)]
+async fn promote_provisions_a_team_tag_set_on_demand(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ // Team 2 has no tag definition in the fixtures.
+ let team2 = uuid("0e000000-0000-0000-0000-000000000002");
+ let provisioned = repo
+ .get_or_create_tag_definition(PropertyDefinitionOwner::Team(team2))
+ .await?;
+ assert!(provisioned.created);
+
+ let option = uuid(USER1_BUG_REPORT);
+ let TagPromotionOutcome::Promoted(remap) = repo
+ .promote_tag_option(
+ option,
+ uuid(USER1_TAG_DEFINITION),
+ provisioned.definition.id,
+ )
+ .await?
+ else {
+ panic!("an empty team tag set cannot collide");
+ };
+
+ assert_eq!(remap.option.display_order, 0);
+ assert_eq!(
+ stored_option_ids(&pool, "tagdoc1", provisioned.definition.id).await,
+ vec![option]
+ );
+
+ Ok(())
+}
diff --git a/crates/properties_service/src/api/swagger.rs b/crates/properties_service/src/api/swagger.rs
index 632397d8c8..0002afd692 100644
--- a/crates/properties_service/src/api/swagger.rs
+++ b/crates/properties_service/src/api/swagger.rs
@@ -8,7 +8,10 @@ use properties::inbound::axum_router::{
EntityPropertiesResponse, EntityPropertyOptionSelectionResponse,
EntityPropertyOptionUpdateRequest, EntityQueryParams, SetEntityPropertyRequest,
},
- tags::{EnsureTagSetRequest, TagScope, TagSetResponse},
+ tags::{
+ EnsureTagSetRequest, MergeTagRequest, PromoteTagRequest, TagPromotionConflictResponse,
+ TagScope, TagSetResponse,
+ },
};
use utoipa::OpenApi;
@@ -30,6 +33,8 @@ use utoipa::OpenApi;
properties::inbound::axum_router::options::delete_property_option,
properties::inbound::axum_router::tags::list_tags,
properties::inbound::axum_router::tags::ensure_tag_set,
+ properties::inbound::axum_router::tags::promote_tag,
+ properties::inbound::axum_router::tags::merge_tag,
// Entity properties
properties::inbound::axum_router::entities::get_entity_properties,
properties::inbound::axum_router::entities::get_bulk_entity_properties,
@@ -77,6 +82,9 @@ use utoipa::OpenApi;
TagScope,
TagSetResponse,
EnsureTagSetRequest,
+ PromoteTagRequest,
+ MergeTagRequest,
+ TagPromotionConflictResponse,
)
),
tags(
diff --git a/packages/sdk/generated/properties/index.ts b/packages/sdk/generated/properties/index.ts
index b777397d31..4569ed2910 100644
--- a/packages/sdk/generated/properties/index.ts
+++ b/packages/sdk/generated/properties/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AddEntityPropertyOptionData, AddEntityPropertyOptionErrors, AddEntityPropertyOptionResponse, AddEntityPropertyOptionResponses, AddNumberOptionRequest, AddPropertyOptionData, AddPropertyOptionErrors, AddPropertyOptionRequest, AddPropertyOptionResponse, AddPropertyOptionResponses, AddStringOptionRequest, BulkEntityOptionUpdateResult, BulkEntityOptionUpdateStatus, BulkEntityPropertiesRequest, BulkUpdateEntitiesPropertyOptionsData, BulkUpdateEntitiesPropertyOptionsErrors, BulkUpdateEntitiesPropertyOptionsRequest, BulkUpdateEntitiesPropertyOptionsResponse, BulkUpdateEntitiesPropertyOptionsResponse2, BulkUpdateEntitiesPropertyOptionsResponses, BulkUpdateEntityPropertyOptionsData, BulkUpdateEntityPropertyOptionsErrors, BulkUpdateEntityPropertyOptionsRequest, BulkUpdateEntityPropertyOptionsResponse, BulkUpdateEntityPropertyOptionsResponse2, BulkUpdateEntityPropertyOptionsResponses, ClientOptions, CreatePropertyDefinitionData, CreatePropertyDefinitionErrors, CreatePropertyDefinitionRequest, CreatePropertyDefinitionResponse, CreatePropertyDefinitionResponses, CreatePropertyScope, DataType, DeleteEntityPropertyData, DeleteEntityPropertyErrors, DeleteEntityPropertyResponse, DeleteEntityPropertyResponses, DeletePropertyDefinitionData, DeletePropertyDefinitionErrors, DeletePropertyDefinitionResponse, DeletePropertyDefinitionResponses, DeletePropertyOptionData, DeletePropertyOptionErrors, DeletePropertyOptionResponse, DeletePropertyOptionResponses, EnsureTagSetData, EnsureTagSetErrors, EnsureTagSetRequest, EnsureTagSetResponse, EnsureTagSetResponses, EntityPropertiesResponse, EntityProperty, EntityPropertyOptionSelectionResponse, EntityPropertyOptionUpdateRequest, EntityPropertyResponse, EntityPropertyWithDefinition, EntityPropertyWithDefinitionResponse, EntityQueryParams, EntityReference, EntityType, GetBulkEntityPropertiesData, GetBulkEntityPropertiesErrors, GetBulkEntityPropertiesResponse, GetBulkEntityPropertiesResponses, GetEntityPropertiesData, GetEntityPropertiesErrors, GetEntityPropertiesResponse, GetEntityPropertiesResponses, GetPropertyDefinitionData, GetPropertyDefinitionErrors, GetPropertyDefinitionResponse, GetPropertyDefinitionResponses, GetPropertyOptionsData, GetPropertyOptionsErrors, GetPropertyOptionsResponse, GetPropertyOptionsResponses, ListPropertiesData, ListPropertiesErrors, ListPropertiesQuery, ListPropertiesResponse, ListPropertiesResponses, ListTagsData, ListTagsErrors, ListTagsResponse, ListTagsResponses, PropertyDataType, PropertyDefinition, PropertyDefinitionDetailResponse, PropertyDefinitionResponse, PropertyDefinitionWithOptions, PropertyDefinitionWithOptionsResponse, PropertyOption, PropertyOptionResponse, PropertyOptionValue, PropertyOwner, PropertyScope, PropertyTargetEntityType, PropertyTargetReference, PropertyValue, RemoveEntityPropertyOptionData, RemoveEntityPropertyOptionErrors, RemoveEntityPropertyOptionResponse, RemoveEntityPropertyOptionResponses, SelectNumberOption, SelectStringOption, SetEntityPropertyData, SetEntityPropertyErrors, SetEntityPropertyRequest, SetEntityPropertyResponse, SetEntityPropertyResponses, SetPropertyValue, TagScope, TagSetResponse, UpdatePropertyOptionData, UpdatePropertyOptionErrors, UpdatePropertyOptionRequest, UpdatePropertyOptionResponse, UpdatePropertyOptionResponses } from './types.gen';
+export type { AddEntityPropertyOptionData, AddEntityPropertyOptionErrors, AddEntityPropertyOptionResponse, AddEntityPropertyOptionResponses, AddNumberOptionRequest, AddPropertyOptionData, AddPropertyOptionErrors, AddPropertyOptionRequest, AddPropertyOptionResponse, AddPropertyOptionResponses, AddStringOptionRequest, BulkEntityOptionUpdateResult, BulkEntityOptionUpdateStatus, BulkEntityPropertiesRequest, BulkUpdateEntitiesPropertyOptionsData, BulkUpdateEntitiesPropertyOptionsErrors, BulkUpdateEntitiesPropertyOptionsRequest, BulkUpdateEntitiesPropertyOptionsResponse, BulkUpdateEntitiesPropertyOptionsResponse2, BulkUpdateEntitiesPropertyOptionsResponses, BulkUpdateEntityPropertyOptionsData, BulkUpdateEntityPropertyOptionsErrors, BulkUpdateEntityPropertyOptionsRequest, BulkUpdateEntityPropertyOptionsResponse, BulkUpdateEntityPropertyOptionsResponse2, BulkUpdateEntityPropertyOptionsResponses, ClientOptions, CreatePropertyDefinitionData, CreatePropertyDefinitionErrors, CreatePropertyDefinitionRequest, CreatePropertyDefinitionResponse, CreatePropertyDefinitionResponses, CreatePropertyScope, DataType, DeleteEntityPropertyData, DeleteEntityPropertyErrors, DeleteEntityPropertyResponse, DeleteEntityPropertyResponses, DeletePropertyDefinitionData, DeletePropertyDefinitionErrors, DeletePropertyDefinitionResponse, DeletePropertyDefinitionResponses, DeletePropertyOptionData, DeletePropertyOptionErrors, DeletePropertyOptionResponse, DeletePropertyOptionResponses, EnsureTagSetData, EnsureTagSetErrors, EnsureTagSetRequest, EnsureTagSetResponse, EnsureTagSetResponses, EntityPropertiesResponse, EntityProperty, EntityPropertyOptionSelectionResponse, EntityPropertyOptionUpdateRequest, EntityPropertyResponse, EntityPropertyWithDefinition, EntityPropertyWithDefinitionResponse, EntityQueryParams, EntityReference, EntityType, GetBulkEntityPropertiesData, GetBulkEntityPropertiesErrors, GetBulkEntityPropertiesResponse, GetBulkEntityPropertiesResponses, GetEntityPropertiesData, GetEntityPropertiesErrors, GetEntityPropertiesResponse, GetEntityPropertiesResponses, GetPropertyDefinitionData, GetPropertyDefinitionErrors, GetPropertyDefinitionResponse, GetPropertyDefinitionResponses, GetPropertyOptionsData, GetPropertyOptionsErrors, GetPropertyOptionsResponse, GetPropertyOptionsResponses, ListPropertiesData, ListPropertiesErrors, ListPropertiesQuery, ListPropertiesResponse, ListPropertiesResponses, ListTagsData, ListTagsErrors, ListTagsResponse, ListTagsResponses, MergeTagData, MergeTagErrors, MergeTagRequest, MergeTagResponse, MergeTagResponses, PromoteTagData, PromoteTagError, PromoteTagErrors, PromoteTagRequest, PromoteTagResponse, PromoteTagResponses, PropertyDataType, PropertyDefinition, PropertyDefinitionDetailResponse, PropertyDefinitionResponse, PropertyDefinitionWithOptions, PropertyDefinitionWithOptionsResponse, PropertyOption, PropertyOptionResponse, PropertyOptionValue, PropertyOwner, PropertyScope, PropertyTargetEntityType, PropertyTargetReference, PropertyValue, RemoveEntityPropertyOptionData, RemoveEntityPropertyOptionErrors, RemoveEntityPropertyOptionResponse, RemoveEntityPropertyOptionResponses, SelectNumberOption, SelectStringOption, SetEntityPropertyData, SetEntityPropertyErrors, SetEntityPropertyRequest, SetEntityPropertyResponse, SetEntityPropertyResponses, SetPropertyValue, TagPromotionConflictResponse, TagScope, TagSetResponse, UpdatePropertyOptionData, UpdatePropertyOptionErrors, UpdatePropertyOptionRequest, UpdatePropertyOptionResponse, UpdatePropertyOptionResponses } from './types.gen';
diff --git a/packages/sdk/generated/properties/sdk.gen.ts b/packages/sdk/generated/properties/sdk.gen.ts
index 586878f877..8ec16563ee 100644
--- a/packages/sdk/generated/properties/sdk.gen.ts
+++ b/packages/sdk/generated/properties/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { AddEntityPropertyOptionData, AddEntityPropertyOptionErrors, AddEntityPropertyOptionResponses, AddPropertyOptionData, AddPropertyOptionErrors, AddPropertyOptionResponses, BulkUpdateEntitiesPropertyOptionsData, BulkUpdateEntitiesPropertyOptionsErrors, BulkUpdateEntitiesPropertyOptionsResponses, BulkUpdateEntityPropertyOptionsData, BulkUpdateEntityPropertyOptionsErrors, BulkUpdateEntityPropertyOptionsResponses, CreatePropertyDefinitionData, CreatePropertyDefinitionErrors, CreatePropertyDefinitionResponses, DeleteEntityPropertyData, DeleteEntityPropertyErrors, DeleteEntityPropertyResponses, DeletePropertyDefinitionData, DeletePropertyDefinitionErrors, DeletePropertyDefinitionResponses, DeletePropertyOptionData, DeletePropertyOptionErrors, DeletePropertyOptionResponses, EnsureTagSetData, EnsureTagSetErrors, EnsureTagSetResponses, GetBulkEntityPropertiesData, GetBulkEntityPropertiesErrors, GetBulkEntityPropertiesResponses, GetEntityPropertiesData, GetEntityPropertiesErrors, GetEntityPropertiesResponses, GetPropertyDefinitionData, GetPropertyDefinitionErrors, GetPropertyDefinitionResponses, GetPropertyOptionsData, GetPropertyOptionsErrors, GetPropertyOptionsResponses, ListPropertiesData, ListPropertiesErrors, ListPropertiesResponses, ListTagsData, ListTagsErrors, ListTagsResponses, RemoveEntityPropertyOptionData, RemoveEntityPropertyOptionErrors, RemoveEntityPropertyOptionResponses, SetEntityPropertyData, SetEntityPropertyErrors, SetEntityPropertyResponses, UpdatePropertyOptionData, UpdatePropertyOptionErrors, UpdatePropertyOptionResponses } from './types.gen';
+import type { AddEntityPropertyOptionData, AddEntityPropertyOptionErrors, AddEntityPropertyOptionResponses, AddPropertyOptionData, AddPropertyOptionErrors, AddPropertyOptionResponses, BulkUpdateEntitiesPropertyOptionsData, BulkUpdateEntitiesPropertyOptionsErrors, BulkUpdateEntitiesPropertyOptionsResponses, BulkUpdateEntityPropertyOptionsData, BulkUpdateEntityPropertyOptionsErrors, BulkUpdateEntityPropertyOptionsResponses, CreatePropertyDefinitionData, CreatePropertyDefinitionErrors, CreatePropertyDefinitionResponses, DeleteEntityPropertyData, DeleteEntityPropertyErrors, DeleteEntityPropertyResponses, DeletePropertyDefinitionData, DeletePropertyDefinitionErrors, DeletePropertyDefinitionResponses, DeletePropertyOptionData, DeletePropertyOptionErrors, DeletePropertyOptionResponses, EnsureTagSetData, EnsureTagSetErrors, EnsureTagSetResponses, GetBulkEntityPropertiesData, GetBulkEntityPropertiesErrors, GetBulkEntityPropertiesResponses, GetEntityPropertiesData, GetEntityPropertiesErrors, GetEntityPropertiesResponses, GetPropertyDefinitionData, GetPropertyDefinitionErrors, GetPropertyDefinitionResponses, GetPropertyOptionsData, GetPropertyOptionsErrors, GetPropertyOptionsResponses, ListPropertiesData, ListPropertiesErrors, ListPropertiesResponses, ListTagsData, ListTagsErrors, ListTagsResponses, MergeTagData, MergeTagErrors, MergeTagResponses, PromoteTagData, PromoteTagErrors, PromoteTagResponses, RemoveEntityPropertyOptionData, RemoveEntityPropertyOptionErrors, RemoveEntityPropertyOptionResponses, SetEntityPropertyData, SetEntityPropertyErrors, SetEntityPropertyResponses, UpdatePropertyOptionData, UpdatePropertyOptionErrors, UpdatePropertyOptionResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -270,4 +270,43 @@ export class Sdk extends HeyApiClient {
}
});
}
+
+ /**
+ * Replace one of the caller's personal labels with an existing team label.
+ *
+ * Every entity carrying the personal label is retagged with the team label
+ * (deduped if it already has both) and the personal label is deleted. The team
+ * label's name and color win. This is the confirmation step after the promote
+ * endpoint reports a name collision.
+ */
+ public mergeTag<ThrowOnError extends boolean = false>(options: Options<MergeTagData, ThrowOnError>): RequestResult<MergeTagResponses, MergeTagErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<MergeTagResponses, MergeTagErrors, ThrowOnError>({
+ url: '/properties/tags/merge',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
+ /**
+ * Share one of the caller's personal labels with their team.
+ *
+ * The label moves into the team tag set keeping its option id, so every entity
+ * already carrying it keeps the label — it just becomes visible to, and usable
+ * by, the whole team. A 409 means the team already has a label with that name;
+ * its body carries that label, and confirming the replacement is a call to the
+ * merge endpoint with `conflicting_option.id` as `target_option_id`.
+ */
+ public promoteTag<ThrowOnError extends boolean = false>(options: Options<PromoteTagData, ThrowOnError>): RequestResult<PromoteTagResponses, PromoteTagErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<PromoteTagResponses, PromoteTagErrors, ThrowOnError>({
+ url: '/properties/tags/promote',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
}
diff --git a/packages/sdk/generated/properties/types.gen.ts b/packages/sdk/generated/properties/types.gen.ts
index a1d81d6a22..bfc51b7f6c 100644
--- a/packages/sdk/generated/properties/types.gen.ts
+++ b/packages/sdk/generated/properties/types.gen.ts
@@ -290,6 +290,30 @@ export type ListPropertiesQuery = {
scope: PropertyScope;
};
+/**
+ * Request to replace a personal label with an existing team label.
+ */
+export type MergeTagRequest = {
+ /**
+ * The personal label to retire.
+ */
+ option_id: string;
+ /**
+ * The team label every entity carrying `option_id` is retagged with.
+ */
+ target_option_id: string;
+};
+
+/**
+ * Request to share one of the caller's personal labels with their team.
+ */
+export type PromoteTagRequest = {
+ /**
+ * The personal label to move into the team tag set.
+ */
+ option_id: string;
+};
+
/**
* Data type with embedded options for requests - provides compile-time validation.
*/
@@ -583,6 +607,22 @@ export type SetPropertyValue = {
urls: Array<string>;
};
+/**
+ * Body returned when a promotion collides with a label the team already has.
+ * The caller confirms with the user, then calls the merge endpoint with
+ * `conflicting_option.id` as the target.
+ */
+export type TagPromotionConflictResponse = {
+ /**
+ * The team label that already uses this name.
+ */
+ conflicting_option: PropertyOptionResponse;
+ /**
+ * Human-readable description of the collision.
+ */
+ message: string;
+};
+
/**
* Which owner a tag set belongs to.
*/
@@ -1306,3 +1346,75 @@ export type EnsureTagSetResponses = {
};
export type EnsureTagSetResponse = EnsureTagSetResponses[keyof EnsureTagSetResponses];
+
+export type MergeTagData = {
+ body: MergeTagRequest;
+ path?: never;
+ query?: never;
+ url: '/properties/tags/merge';
+};
+
+export type MergeTagErrors = {
+ /**
+ * Invalid request
+ */
+ 400: unknown;
+ /**
+ * Team membership required
+ */
+ 403: unknown;
+ /**
+ * Either label was not found in the expected tag set
+ */
+ 404: unknown;
+ /**
+ * Internal server error
+ */
+ 500: unknown;
+};
+
+export type MergeTagResponses = {
+ /**
+ * Label merged into the team label
+ */
+ 200: PropertyOptionResponse;
+};
+
+export type MergeTagResponse = MergeTagResponses[keyof MergeTagResponses];
+
+export type PromoteTagData = {
+ body: PromoteTagRequest;
+ path?: never;
+ query?: never;
+ url: '/properties/tags/promote';
+};
+
+export type PromoteTagErrors = {
+ /**
+ * Team membership required
+ */
+ 403: unknown;
+ /**
+ * Label not found in the caller's tag set
+ */
+ 404: unknown;
+ /**
+ * The team already has a label with that name
+ */
+ 409: TagPromotionConflictResponse;
+ /**
+ * Internal server error
+ */
+ 500: unknown;
+};
+
+export type PromoteTagError = PromoteTagErrors[keyof PromoteTagErrors];
+
+export type PromoteTagResponses = {
+ /**
+ * Label moved to the team tag set
+ */
+ 200: PropertyOptionResponse;
+};
+
+export type PromoteTagResponse = PromoteTagResponses[keyof PromoteTagResponses];
diff --git a/packages/sdk/specs/properties.json b/packages/sdk/specs/properties.json
index 7abced117d..a71d891cdf 100644
--- a/packages/sdk/specs/properties.json
+++ b/packages/sdk/specs/properties.json
@@ -855,6 +855,97 @@
}
}
}
+ },
+ "/properties/tags/merge": {
+ "post": {
+ "tags": ["Properties"],
+ "summary": "Replace one of the caller's personal labels with an existing team label.",
+ "description": "Every entity carrying the personal label is retagged with the team label\n(deduped if it already has both) and the personal label is deleted. The team\nlabel's name and color win. This is the confirmation step after the promote\nendpoint reports a name collision.",
+ "operationId": "merge_tag",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/MergeTagRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Label merged into the team label",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PropertyOptionResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid request"
+ },
+ "403": {
+ "description": "Team membership required"
+ },
+ "404": {
+ "description": "Either label was not found in the expected tag set"
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ }
+ }
+ },
+ "/properties/tags/promote": {
+ "post": {
+ "tags": ["Properties"],
+ "summary": "Share one of the caller's personal labels with their team.",
+ "description": "The label moves into the team tag set keeping its option id, so every entity\nalready carrying it keeps the label — it just becomes visible to, and usable\nby, the whole team. A 409 means the team already has a label with that name;\nits body carries that label, and confirming the replacement is a call to the\nmerge endpoint with `conflicting_option.id` as `target_option_id`.",
+ "operationId": "promote_tag",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PromoteTagRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Label moved to the team tag set",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PropertyOptionResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "Team membership required"
+ },
+ "404": {
+ "description": "Label not found in the caller's tag set"
+ },
+ "409": {
+ "description": "The team already has a label with that name",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TagPromotionConflictResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ }
+ }
}
},
"components": {
@@ -1362,6 +1453,35 @@
}
}
},
+ "MergeTagRequest": {
+ "type": "object",
+ "description": "Request to replace a personal label with an existing team label.",
+ "required": ["option_id", "target_option_id"],
+ "properties": {
+ "option_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The personal label to retire."
+ },
+ "target_option_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The team label every entity carrying `option_id` is retagged with."
+ }
+ }
+ },
+ "PromoteTagRequest": {
+ "type": "object",
+ "description": "Request to share one of the caller's personal labels with their team.",
+ "required": ["option_id"],
+ "properties": {
+ "option_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The personal label to move into the team tag set."
+ }
+ }
+ },
"PropertyDataType": {
"oneOf": [
{
@@ -2157,6 +2277,21 @@
],
"description": "Type-safe enum for setting entity property values - provides compile-time validation."
},
+ "TagPromotionConflictResponse": {
+ "type": "object",
+ "description": "Body returned when a promotion collides with a label the team already has.\nThe caller confirms with the user, then calls the merge endpoint with\n`conflicting_option.id` as the target.",
+ "required": ["message", "conflicting_option"],
+ "properties": {
+ "conflicting_option": {
+ "$ref": "#/components/schemas/PropertyOptionResponse",
+ "description": "The team label that already uses this name."
+ },
+ "message": {
+ "type": "string",
+ "description": "Human-readable description of the collision."
+ }
+ }
+ },
"TagScope": {
"type": "string",
"description": "Which owner a tag set belongs to.",
diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.ts
index be52b223d8..c9d0aadcff 100644
--- a/packages/sdk/src/coverage/skipped.ts
+++ b/packages/sdk/src/coverage/skipped.ts
@@ -189,6 +189,8 @@ export const notificationBacklog =
export const propertiesExcluded = [
'ensureTagSet',
+ 'mergeTag',
+ 'promoteTag',
] as const satisfies readonly (keyof PropertiesSdk)[];
export const propertiesBacklog =