diff --git a/.gitignore b/.gitignore index 1f867cca..f2c9b9a7 100644 --- a/.gitignore +++ b/.gitignore @@ -37,6 +37,8 @@ tmp/ .vscode/ .claude/settings.local.json .paperclip-local/ +/.idea/ +/.agents/ # Doc maintenance cursor .doc-review-cursor @@ -44,4 +46,4 @@ tmp/ # Playwright tests/e2e/test-results/ tests/e2e/playwright-report/ -.superset/ \ No newline at end of file +.superset/ diff --git a/cli/src/__tests__/company-delete.test.ts b/cli/src/__tests__/company-delete.test.ts index 6858a3d1..18a98cea 100644 --- a/cli/src/__tests__/company-delete.test.ts +++ b/cli/src/__tests__/company-delete.test.ts @@ -14,6 +14,8 @@ function makeCompany(overrides: Partial): Company { spentMonthlyCents: 0, requireBoardApprovalForNewAgents: false, brandColor: null, + logoAssetId: null, + logoUrl: null, createdAt: new Date(), updatedAt: new Date(), ...overrides, diff --git a/docs/api/companies.md b/docs/api/companies.md index a0aafae5..00e7ab66 100644 --- a/docs/api/companies.md +++ b/docs/api/companies.md @@ -38,10 +38,33 @@ PATCH /api/companies/{companyId} { "name": "Updated Name", "description": "Updated description", - "budgetMonthlyCents": 100000 + "budgetMonthlyCents": 100000, + "logoAssetId": "b9f5e911-6de5-4cd0-8dc6-a55a13bc02f6" } ``` +## Upload Company Logo + +Upload an image for a company icon and store it as that company’s logo. + +``` +POST /api/companies/{companyId}/logo +Content-Type: multipart/form-data +``` + +Valid image content types: + +- `image/png` +- `image/jpeg` +- `image/jpg` +- `image/webp` +- `image/gif` +- `image/svg+xml` + +Company logo uploads use the normal Paperclip attachment size limit. + +Then set the company logo by PATCHing the returned `assetId` into `logoAssetId`. + ## Archive Company ``` @@ -58,6 +81,8 @@ Archives a company. Archived companies are hidden from default listings. | `name` | string | Company name | | `description` | string | Company description | | `status` | string | `active`, `paused`, `archived` | +| `logoAssetId` | string | Optional asset id for the stored logo image | +| `logoUrl` | string | Optional Paperclip asset content path for the stored logo image | | `budgetMonthlyCents` | number | Monthly budget limit | | `createdAt` | string | ISO timestamp | | `updatedAt` | string | ISO timestamp | diff --git a/packages/db/src/migrations/0030_rich_magneto.sql b/packages/db/src/migrations/0030_rich_magneto.sql new file mode 100644 index 00000000..76d44de7 --- /dev/null +++ b/packages/db/src/migrations/0030_rich_magneto.sql @@ -0,0 +1,12 @@ +CREATE TABLE "company_logos" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "company_id" uuid NOT NULL, + "asset_id" uuid NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "company_logos" ADD CONSTRAINT "company_logos_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "company_logos" ADD CONSTRAINT "company_logos_asset_id_assets_id_fk" FOREIGN KEY ("asset_id") REFERENCES "public"."assets"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE UNIQUE INDEX "company_logos_company_uq" ON "company_logos" USING btree ("company_id");--> statement-breakpoint +CREATE UNIQUE INDEX "company_logos_asset_uq" ON "company_logos" USING btree ("asset_id"); \ No newline at end of file diff --git a/packages/db/src/migrations/meta/0026_snapshot.json b/packages/db/src/migrations/meta/0030_snapshot.json similarity index 77% rename from packages/db/src/migrations/meta/0026_snapshot.json rename to packages/db/src/migrations/meta/0030_snapshot.json index a3ebaad7..4f21ce46 100644 --- a/packages/db/src/migrations/meta/0026_snapshot.json +++ b/packages/db/src/migrations/meta/0030_snapshot.json @@ -1,6 +1,6 @@ { - "id": "5f8dd541-9e28-4a42-890b-fc4a301604ac", - "prevId": "bd8d9b8d-3012-4c58-bcfd-b3215c164f82", + "id": "ff007d90-e1a0-4df3-beab-a5be4a47273c", + "prevId": "fdb36f4e-6463-497d-b704-22d33be9b450", "version": "7", "dialect": "postgresql", "tables": { @@ -2179,6 +2179,110 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.company_logos": { + "name": "company_logos", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "asset_id": { + "name": "asset_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "company_logos_company_uq": { + "name": "company_logos_company_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "company_logos_asset_uq": { + "name": "company_logos_asset_uq", + "columns": [ + { + "expression": "asset_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "company_logos_company_id_companies_id_fk": { + "name": "company_logos_company_id_companies_id_fk", + "tableFrom": "company_logos", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "company_logos_asset_id_assets_id_fk": { + "name": "company_logos_asset_id_assets_id_fk", + "tableFrom": "company_logos", + "tableTo": "assets", + "columnsFrom": [ + "asset_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.company_memberships": { "name": "company_memberships", "schema": "", @@ -2873,6 +2977,343 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.document_revisions": { + "name": "document_revisions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "document_id": { + "name": "document_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "revision_number": { + "name": "revision_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "change_summary": { + "name": "change_summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by_agent_id": { + "name": "created_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "document_revisions_document_revision_uq": { + "name": "document_revisions_document_revision_uq", + "columns": [ + { + "expression": "document_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "revision_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "document_revisions_company_document_created_idx": { + "name": "document_revisions_company_document_created_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "document_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "document_revisions_company_id_companies_id_fk": { + "name": "document_revisions_company_id_companies_id_fk", + "tableFrom": "document_revisions", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "document_revisions_document_id_documents_id_fk": { + "name": "document_revisions_document_id_documents_id_fk", + "tableFrom": "document_revisions", + "tableTo": "documents", + "columnsFrom": [ + "document_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "document_revisions_created_by_agent_id_agents_id_fk": { + "name": "document_revisions_created_by_agent_id_agents_id_fk", + "tableFrom": "document_revisions", + "tableTo": "agents", + "columnsFrom": [ + "created_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.documents": { + "name": "documents", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "format": { + "name": "format", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'markdown'" + }, + "latest_body": { + "name": "latest_body", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "latest_revision_id": { + "name": "latest_revision_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "latest_revision_number": { + "name": "latest_revision_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_by_agent_id": { + "name": "created_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by_agent_id": { + "name": "updated_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "updated_by_user_id": { + "name": "updated_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "documents_company_updated_idx": { + "name": "documents_company_updated_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "documents_company_created_idx": { + "name": "documents_company_created_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "documents_company_id_companies_id_fk": { + "name": "documents_company_id_companies_id_fk", + "tableFrom": "documents", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "documents_created_by_agent_id_agents_id_fk": { + "name": "documents_created_by_agent_id_agents_id_fk", + "tableFrom": "documents", + "tableTo": "agents", + "columnsFrom": [ + "created_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "documents_updated_by_agent_id_agents_id_fk": { + "name": "documents_updated_by_agent_id_agents_id_fk", + "tableFrom": "documents", + "tableTo": "agents", + "columnsFrom": [ + "updated_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.goals": { "name": "goals", "schema": "", @@ -4204,6 +4645,174 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.issue_documents": { + "name": "issue_documents", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "document_id": { + "name": "document_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "issue_documents_company_issue_key_uq": { + "name": "issue_documents_company_issue_key_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "issue_documents_document_uq": { + "name": "issue_documents_document_uq", + "columns": [ + { + "expression": "document_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "issue_documents_company_issue_updated_idx": { + "name": "issue_documents_company_issue_updated_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "issue_documents_company_id_companies_id_fk": { + "name": "issue_documents_company_id_companies_id_fk", + "tableFrom": "issue_documents", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "issue_documents_issue_id_issues_id_fk": { + "name": "issue_documents_issue_id_issues_id_fk", + "tableFrom": "issue_documents", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "issue_documents_document_id_documents_id_fk": { + "name": "issue_documents_document_id_documents_id_fk", + "tableFrom": "issue_documents", + "tableTo": "documents", + "columnsFrom": [ + "document_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.issue_labels": { "name": "issue_labels", "schema": "", @@ -4632,6 +5241,12 @@ "primaryKey": false, "notNull": false }, + "execution_workspace_settings": { + "name": "execution_workspace_settings", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, "started_at": { "name": "started_at", "type": "timestamp with time zone", @@ -5258,6 +5873,1195 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.plugin_company_settings": { + "name": "plugin_company_settings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "plugin_id": { + "name": "plugin_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "settings_json": { + "name": "settings_json", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "plugin_company_settings_company_idx": { + "name": "plugin_company_settings_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "plugin_company_settings_plugin_idx": { + "name": "plugin_company_settings_plugin_idx", + "columns": [ + { + "expression": "plugin_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "plugin_company_settings_company_plugin_uq": { + "name": "plugin_company_settings_company_plugin_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "plugin_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "plugin_company_settings_company_id_companies_id_fk": { + "name": "plugin_company_settings_company_id_companies_id_fk", + "tableFrom": "plugin_company_settings", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "plugin_company_settings_plugin_id_plugins_id_fk": { + "name": "plugin_company_settings_plugin_id_plugins_id_fk", + "tableFrom": "plugin_company_settings", + "tableTo": "plugins", + "columnsFrom": [ + "plugin_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.plugin_config": { + "name": "plugin_config", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "plugin_id": { + "name": "plugin_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "config_json": { + "name": "config_json", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "plugin_config_plugin_id_idx": { + "name": "plugin_config_plugin_id_idx", + "columns": [ + { + "expression": "plugin_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "plugin_config_plugin_id_plugins_id_fk": { + "name": "plugin_config_plugin_id_plugins_id_fk", + "tableFrom": "plugin_config", + "tableTo": "plugins", + "columnsFrom": [ + "plugin_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.plugin_entities": { + "name": "plugin_entities", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "plugin_id": { + "name": "plugin_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope_kind": { + "name": "scope_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope_id": { + "name": "scope_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "plugin_entities_plugin_idx": { + "name": "plugin_entities_plugin_idx", + "columns": [ + { + "expression": "plugin_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "plugin_entities_type_idx": { + "name": "plugin_entities_type_idx", + "columns": [ + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "plugin_entities_scope_idx": { + "name": "plugin_entities_scope_idx", + "columns": [ + { + "expression": "scope_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "plugin_entities_external_idx": { + "name": "plugin_entities_external_idx", + "columns": [ + { + "expression": "plugin_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "entity_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "external_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "plugin_entities_plugin_id_plugins_id_fk": { + "name": "plugin_entities_plugin_id_plugins_id_fk", + "tableFrom": "plugin_entities", + "tableTo": "plugins", + "columnsFrom": [ + "plugin_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.plugin_job_runs": { + "name": "plugin_job_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "job_id": { + "name": "job_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "plugin_id": { + "name": "plugin_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "logs": { + "name": "logs", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "plugin_job_runs_job_idx": { + "name": "plugin_job_runs_job_idx", + "columns": [ + { + "expression": "job_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "plugin_job_runs_plugin_idx": { + "name": "plugin_job_runs_plugin_idx", + "columns": [ + { + "expression": "plugin_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "plugin_job_runs_status_idx": { + "name": "plugin_job_runs_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "plugin_job_runs_job_id_plugin_jobs_id_fk": { + "name": "plugin_job_runs_job_id_plugin_jobs_id_fk", + "tableFrom": "plugin_job_runs", + "tableTo": "plugin_jobs", + "columnsFrom": [ + "job_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "plugin_job_runs_plugin_id_plugins_id_fk": { + "name": "plugin_job_runs_plugin_id_plugins_id_fk", + "tableFrom": "plugin_job_runs", + "tableTo": "plugins", + "columnsFrom": [ + "plugin_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.plugin_jobs": { + "name": "plugin_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "plugin_id": { + "name": "plugin_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "job_key": { + "name": "job_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "schedule": { + "name": "schedule", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "last_run_at": { + "name": "last_run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "next_run_at": { + "name": "next_run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "plugin_jobs_plugin_idx": { + "name": "plugin_jobs_plugin_idx", + "columns": [ + { + "expression": "plugin_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "plugin_jobs_next_run_idx": { + "name": "plugin_jobs_next_run_idx", + "columns": [ + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "plugin_jobs_unique_idx": { + "name": "plugin_jobs_unique_idx", + "columns": [ + { + "expression": "plugin_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "job_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "plugin_jobs_plugin_id_plugins_id_fk": { + "name": "plugin_jobs_plugin_id_plugins_id_fk", + "tableFrom": "plugin_jobs", + "tableTo": "plugins", + "columnsFrom": [ + "plugin_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.plugin_logs": { + "name": "plugin_logs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "plugin_id": { + "name": "plugin_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'info'" + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "meta": { + "name": "meta", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "plugin_logs_plugin_time_idx": { + "name": "plugin_logs_plugin_time_idx", + "columns": [ + { + "expression": "plugin_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "plugin_logs_level_idx": { + "name": "plugin_logs_level_idx", + "columns": [ + { + "expression": "level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "plugin_logs_plugin_id_plugins_id_fk": { + "name": "plugin_logs_plugin_id_plugins_id_fk", + "tableFrom": "plugin_logs", + "tableTo": "plugins", + "columnsFrom": [ + "plugin_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.plugin_state": { + "name": "plugin_state", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "plugin_id": { + "name": "plugin_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "scope_kind": { + "name": "scope_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope_id": { + "name": "scope_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "namespace": { + "name": "namespace", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'default'" + }, + "state_key": { + "name": "state_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value_json": { + "name": "value_json", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "plugin_state_plugin_scope_idx": { + "name": "plugin_state_plugin_scope_idx", + "columns": [ + { + "expression": "plugin_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "plugin_state_plugin_id_plugins_id_fk": { + "name": "plugin_state_plugin_id_plugins_id_fk", + "tableFrom": "plugin_state", + "tableTo": "plugins", + "columnsFrom": [ + "plugin_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "plugin_state_unique_entry_idx": { + "name": "plugin_state_unique_entry_idx", + "nullsNotDistinct": true, + "columns": [ + "plugin_id", + "scope_kind", + "scope_id", + "namespace", + "state_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.plugin_webhook_deliveries": { + "name": "plugin_webhook_deliveries", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "plugin_id": { + "name": "plugin_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "webhook_key": { + "name": "webhook_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "headers": { + "name": "headers", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "plugin_webhook_deliveries_plugin_idx": { + "name": "plugin_webhook_deliveries_plugin_idx", + "columns": [ + { + "expression": "plugin_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "plugin_webhook_deliveries_status_idx": { + "name": "plugin_webhook_deliveries_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "plugin_webhook_deliveries_key_idx": { + "name": "plugin_webhook_deliveries_key_idx", + "columns": [ + { + "expression": "webhook_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "plugin_webhook_deliveries_plugin_id_plugins_id_fk": { + "name": "plugin_webhook_deliveries_plugin_id_plugins_id_fk", + "tableFrom": "plugin_webhook_deliveries", + "tableTo": "plugins", + "columnsFrom": [ + "plugin_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.plugins": { + "name": "plugins", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "plugin_key": { + "name": "plugin_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "package_name": { + "name": "package_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "api_version": { + "name": "api_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "categories": { + "name": "categories", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "manifest_json": { + "name": "manifest_json", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'installed'" + }, + "install_order": { + "name": "install_order", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "package_path": { + "name": "package_path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "installed_at": { + "name": "installed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "plugins_plugin_key_idx": { + "name": "plugins_plugin_key_idx", + "columns": [ + { + "expression": "plugin_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "plugins_status_idx": { + "name": "plugins_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.principal_permission_grants": { "name": "principal_permission_grants", "schema": "", @@ -5749,6 +7553,12 @@ "primaryKey": false, "notNull": false }, + "execution_workspace_policy": { + "name": "execution_workspace_policy", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, "archived_at": { "name": "archived_at", "type": "timestamp with time zone", diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index b061a56a..696c437a 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -211,6 +211,13 @@ "when": 1773417600000, "tag": "0029_plugin_tables", "breakpoints": true + }, + { + "idx": 30, + "version": "7", + "when": 1773670925214, + "tag": "0030_rich_magneto", + "breakpoints": true } ] -} +} \ No newline at end of file diff --git a/packages/db/src/schema/company_logos.ts b/packages/db/src/schema/company_logos.ts new file mode 100644 index 00000000..13e0abe0 --- /dev/null +++ b/packages/db/src/schema/company_logos.ts @@ -0,0 +1,18 @@ +import { pgTable, uuid, timestamp, uniqueIndex } from "drizzle-orm/pg-core"; +import { companies } from "./companies.js"; +import { assets } from "./assets.js"; + +export const companyLogos = pgTable( + "company_logos", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + assetId: uuid("asset_id").notNull().references(() => assets.id, { onDelete: "cascade" }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), + }, + (table) => ({ + companyUq: uniqueIndex("company_logos_company_uq").on(table.companyId), + assetUq: uniqueIndex("company_logos_asset_uq").on(table.assetId), + }), +); diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts index f173db45..422d7cdd 100644 --- a/packages/db/src/schema/index.ts +++ b/packages/db/src/schema/index.ts @@ -1,4 +1,5 @@ export { companies } from "./companies.js"; +export { companyLogos } from "./company_logos.js"; export { authUsers, authSessions, authAccounts, authVerifications } from "./auth.js"; export { instanceUserRoles } from "./instance_user_roles.js"; export { agents } from "./agents.js"; diff --git a/packages/shared/src/types/company.ts b/packages/shared/src/types/company.ts index 435be80d..e9022b93 100644 --- a/packages/shared/src/types/company.ts +++ b/packages/shared/src/types/company.ts @@ -11,6 +11,8 @@ export interface Company { spentMonthlyCents: number; requireBoardApprovalForNewAgents: boolean; brandColor: string | null; + logoAssetId: string | null; + logoUrl: string | null; createdAt: Date; updatedAt: Date; } diff --git a/packages/shared/src/validators/company.ts b/packages/shared/src/validators/company.ts index 407d2ae4..bb4851f4 100644 --- a/packages/shared/src/validators/company.ts +++ b/packages/shared/src/validators/company.ts @@ -1,6 +1,8 @@ import { z } from "zod"; import { COMPANY_STATUSES } from "../constants.js"; +const logoAssetIdSchema = z.string().uuid().nullable().optional(); + export const createCompanySchema = z.object({ name: z.string().min(1), description: z.string().optional().nullable(), @@ -16,6 +18,7 @@ export const updateCompanySchema = createCompanySchema spentMonthlyCents: z.number().int().nonnegative().optional(), requireBoardApprovalForNewAgents: z.boolean().optional(), brandColor: z.string().regex(/^#[0-9a-fA-F]{6}$/).nullable().optional(), + logoAssetId: logoAssetIdSchema, }); export type UpdateCompany = z.infer; diff --git a/server/package.json b/server/package.json index 1887d64c..464d7395 100644 --- a/server/package.json +++ b/server/package.json @@ -51,10 +51,12 @@ "better-auth": "1.4.18", "chokidar": "^4.0.3", "detect-port": "^2.1.0", + "dompurify": "^3.3.2", "dotenv": "^17.0.1", "drizzle-orm": "^0.38.4", "embedded-postgres": "^18.1.0-beta.16", "express": "^5.1.0", + "jsdom": "^28.1.0", "multer": "^2.0.2", "open": "^11.0.0", "pino": "^9.6.0", @@ -66,6 +68,7 @@ "devDependencies": { "@types/express": "^5.0.0", "@types/express-serve-static-core": "^5.0.0", + "@types/jsdom": "^28.0.0", "@types/multer": "^2.0.0", "@types/node": "^24.6.0", "@types/supertest": "^6.0.2", diff --git a/server/src/__tests__/assets.test.ts b/server/src/__tests__/assets.test.ts new file mode 100644 index 00000000..b7bec332 --- /dev/null +++ b/server/src/__tests__/assets.test.ts @@ -0,0 +1,250 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import express from "express"; +import request from "supertest"; +import { MAX_ATTACHMENT_BYTES } from "../attachment-types.js"; +import { assetRoutes } from "../routes/assets.js"; +import type { StorageService } from "../storage/types.js"; + +const { createAssetMock, getAssetByIdMock, logActivityMock } = vi.hoisted(() => ({ + createAssetMock: vi.fn(), + getAssetByIdMock: vi.fn(), + logActivityMock: vi.fn(), +})); + +vi.mock("../services/index.js", () => ({ + assetService: vi.fn(() => ({ + create: createAssetMock, + getById: getAssetByIdMock, + })), + logActivity: logActivityMock, +})); + +function createAsset() { + const now = new Date("2026-01-01T00:00:00.000Z"); + return { + id: "asset-1", + companyId: "company-1", + provider: "local", + objectKey: "assets/abc", + contentType: "image/png", + byteSize: 40, + sha256: "sha256-sample", + originalFilename: "logo.png", + createdByAgentId: null, + createdByUserId: "user-1", + createdAt: now, + updatedAt: now, + }; +} + +function createStorageService(contentType = "image/png"): StorageService { + const putFile: StorageService["putFile"] = vi.fn(async (input: { + companyId: string; + namespace: string; + originalFilename: string | null; + contentType: string; + body: Buffer; + }) => { + return { + provider: "local_disk" as const, + objectKey: `${input.namespace}/${input.originalFilename ?? "upload"}`, + contentType: contentType || input.contentType, + byteSize: input.body.length, + sha256: "sha256-sample", + originalFilename: input.originalFilename, + }; + }); + + return { + provider: "local_disk" as const, + putFile, + getObject: vi.fn(), + headObject: vi.fn(), + deleteObject: vi.fn(), + }; +} + +function createApp(storage: ReturnType) { + const app = express(); + app.use((req, _res, next) => { + req.actor = { + type: "board", + source: "local_implicit", + userId: "user-1", + }; + next(); + }); + app.use("/api", assetRoutes({} as any, storage)); + return app; +} + +describe("POST /api/companies/:companyId/assets/images", () => { + afterEach(() => { + createAssetMock.mockReset(); + getAssetByIdMock.mockReset(); + logActivityMock.mockReset(); + }); + + it("accepts PNG image uploads and returns an asset path", async () => { + const png = createStorageService("image/png"); + const app = createApp(png); + + createAssetMock.mockResolvedValue(createAsset()); + + const res = await request(app) + .post("/api/companies/company-1/assets/images") + .field("namespace", "goals") + .attach("file", Buffer.from("png"), "logo.png"); + + expect(res.status).toBe(201); + expect(res.body.contentPath).toBe("/api/assets/asset-1/content"); + expect(createAssetMock).toHaveBeenCalledTimes(1); + expect(png.putFile).toHaveBeenCalledWith({ + companyId: "company-1", + namespace: "assets/goals", + originalFilename: "logo.png", + contentType: "image/png", + body: expect.any(Buffer), + }); + }); + + it("allows supported non-image attachments outside the company logo flow", async () => { + const text = createStorageService("text/plain"); + const app = createApp(text); + + createAssetMock.mockResolvedValue({ + ...createAsset(), + contentType: "text/plain", + originalFilename: "note.txt", + }); + + const res = await request(app) + .post("/api/companies/company-1/assets/images") + .field("namespace", "issues/drafts") + .attach("file", Buffer.from("hello"), { filename: "note.txt", contentType: "text/plain" }); + + expect(res.status).toBe(201); + expect(text.putFile).toHaveBeenCalledWith({ + companyId: "company-1", + namespace: "assets/issues/drafts", + originalFilename: "note.txt", + contentType: "text/plain", + body: expect.any(Buffer), + }); + }); +}); + +describe("POST /api/companies/:companyId/logo", () => { + afterEach(() => { + createAssetMock.mockReset(); + getAssetByIdMock.mockReset(); + logActivityMock.mockReset(); + }); + + it("accepts PNG logo uploads and returns an asset path", async () => { + const png = createStorageService("image/png"); + const app = createApp(png); + + createAssetMock.mockResolvedValue(createAsset()); + + const res = await request(app) + .post("/api/companies/company-1/logo") + .attach("file", Buffer.from("png"), "logo.png"); + + expect(res.status).toBe(201); + expect(res.body.contentPath).toBe("/api/assets/asset-1/content"); + expect(createAssetMock).toHaveBeenCalledTimes(1); + expect(png.putFile).toHaveBeenCalledWith({ + companyId: "company-1", + namespace: "assets/companies", + originalFilename: "logo.png", + contentType: "image/png", + body: expect.any(Buffer), + }); + }); + + it("sanitizes SVG logo uploads before storing them", async () => { + const svg = createStorageService("image/svg+xml"); + const app = createApp(svg); + + createAssetMock.mockResolvedValue({ + ...createAsset(), + contentType: "image/svg+xml", + originalFilename: "logo.svg", + }); + + const res = await request(app) + .post("/api/companies/company-1/logo") + .attach( + "file", + Buffer.from( + "", + ), + "logo.svg", + ); + + expect(res.status).toBe(201); + expect(svg.putFile).toHaveBeenCalledTimes(1); + const stored = (svg.putFile as ReturnType).mock.calls[0]?.[0]; + expect(stored.contentType).toBe("image/svg+xml"); + expect(stored.originalFilename).toBe("logo.svg"); + const body = stored.body.toString("utf8"); + expect(body).toContain(" { + const png = createStorageService("image/png"); + const app = createApp(png); + createAssetMock.mockResolvedValue(createAsset()); + + const file = Buffer.alloc(150 * 1024, "a"); + const res = await request(app) + .post("/api/companies/company-1/logo") + .attach("file", file, "within-limit.png"); + + expect(res.status).toBe(201); + }); + + it("rejects logo files larger than the general attachment limit", async () => { + const app = createApp(createStorageService()); + createAssetMock.mockResolvedValue(createAsset()); + + const file = Buffer.alloc(MAX_ATTACHMENT_BYTES + 1, "a"); + const res = await request(app) + .post("/api/companies/company-1/logo") + .attach("file", file, "too-large.png"); + + expect(res.status).toBe(422); + expect(res.body.error).toBe(`Image exceeds ${MAX_ATTACHMENT_BYTES} bytes`); + }); + + it("rejects unsupported image types", async () => { + const app = createApp(createStorageService("text/plain")); + createAssetMock.mockResolvedValue(createAsset()); + + const res = await request(app) + .post("/api/companies/company-1/logo") + .attach("file", Buffer.from("not an image"), "note.txt"); + + expect(res.status).toBe(422); + expect(res.body.error).toBe("Unsupported image type: text/plain"); + expect(createAssetMock).not.toHaveBeenCalled(); + }); + + it("rejects SVG image uploads that cannot be sanitized", async () => { + const app = createApp(createStorageService("image/svg+xml")); + createAssetMock.mockResolvedValue(createAsset()); + + const res = await request(app) + .post("/api/companies/company-1/logo") + .attach("file", Buffer.from("not actually svg"), "logo.svg"); + + expect(res.status).toBe(422); + expect(res.body.error).toBe("SVG could not be sanitized"); + expect(createAssetMock).not.toHaveBeenCalled(); + }); +}); diff --git a/server/src/routes/assets.ts b/server/src/routes/assets.ts index bd2f154d..0a6f857a 100644 --- a/server/src/routes/assets.ts +++ b/server/src/routes/assets.ts @@ -1,21 +1,104 @@ import { Router, type Request, type Response } from "express"; import multer from "multer"; +import createDOMPurify from "dompurify"; +import { JSDOM } from "jsdom"; import type { Db } from "@paperclipai/db"; import { createAssetImageMetadataSchema } from "@paperclipai/shared"; import type { StorageService } from "../storage/types.js"; import { assetService, logActivity } from "../services/index.js"; -import { assertCompanyAccess, getActorInfo } from "./authz.js"; import { isAllowedContentType, MAX_ATTACHMENT_BYTES } from "../attachment-types.js"; +import { assertCompanyAccess, getActorInfo } from "./authz.js"; +const SVG_CONTENT_TYPE = "image/svg+xml"; +const ALLOWED_COMPANY_LOGO_CONTENT_TYPES = new Set([ + "image/png", + "image/jpeg", + "image/jpg", + "image/webp", + "image/gif", + SVG_CONTENT_TYPE, +]); + +function sanitizeSvgBuffer(input: Buffer): Buffer | null { + const raw = input.toString("utf8").trim(); + if (!raw) return null; + + const baseDom = new JSDOM(""); + const domPurify = createDOMPurify( + baseDom.window as unknown as Parameters[0], + ); + domPurify.addHook("uponSanitizeAttribute", (_node, data) => { + const attrName = data.attrName.toLowerCase(); + const attrValue = (data.attrValue ?? "").trim(); + + if (attrName.startsWith("on")) { + data.keepAttr = false; + return; + } + + if ((attrName === "href" || attrName === "xlink:href") && attrValue && !attrValue.startsWith("#")) { + data.keepAttr = false; + } + }); + + let parsedDom: JSDOM | null = null; + try { + const sanitized = domPurify.sanitize(raw, { + USE_PROFILES: { svg: true, svgFilters: true, html: false }, + FORBID_TAGS: ["script", "foreignObject"], + FORBID_CONTENTS: ["script", "foreignObject"], + RETURN_TRUSTED_TYPE: false, + }); + + parsedDom = new JSDOM(sanitized, { contentType: SVG_CONTENT_TYPE }); + const document = parsedDom.window.document; + const root = document.documentElement; + if (!root || root.tagName.toLowerCase() !== "svg") return null; + + for (const el of Array.from(root.querySelectorAll("script, foreignObject"))) { + el.remove(); + } + for (const el of Array.from(root.querySelectorAll("*"))) { + for (const attr of Array.from(el.attributes)) { + const attrName = attr.name.toLowerCase(); + const attrValue = attr.value.trim(); + if (attrName.startsWith("on")) { + el.removeAttribute(attr.name); + continue; + } + if ((attrName === "href" || attrName === "xlink:href") && attrValue && !attrValue.startsWith("#")) { + el.removeAttribute(attr.name); + } + } + } + + const output = root.outerHTML.trim(); + if (!output || !/^]/i.test(output)) return null; + return Buffer.from(output, "utf8"); + } catch { + return null; + } finally { + parsedDom?.window.close(); + baseDom.window.close(); + } +} export function assetRoutes(db: Db, storage: StorageService) { const router = Router(); const svc = assetService(db); - const upload = multer({ + const assetUpload = multer({ + storage: multer.memoryStorage(), + limits: { fileSize: MAX_ATTACHMENT_BYTES, files: 1 }, + }); + const companyLogoUpload = multer({ storage: multer.memoryStorage(), limits: { fileSize: MAX_ATTACHMENT_BYTES, files: 1 }, }); - async function runSingleFileUpload(req: Request, res: Response) { + async function runSingleFileUpload( + upload: ReturnType, + req: Request, + res: Response, + ) { await new Promise((resolve, reject) => { upload.single("file")(req, res, (err: unknown) => { if (err) reject(err); @@ -29,7 +112,7 @@ export function assetRoutes(db: Db, storage: StorageService) { assertCompanyAccess(req, companyId); try { - await runSingleFileUpload(req, res); + await runSingleFileUpload(assetUpload, req, res); } catch (err) { if (err instanceof multer.MulterError) { if (err.code === "LIMIT_FILE_SIZE") { @@ -48,16 +131,6 @@ export function assetRoutes(db: Db, storage: StorageService) { return; } - const contentType = (file.mimetype || "").toLowerCase(); - if (!isAllowedContentType(contentType)) { - res.status(422).json({ error: `Unsupported file type: ${contentType || "unknown"}` }); - return; - } - if (file.buffer.length <= 0) { - res.status(422).json({ error: "Image is empty" }); - return; - } - const parsedMeta = createAssetImageMetadataSchema.safeParse(req.body ?? {}); if (!parsedMeta.success) { res.status(400).json({ error: "Invalid image metadata", details: parsedMeta.error.issues }); @@ -65,13 +138,32 @@ export function assetRoutes(db: Db, storage: StorageService) { } const namespaceSuffix = parsedMeta.data.namespace ?? "general"; + const contentType = (file.mimetype || "").toLowerCase(); + if (contentType !== SVG_CONTENT_TYPE && !isAllowedContentType(contentType)) { + res.status(422).json({ error: `Unsupported file type: ${contentType || "unknown"}` }); + return; + } + let fileBody = file.buffer; + if (contentType === SVG_CONTENT_TYPE) { + const sanitized = sanitizeSvgBuffer(file.buffer); + if (!sanitized || sanitized.length <= 0) { + res.status(422).json({ error: "SVG could not be sanitized" }); + return; + } + fileBody = sanitized; + } + if (fileBody.length <= 0) { + res.status(422).json({ error: "Image is empty" }); + return; + } + const actor = getActorInfo(req); const stored = await storage.putFile({ companyId, namespace: `assets/${namespaceSuffix}`, originalFilename: file.originalname || null, contentType, - body: file.buffer, + body: fileBody, }); const asset = await svc.create(companyId, { @@ -118,6 +210,105 @@ export function assetRoutes(db: Db, storage: StorageService) { }); }); + router.post("/companies/:companyId/logo", async (req, res) => { + const companyId = req.params.companyId as string; + assertCompanyAccess(req, companyId); + + try { + await runSingleFileUpload(companyLogoUpload, req, res); + } catch (err) { + if (err instanceof multer.MulterError) { + if (err.code === "LIMIT_FILE_SIZE") { + res.status(422).json({ error: `Image exceeds ${MAX_ATTACHMENT_BYTES} bytes` }); + return; + } + res.status(400).json({ error: err.message }); + return; + } + throw err; + } + + const file = (req as Request & { file?: { mimetype: string; buffer: Buffer; originalname: string } }).file; + if (!file) { + res.status(400).json({ error: "Missing file field 'file'" }); + return; + } + + const contentType = (file.mimetype || "").toLowerCase(); + if (!ALLOWED_COMPANY_LOGO_CONTENT_TYPES.has(contentType)) { + res.status(422).json({ error: `Unsupported image type: ${contentType || "unknown"}` }); + return; + } + + let fileBody = file.buffer; + if (contentType === SVG_CONTENT_TYPE) { + const sanitized = sanitizeSvgBuffer(file.buffer); + if (!sanitized || sanitized.length <= 0) { + res.status(422).json({ error: "SVG could not be sanitized" }); + return; + } + fileBody = sanitized; + } + + if (fileBody.length <= 0) { + res.status(422).json({ error: "Image is empty" }); + return; + } + + const actor = getActorInfo(req); + const stored = await storage.putFile({ + companyId, + namespace: "assets/companies", + originalFilename: file.originalname || null, + contentType, + body: fileBody, + }); + + const asset = await svc.create(companyId, { + provider: stored.provider, + objectKey: stored.objectKey, + contentType: stored.contentType, + byteSize: stored.byteSize, + sha256: stored.sha256, + originalFilename: stored.originalFilename, + createdByAgentId: actor.agentId, + createdByUserId: actor.actorType === "user" ? actor.actorId : null, + }); + + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "asset.created", + entityType: "asset", + entityId: asset.id, + details: { + originalFilename: asset.originalFilename, + contentType: asset.contentType, + byteSize: asset.byteSize, + namespace: "assets/companies", + }, + }); + + res.status(201).json({ + assetId: asset.id, + companyId: asset.companyId, + provider: asset.provider, + objectKey: asset.objectKey, + contentType: asset.contentType, + byteSize: asset.byteSize, + sha256: asset.sha256, + originalFilename: asset.originalFilename, + createdByAgentId: asset.createdByAgentId, + createdByUserId: asset.createdByUserId, + createdAt: asset.createdAt, + updatedAt: asset.updatedAt, + contentPath: `/api/assets/${asset.id}/content`, + }); + }); + router.get("/assets/:assetId/content", async (req, res, next) => { const assetId = req.params.assetId as string; const asset = await svc.getById(assetId); @@ -128,9 +319,14 @@ export function assetRoutes(db: Db, storage: StorageService) { assertCompanyAccess(req, asset.companyId); const object = await storage.getObject(asset.companyId, asset.objectKey); - res.setHeader("Content-Type", asset.contentType || object.contentType || "application/octet-stream"); + const responseContentType = asset.contentType || object.contentType || "application/octet-stream"; + res.setHeader("Content-Type", responseContentType); res.setHeader("Content-Length", String(asset.byteSize || object.contentLength || 0)); res.setHeader("Cache-Control", "private, max-age=60"); + res.setHeader("X-Content-Type-Options", "nosniff"); + if (responseContentType === SVG_CONTENT_TYPE) { + res.setHeader("Content-Security-Policy", "sandbox; default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'"); + } const filename = asset.originalFilename ?? "asset"; res.setHeader("Content-Disposition", `inline; filename=\"${filename.replaceAll("\"", "")}\"`); @@ -142,4 +338,3 @@ export function assetRoutes(db: Db, storage: StorageService) { return router; } - diff --git a/server/src/services/companies.ts b/server/src/services/companies.ts index 38a1f12f..42c4e972 100644 --- a/server/src/services/companies.ts +++ b/server/src/services/companies.ts @@ -2,6 +2,8 @@ import { eq, count } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { companies, + companyLogos, + assets, agents, agentApiKeys, agentRuntimeState, @@ -23,10 +25,41 @@ import { principalPermissionGrants, companyMemberships, } from "@paperclipai/db"; +import { notFound, unprocessable } from "../errors.js"; export function companyService(db: Db) { const ISSUE_PREFIX_FALLBACK = "CMP"; + const companySelection = { + id: companies.id, + name: companies.name, + description: companies.description, + status: companies.status, + issuePrefix: companies.issuePrefix, + issueCounter: companies.issueCounter, + budgetMonthlyCents: companies.budgetMonthlyCents, + spentMonthlyCents: companies.spentMonthlyCents, + requireBoardApprovalForNewAgents: companies.requireBoardApprovalForNewAgents, + brandColor: companies.brandColor, + logoAssetId: companyLogos.assetId, + createdAt: companies.createdAt, + updatedAt: companies.updatedAt, + }; + + function enrichCompany(company: T) { + return { + ...company, + logoUrl: company.logoAssetId ? `/api/assets/${company.logoAssetId}/content` : null, + }; + } + + function getCompanyQuery(database: Pick) { + return database + .select(companySelection) + .from(companies) + .leftJoin(companyLogos, eq(companyLogos.companyId, companies.id)); + } + function deriveIssuePrefixBase(name: string) { const normalized = name.toUpperCase().replace(/[^A-Z]/g, ""); return normalized.slice(0, 3) || ISSUE_PREFIX_FALLBACK; @@ -70,32 +103,97 @@ export function companyService(db: Db) { } return { - list: () => db.select().from(companies), + list: () => + getCompanyQuery(db).then((rows) => rows.map((row) => enrichCompany(row))), getById: (id: string) => - db - .select() - .from(companies) + getCompanyQuery(db) .where(eq(companies.id, id)) - .then((rows) => rows[0] ?? null), + .then((rows) => (rows[0] ? enrichCompany(rows[0]) : null)), - create: async (data: typeof companies.$inferInsert) => createCompanyWithUniquePrefix(data), + create: async (data: typeof companies.$inferInsert) => { + const created = await createCompanyWithUniquePrefix(data); + const row = await getCompanyQuery(db) + .where(eq(companies.id, created.id)) + .then((rows) => rows[0] ?? null); + if (!row) throw notFound("Company not found after creation"); + return enrichCompany(row); + }, - update: (id: string, data: Partial) => - db - .update(companies) - .set({ ...data, updatedAt: new Date() }) - .where(eq(companies.id, id)) - .returning() - .then((rows) => rows[0] ?? null), + update: ( + id: string, + data: Partial & { logoAssetId?: string | null }, + ) => + db.transaction(async (tx) => { + const existing = await getCompanyQuery(tx) + .where(eq(companies.id, id)) + .then((rows) => rows[0] ?? null); + if (!existing) return null; + + const { logoAssetId, ...companyPatch } = data; + + if (logoAssetId !== undefined && logoAssetId !== null) { + const nextLogoAsset = await tx + .select({ id: assets.id, companyId: assets.companyId }) + .from(assets) + .where(eq(assets.id, logoAssetId)) + .then((rows) => rows[0] ?? null); + if (!nextLogoAsset) throw notFound("Logo asset not found"); + if (nextLogoAsset.companyId !== existing.id) { + throw unprocessable("Logo asset must belong to the same company"); + } + } + + const updated = await tx + .update(companies) + .set({ ...companyPatch, updatedAt: new Date() }) + .where(eq(companies.id, id)) + .returning() + .then((rows) => rows[0] ?? null); + if (!updated) return null; + + if (logoAssetId === null) { + await tx.delete(companyLogos).where(eq(companyLogos.companyId, id)); + } else if (logoAssetId !== undefined) { + await tx + .insert(companyLogos) + .values({ + companyId: id, + assetId: logoAssetId, + }) + .onConflictDoUpdate({ + target: companyLogos.companyId, + set: { + assetId: logoAssetId, + updatedAt: new Date(), + }, + }); + } + + if (logoAssetId !== undefined && existing.logoAssetId && existing.logoAssetId !== logoAssetId) { + await tx.delete(assets).where(eq(assets.id, existing.logoAssetId)); + } + + return enrichCompany({ + ...updated, + logoAssetId: logoAssetId === undefined ? existing.logoAssetId : logoAssetId, + }); + }), archive: (id: string) => - db - .update(companies) - .set({ status: "archived", updatedAt: new Date() }) - .where(eq(companies.id, id)) - .returning() - .then((rows) => rows[0] ?? null), + db.transaction(async (tx) => { + const updated = await tx + .update(companies) + .set({ status: "archived", updatedAt: new Date() }) + .where(eq(companies.id, id)) + .returning() + .then((rows) => rows[0] ?? null); + if (!updated) return null; + const row = await getCompanyQuery(tx) + .where(eq(companies.id, id)) + .then((rows) => rows[0] ?? null); + return row ? enrichCompany(row) : null; + }), remove: (id: string) => db.transaction(async (tx) => { @@ -116,6 +214,8 @@ export function companyService(db: Db) { await tx.delete(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, id)); await tx.delete(companyMemberships).where(eq(companyMemberships.companyId, id)); await tx.delete(issues).where(eq(issues.companyId, id)); + await tx.delete(companyLogos).where(eq(companyLogos.companyId, id)); + await tx.delete(assets).where(eq(assets.companyId, id)); await tx.delete(goals).where(eq(goals.companyId, id)); await tx.delete(projects).where(eq(projects.companyId, id)); await tx.delete(agents).where(eq(agents.companyId, id)); diff --git a/ui/src/api/assets.ts b/ui/src/api/assets.ts index 8b3d056c..6fcf323f 100644 --- a/ui/src/api/assets.ts +++ b/ui/src/api/assets.ts @@ -11,11 +11,19 @@ export const assetsApi = { const safeFile = new File([buffer], file.name, { type: file.type }); const form = new FormData(); - form.append("file", safeFile); if (namespace && namespace.trim().length > 0) { form.append("namespace", namespace.trim()); } + form.append("file", safeFile); return api.postForm(`/companies/${companyId}/assets/images`, form); }, -}; + uploadCompanyLogo: async (companyId: string, file: File) => { + const buffer = await file.arrayBuffer(); + const safeFile = new File([buffer], file.name, { type: file.type }); + + const form = new FormData(); + form.append("file", safeFile); + return api.postForm(`/companies/${companyId}/logo`, form); + }, +}; diff --git a/ui/src/api/companies.ts b/ui/src/api/companies.ts index 583d9e69..bc21414e 100644 --- a/ui/src/api/companies.ts +++ b/ui/src/api/companies.ts @@ -14,14 +14,18 @@ export const companiesApi = { list: () => api.get("/companies"), get: (companyId: string) => api.get(`/companies/${companyId}`), stats: () => api.get("/companies/stats"), - create: (data: { name: string; description?: string | null; budgetMonthlyCents?: number }) => + create: (data: { + name: string; + description?: string | null; + budgetMonthlyCents?: number; + }) => api.post("/companies", data), update: ( companyId: string, data: Partial< Pick< Company, - "name" | "description" | "status" | "budgetMonthlyCents" | "requireBoardApprovalForNewAgents" | "brandColor" + "name" | "description" | "status" | "budgetMonthlyCents" | "requireBoardApprovalForNewAgents" | "brandColor" | "logoAssetId" > >, ) => api.patch(`/companies/${companyId}`, data), diff --git a/ui/src/components/CompanyPatternIcon.tsx b/ui/src/components/CompanyPatternIcon.tsx index c7e5acc3..6ea40788 100644 --- a/ui/src/components/CompanyPatternIcon.tsx +++ b/ui/src/components/CompanyPatternIcon.tsx @@ -1,4 +1,4 @@ -import { useMemo } from "react"; +import { useEffect, useMemo, useState } from "react"; import { cn } from "../lib/utils"; const BAYER_4X4 = [ @@ -10,6 +10,7 @@ const BAYER_4X4 = [ interface CompanyPatternIconProps { companyName: string; + logoUrl?: string | null; brandColor?: string | null; className?: string; } @@ -159,8 +160,18 @@ function makeCompanyPatternDataUrl(seed: string, brandColor?: string | null, log return canvas.toDataURL("image/png"); } -export function CompanyPatternIcon({ companyName, brandColor, className }: CompanyPatternIconProps) { +export function CompanyPatternIcon({ + companyName, + logoUrl, + brandColor, + className, +}: CompanyPatternIconProps) { const initial = companyName.trim().charAt(0).toUpperCase() || "?"; + const [imageError, setImageError] = useState(false); + const logo = !imageError && typeof logoUrl === "string" && logoUrl.trim().length > 0 ? logoUrl : null; + useEffect(() => { + setImageError(false); + }, [logoUrl]); const patternDataUrl = useMemo( () => makeCompanyPatternDataUrl(companyName.trim().toLowerCase(), brandColor), [companyName, brandColor], @@ -173,7 +184,14 @@ export function CompanyPatternIcon({ companyName, brandColor, className }: Compa className, )} > - {patternDataUrl ? ( + {logo ? ( + {`${companyName} setImageError(true)} + className="absolute inset-0 h-full w-full object-cover" + /> + ) : patternDataUrl ? ( )} - - {initial} - + {!logo && ( + + {initial} + + )} ); } diff --git a/ui/src/components/CompanyRail.tsx b/ui/src/components/CompanyRail.tsx index fa981d1b..2ec8fc06 100644 --- a/ui/src/components/CompanyRail.tsx +++ b/ui/src/components/CompanyRail.tsx @@ -122,6 +122,7 @@ function SortableCompanyItem({ > + mutationFn: (data: { + name: string; + description?: string | null; + budgetMonthlyCents?: number; + }) => companiesApi.create(data), onSuccess: (company) => { queryClient.invalidateQueries({ queryKey: queryKeys.companies.all }); @@ -94,7 +98,11 @@ export function CompanyProvider({ children }: { children: ReactNode }) { }); const createCompany = useCallback( - async (data: { name: string; description?: string | null; budgetMonthlyCents?: number }) => { + async (data: { + name: string; + description?: string | null; + budgetMonthlyCents?: number; + }) => { return createMutation.mutateAsync(data); }, [createMutation], diff --git a/ui/src/pages/CompanySettings.tsx b/ui/src/pages/CompanySettings.tsx index 95ba1d75..225b7398 100644 --- a/ui/src/pages/CompanySettings.tsx +++ b/ui/src/pages/CompanySettings.tsx @@ -1,9 +1,10 @@ -import { useEffect, useState } from "react"; +import { ChangeEvent, useEffect, useState } from "react"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { useCompany } from "../context/CompanyContext"; import { useBreadcrumbs } from "../context/BreadcrumbContext"; import { companiesApi } from "../api/companies"; import { accessApi } from "../api/access"; +import { assetsApi } from "../api/assets"; import { queryKeys } from "../lib/queryKeys"; import { Button } from "@/components/ui/button"; import { Settings, Check } from "lucide-react"; @@ -34,6 +35,8 @@ export function CompanySettings() { const [companyName, setCompanyName] = useState(""); const [description, setDescription] = useState(""); const [brandColor, setBrandColor] = useState(""); + const [logoUrl, setLogoUrl] = useState(""); + const [logoUploadError, setLogoUploadError] = useState(null); // Sync local state from selected company useEffect(() => { @@ -41,6 +44,7 @@ export function CompanySettings() { setCompanyName(selectedCompany.name); setDescription(selectedCompany.description ?? ""); setBrandColor(selectedCompany.brandColor ?? ""); + setLogoUrl(selectedCompany.logoUrl ?? ""); }, [selectedCompany]); const [inviteError, setInviteError] = useState(null); @@ -128,6 +132,42 @@ export function CompanySettings() { } }); + const syncLogoState = (nextLogoUrl: string | null) => { + setLogoUrl(nextLogoUrl ?? ""); + void queryClient.invalidateQueries({ queryKey: queryKeys.companies.all }); + }; + + const logoUploadMutation = useMutation({ + mutationFn: (file: File) => + assetsApi + .uploadCompanyLogo(selectedCompanyId!, file) + .then((asset) => companiesApi.update(selectedCompanyId!, { logoAssetId: asset.assetId })), + onSuccess: (company) => { + syncLogoState(company.logoUrl); + setLogoUploadError(null); + } + }); + + const clearLogoMutation = useMutation({ + mutationFn: () => companiesApi.update(selectedCompanyId!, { logoAssetId: null }), + onSuccess: (company) => { + setLogoUploadError(null); + syncLogoState(company.logoUrl); + } + }); + + function handleLogoFileChange(event: ChangeEvent) { + const file = event.target.files?.[0] ?? null; + event.currentTarget.value = ""; + if (!file) return; + setLogoUploadError(null); + logoUploadMutation.mutate(file); + } + + function handleClearLogo() { + clearLogoMutation.mutate(); + } + useEffect(() => { setInviteError(null); setInviteSnippet(null); @@ -224,11 +264,53 @@ export function CompanySettings() {
-
+
+ +
+ + {logoUrl && ( +
+ +
+ )} + {(logoUploadMutation.isError || logoUploadError) && ( + + {logoUploadError ?? + (logoUploadMutation.error instanceof Error + ? logoUploadMutation.error.message + : "Logo upload failed")} + + )} + {clearLogoMutation.isError && ( + + {clearLogoMutation.error.message} + + )} + {logoUploadMutation.isPending && ( + Uploading logo... + )} +
+
{generalMutation.error instanceof Error - ? generalMutation.error.message - : "Failed to save"} + ? generalMutation.error.message + : "Failed to save"} )}